
// Props to "soundphed" on engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript for
// the jQuery plugin onImagesLoaded
// Props to Alen Grakalic (http://cssglobe.com) for outline of the imagePreview

(function(){
	jQuery.fn.fixedCenter = function(){
		return this.each(function(){
			var element = jQuery(this), win = jQuery(window);
			centerElement();
			
			jQuery(window).bind('resize',function(){
				centerElement();
			});

			function centerElement(){
				var elementWidth, elementHeight, windowWidth, windowHeight, X2, Y2;
				    elementWidth = element.outerWidth();
				elementHeight = element.outerHeight();
				windowWidth = win.width();
				windowHeight = win.height();    
				X2 = (windowWidth/2 - elementWidth/2);
				Y2 = (windowHeight/2 - elementHeight/2);
				Y2 = Y2 < 10 ? 10 : Y2;
				jQuery(element).css({
					'left':X2+'px',
					'top':Y2+'px',
					'position':'absolute'
				});                     
			} //centerElement function
		});
	}
})();


jQuery.fn.onImagesLoaded = function(_cb) { 
  return this.each(function() {
 
    var $imgs = (this.tagName.toLowerCase()==='img')?$(this):$('img',this),
        _cont = this,
            i = 0,
    _done=function() {
      if( typeof _cb === 'function' ) _cb(_cont);
    };
 
    if( $imgs.length ) {
      $imgs.each(function() {
        var _img = this,
        _checki=function(e) {
          if((_img.complete) || (_img.readyState=='complete'&&e.type=='readystatechange') )
          {
            if( ++i===$imgs.length ) _done();
          }
          else if( _img.readyState === undefined ) // dont for IE
          {
            $(_img).attr('src',$(_img).attr('src')); // re-fire load event
          }
        }; // _checki \\
 
        $(_img).bind('load readystatechange', function(e){_checki(e);});
        _checki({type:'readystatechange'}); // bind to 'load' event...
      });
    } else _done();
  });
};


 
this.imagePreview = function(){	

	var skipme = null;

	$("a.preview").hover(function(e){
		if (this==skipme)
		{
			skipme = null;
			return;
		}
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("#preview").remove();
		$("#preview_loader").remove();
		var img = $(this).find("img");
		var sources=this.getAttribute('data-previewsrc').split(';');
		var imgs = '<img src="' + sources.join('"/><img src="') + '" />';
		$("body").append("<div id='preview' style='font-size: 1px'>" + imgs + c +"<div style='font-size: 10px' id='preview_caption'></div></div>");
		$("body").append("<div id='preview_loader'></div>");

		var popup=$("#preview");
		$(window).unload(function() { $("#preview").remove(); });
		var preview_caption = popup.find("#preview_caption");
		var images = popup.find('img');
		var backlink = this;
		images.css('cursor','pointer');
		if(images.size()>1){
			images.slice(1).hide();
			images.each(function(i,e) {
				$('<a class="preview_image_number" href="#">'+(i+1)+'</a>').
				appendTo(preview_caption)
					.hover( function(x) {
						if($(e).is(":visible"))
							return;
						images.hide();
						$(e).fadeIn("fast");
					})
					.click( function(x) {
						window.location = backlink.href;
						return false;
					});
			});
		}
		else {
			preview_caption.css('display','none');
		}
		var loader=$("#preview_loader");
		var centx = img.offset().left + img.width()/2;
		var centy = img.offset().top + img.height()/2;

		loader.css('position','absolute')
			.css('top',img.offset().top)
			.css('left',img.offset().left)
			.css('width',img.width())
			.css('height',img.height())
			.css('background-image','url("/loading2.gif")')
			.css('background-repeat','no-repeat')
			.css('background-position','center')
			.fadeTo(10,0.5)
			.click(function(e) { window.location = backlink.href; });
		
		popup.onImagesLoaded(function(e){
			var posx = centx - $(e).width()/2;
			var posy = centy - $(e).height()/2;
			if(posx<0){posx=0;}
			if(posy<0){posy=0;}
			loader.remove();
			$(e)
				.css("top",posy + "px")
				.css("left",posx + "px")
				.fadeIn("fast");						
	
			$(e).hover(function(e) {}, function(e){
				backlink.title=backlink.t;
				$(this).fadeOut("fast", function(e){$(this).remove();});
			});
			//$(e).click(function(e) { skipme=backlink; $(this).remove(); });
			$(e).click(function(e) { window.location = backlink.href; });
		});
    },
    function(e){});
};

function popZoom(images,first_selected)
{

	var zoomsources = images.split(";");

	var background = $('<div class="zoom-background"></div>').appendTo($('body'));
	var zoomed = $('<div class="zoomed"><div class="zoomed-closer"></div><img src="' + zoomsources[0] + '" /></div>').appendTo($('body'));
	var img = zoomed.find('img');
	var selected = parseInt(first_selected);
	setimg();
	if(zoomsources.length>1)
	{
		var selector = $('<div></div>').appendTo($(zoomed));
		$.each(zoomsources, function (i,elt) {
			$('<a class="preview_image_number" data-imgnum="'+i+'" href="#">' + (i+1) + '</a>')
				.appendTo($(selector))
				.click( function(x) {
					var n = this.getAttribute('data-imgnum');
					if(selected == n)
						return false;
					selected = n;
					setimg();
					return false;
				});
				
		});
	}
	$('.zoom-background').hide().fadeTo(10,0.4);
	zoomed.css("top","100px").css("left","100px")
		.fadeIn("slow")
		.draggable()
		.click(nextimg)
		.onImagesLoaded(function(e){$(e).fixedCenter();});
/*
	zoomed.find('div.zoomed-left').click(previmg);
	zoomed.find('div.zoomed-right').click(nextimg);
	zoomed.hover(
		function(e){zoomed.find('div.zoomed-left,div.zoomed-right').fadeIn('fast');},
		function(e){zoomed.find('div.zoomed-left,div.zoomed-right').fadeOut('fast');});
*/
	background.click(closeit);
	zoomed.find(".zoomed-closer").click(closeit);

	function closeit() {
		$(zoomed).remove();
		$('.zoom-background').remove();
	}

	function setimg()
	{
		img[0].src = zoomsources[selected];
		img.onImagesLoaded(function(){zoomed.fixedCenter();});
	}

	function nextimg() {
		selected = (selected + 1) % zoomsources.length;
		setimg();
	}
	function previmg() {
		selected = (selected + zoomsources.length - 1) % zoomsources.length;
		setimg();
	}
	
}

this.imageZoom = function(){	

	$("div.zoomable").each(function(i,e){
		var zoomed_images = e.getAttribute('data-zoomed-sources');
		var last_hover = 0;
		$(e).find('div.zoomable-thumbs').find('img').hover(
			function(x){
				$(e).find('div.zoomable-image img').hide();
				$(e).find('div.zoomable-image img').eq(this.getAttribute('data-imgidx')).fadeIn('fast');
				last_hover = this.getAttribute('data-imgidx');
			},
			function(x){ }
		)
			.click(function(x){popZoom(zoomed_images,this.getAttribute('data-imgidx'));});
		$(e).find('div.zoomable-image').click(function(x) { popZoom(zoomed_images, last_hover); });
		$(e).find('span.zoomable-zoom').click(function(x) { popZoom(zoomed_images, last_hover); });

    });
};


// starting the script on page load
$(document).ready(function(){
	imagePreview();
	imageZoom();
});

