var images_path = '/';

function addslashes(str) {
    str=str.replace(/\\/g,'\\\\');
    str=str.replace(/\'/g,'\\\'');
    str=str.replace(/\"/g,'\\"');
    str=str.replace(/\0/g,'\\0');
    return str;
}

function initPopupImage (path) {
    images_path = path;
    $('a.popup_image').each (function () {
        var url = $(this).attr ('href');
        var title = $(this).attr ('title');
        $(this).attr ('href', "javascript:popupImage ('"+url+"', '"+addslashes(title)+"')");
    });
}
    
function popupImage (url, title) {
    img_preloader = new Image();
	img_preloader.onload = function(){
        $("#popup_image").remove ();
                    
        // resize image if necessary
        var x = $(window).width() - 150;
        var y = $(window).height() - 150;
        var image_width = img_preloader.width;
		var image_height = img_preloader.height;
		if (image_width > x) {
			image_height = image_height * (x / image_width); 
			image_width = x; 
			if (image_height > y) { 
				image_width = image_width * (y / image_height); 
				image_height = y; 
			}
		} else if (image_height > y) { 
			image_width = image_width * (y / image_height); 
			image_height = y; 
			if (image_width > x) { 
				image_height = image_height * (x / image_width); 
				image_width = x;
			}
		}
		
        $("body").prepend ('<div id="popup_mask"></div><div id="popup_image"><h4>'+title+'<a href="javascript:popupImageClose();"><img src="'+images_path+'/cross.png" alt="close" /></a></h4><div id="popup_image_content" class="scroll-pane"><img src="'+url+'" width="'+image_width+'" height="'+image_height+'" /></div></div>');
        
        // popup position
        $("#popup_image").css ('left', (($(window).width()-$("#popup_image").width())/2)+'px');
        $("#popup_image").css ('top', (($(window).height()-$("#popup_image").height())/2)+$(window).scrollTop()+'px');
        
        // background mask
        $("#popup_mask").css ('height', $(document).height()+'px');
        $("#popup_mask").css ('width', $(document).width()+'px');
        $("#popup_mask").click (popupImageClose);
        $("#popup_image_content img").click (popupImageClose);
        
	};
	img_preloader.src = url;
}

function popupImageClose ()
{
    $("#popup_image").remove ();
    $("#popup_mask").remove ();
}
