/**
* jQuery fancyzoom plugin.
* This is an adaptation of the fancyzoom effect as a jQuery plugin
*
* Author: Mathieu Vilaplana <mvilaplana@df-e.com>
* Date: March 2008
* rev: 1.0

TODO:
- HOTOVO - pri rozkliknutem obrazku nejde kliknout na jiny v carouselu 
- HOTOVO - pri kliku na obrazek v rozbalene galerii menit hash
- opravit adjustHeights
- pri zpet rotovat carousel na misto, odkud se fotka rozbaluje

*/

var actualHash = "";
var actualHref="";
var actualAlt="";
var actualOpenedBoxCloseFunction;

(function($) {
	var strImgDir = 'ressources/';
	
	
	$.fn.fancyzoom = function(userOptions) {
	
		// ochrana proti zobrazeni stinu i po zruseni rozbaleni behem animace
		var readyToFinish = true;		
    	//the var to the image box div
    	var oImgZoomBox;
	 	
  		var oImgClose = $('<div>').addClass('fancyzoom-img-close');
		var oImgLoader= $('<div>').addClass('fancyzoom-img-loader');
  			 
		var oImgZoomWrap;
		
		var images = new Array();
		var actualO;	
		var hashChangeCounter = 0;	
		
		if ($.fn.carouselInit!==undefined)
			var carousels_opts = $.fn.carouselInit.r[$.fn.fancyzoom.defaultsOptions.carouselOptsId];
		
		function callHashInit() {
			$.fn.initHashCallback(function(hash){
				//alert(actualHash)
				hashChangeCounter++;
				//console.log(hashChangeCounter);
				//console.log(actualHash+"########"+hash);
				
				var podminka = actualHash!=hash && images.length>0 && !manualHashChange
				
				if (podminka) { //actualHash!=hash && images.length>0  && !manualHashChange) {
					
					if (hash=="closed" || hash=="") {
						if (actualHash!="") {							
							closeZoomBox(actualO);
						}
					} else {
						// find new image url				
						//console.log(actualO);									
						for (var i=0; i<images.length; i++) {
												
							if (hash==images[i][0] && actualHref!=images[i][1]) {																			
								var $context;
								if ($.fn.fancyzoom.defaultsOptions.carousel) {
									$context = $('#'+carousels_opts.carouselMain.carouselId);									
								} else {
									$context = $('body');
								}	
								
								$("a[href="+images[i][1]+"]",$context).trigger('click');															
							}
						}
					}
				}		
				manualHashChange = false;				
			},250,true);
		}
		
		function openZoomBox(elLink,o){			
			document.location.hash = getHash(actualAlt, actualHref);
			actualHash = getHash(actualAlt, actualHref);
			//alert('changing hash');			
			// reset closeBox funtion target after gallery scroll
			$.fn.fancyzoom.defaultsOptions.dimOri = undefined;
			if (o.carousel) {
				carousels_opts.carouselMain.scrollBuffer = -1;
			
				actualOpenedBoxCloseFunction = function(){
					$('.carousel-expanded').appendTo(carousels_opts.carouselMain.parent);
					$('.fancyzoom-img-zoom-box, .fancyzoom-img-close').empty().remove();
					$('.carousel-expanded').hide();
					if (o.carousel) { 
						if (carousels_opts.carouselMain.scrollBuffer!=-1) {
							carousels_opts.carouselMain.carousel.scroll(carousels_opts.carouselMain.scrollBuffer);
						}
						carousels_opts.carouselExpanded.scrollBuffer = -1;
						//console.log($.fn.carouselInit.defaultsOptions.scrollBuffer+'--'+$.fn.carouselInit.defaultsOptions.carousel.offset);
						//console.log($.fn.carouselInit.defaultsOptions.carousel);
						// set animation target after gallery scroll
						if ($.fn.fancyzoom.defaultsOptions.dimOri!==undefined && carousels_opts.carouselMain.scrollBuffer==-1) {
							o.dimOri = $.fn.fancyzoom.defaultsOptions.dimOri;
						}				
					}
					//closeZoomBox(o);
				};
			}
			
			readyToFinish = true;
            //calculate the start point of the animation, it start from the image of the element clicked
            pos=$('img',elLink).offset();
			o=$.extend(o,{dimOri:{width:$('img',elLink).outerWidth(),height:$('img',elLink).outerHeight(),left:pos.left,top:pos.top,'opacity':0}});
			
			//calculate the end point of the animaton
			oImgZoomBox.attr('id','zoom-box').css({'opacity':0}).appendTo('body');
			if (o.carousel) { 
				// projit otevrene zoomBoxy a zavrit je
				/*
				for (var i=0; i<$.fn.carouselInit.r.length; i++) {
					var r = $.fn.carouselInit.r[i];
					if (r!==undefined) {
						if (r.carouselMain.closeZoomBoxFunction!==undefined) {
							r.carouselMain.closeZoomBoxFunction();
						}
					}						
				}
			*/
			
				if (o.carousel) {
					var carousel = $('<div>').attr('id','carousel').addClass('fancyzoom-carousel').appendTo(oContainer);
				
					var gal_opts = carousels_opts.carouselExpanded;
					$('#'+gal_opts.carouselId).show().appendTo('#carousel');			
					
					if (gal_opts.scrollBuffer!=-1) {
						gal_opts.carousel.scroll(gal_opts.scrollBuffer);
					}
				}
				/*
				carousels_opts.carouselMain.closeZoomBoxFunction = function(){
				
					closeZoomBox(o);
					//alert('run');
					carousels_opts.carouselMain.closeZoomBoxFunction = undefined;
				};*/
				
			}	
			
			// height zoomboxu se rovna max velikosti obrazku + velikost carouselu
			var iHeight = parseFloat(o.maxHeight) + parseFloat($('#carousel').outerHeight());
			var iWidth  = oImgZoomBox.outerWidth()+(oImgClose.height()/2);
			
			if (!o.carousel) {
				iWidth = oImgZoom.outerWidth();
				iHeight = oImgZoomBox.outerHeight();				
			}
			//console.log(iWidth);
			// vypopcitame procentuelni height objektu container, carousel a imgZoom
			var finalCarouselHeight  = $('#carousel').height();
			var finalImgWrapHeight = iHeight-finalCarouselHeight;
			var finalImgHeight = oImgZoom.height();
			
			oImgZoom.wrap(oImgZoomWrap);
			
			if (o.carousel) {
				oContainer.css('height','100%');
				$('#carousel').css('height',((finalCarouselHeight/iHeight)*100)+'%');
				$('#imgZoomWrap').css('height',((finalImgWrapHeight/iHeight)*100)+'%');
				oImgZoom.css('height',((finalImgHeight/finalImgWrapHeight)*100)+'%');
				oImgZoom.css({'top':((finalImgWrapHeight-finalImgHeight)/finalImgWrapHeight)*50+'%'});
			} else {
				$('#imgZoomWrap, #imgZoom, #container').css('height','100%');
			}
			
			
			
			
			if (o.carousel) { 
				iWidth = 700;
			} else {
				iWidth = iWidth +18;
			}
			if (o.youtube) {			
				iWidth = o.youtube_width;
				$('#carousel').css('height','0px');
				iHeight = o.youtube_height+17;
				
				if ($.browser.msie) {
					iHeight = o.youtube_height+15;
				}
				
				$('#imgZoomWrap').css({'background':'#000'});
				
				
				oImgZoom.css('height',90.1+'%');
				$('#container').css('padding','0px');
				iHeight = iHeight-18;
				
			}
			
			//the target is in the center without the extra margin du to close Image
			dimBoxTarget=$.extend({},{width:iWidth,height:iHeight,'opacity':1}, __posCenter((iWidth-15),(iHeight-15)));
			
            //place the close button at the right of the zoomed Image and add the close box action
                        
            oImgClose.css({left:(iWidth+dimBoxTarget.left-15),top:(dimBoxTarget.top-15)});
			
			if (o.youtube) {
				var offset = 10;
				if ($.browser.msie) {
					offset = 15;
				}
				oImgClose.css({left:(iWidth+dimBoxTarget.left-15),top:(dimBoxTarget.top-offset)});
			}
            oImgLoader.css({left:(iWidth/2+dimBoxTarget.left),top:(dimBoxTarget.top+oImgZoom.height()/2)});            
           /* if (!$.browser.msie) {				
				oImgClose.css({'left':parseFloat(oImgClose.css('left'))+15+"px"});
				oImgClose.css({'top':parseFloat(oImgClose.css('top'))-15+"px"});
			}*/
            var $fctEnd = function(){
            	
            	// aby se stin zobrazil az za doanimovanym prvkem
            	if (readyToFinish && (Math.abs(dimBoxTarget.top-oImgZoomBox.offset().top)<2) && (Math.abs(dimBoxTarget.left-oImgZoomBox.offset().left)<2)) {
            		if(o.Speed>0 && !$.browser.msie) {oImgClose.fadeIn('slow');}
						else {oImgClose.show();}
					if (o.pngShadow) {
						oContainer.pngShadow({
							shadow_css: {display:'none'},
							fx:			{opacity:'show'},
							fx_speed:	'default'
						});
					}
					if (o.youtube) {
						$('#imgZoom').hide();
						$('div.player#player-'+elLink.attr('rel')+':first object').appendTo('#imgZoomWrap');						

					}
					syncIframe();				
					//$('#imgZoomWrap').css({'height':'auto'});			
				}	
						
            };
  			if(o.Speed > 0) {
  				oImgZoomBox.css(o.dimOri).animate(dimBoxTarget,o.Speed,$fctEnd);  				
  			}
  			else {
  				oImgZoomBox.css(dimBoxTarget);
  				$fctEnd();
  			}
	 	 }//end openZoomBox
 	 	 
 	 	 /**
 	 	  * First hide the closeBtn, then remove the ZoomBox and the overlay
 	 	  * Animate if Speed > 0 
 	 	  */
 	 	 function closeZoomBox(o){ 	 
			$('#imgZoom').show();
 	 	 	if (o.youtube) {
				$('#imgZoom').show();
				$('#imgZoomWrap object').appendTo('.player#player-'+$('#imgZoomWrap object').attr('rel'));						
			}
 	 	 	manualHashChange = true;
	 	 	//$('#celek div').animate({'opacity':0});
	 	 	document.location.hash="closed"; 
//			actualO = undefined;					
			actualHash="";			
			actualHref = "";
			timerLoadingImg=null;
			actualOpenedBoxCloseFunction = undefined;
			
			
			if (o.carousel) { 
				if (carousels_opts.carouselMain.scrollBuffer!=-1) {
					carousels_opts.carouselMain.carousel.scroll(carousels_opts.carouselMain.scrollBuffer);
				}
				carousels_opts.carouselExpanded.scrollBuffer = -1;
				//console.log($.fn.carouselInit.defaultsOptions.scrollBuffer+'--'+$.fn.carouselInit.defaultsOptions.carousel.offset);
				//console.log($.fn.carouselInit.defaultsOptions.carousel);
				// set animation target after gallery scroll
				if ($.fn.fancyzoom.defaultsOptions.dimOri!==undefined && carousels_opts.carouselMain.scrollBuffer==-1 && $.fn.fancyzoom.defaultsOptions.dimOri.top!==undefined) {
					o.dimOri = $.fn.fancyzoom.defaultsOptions.dimOri;						
				}				
			}
			
	 	 	oImgClose.stop().hide().css('opacity',1);
	 	 	if (o.pngShadow) {oContainer.removePngShadow()};
		 	 if(o.Speed > 0){				 
		 	 	oImgZoomBox.animate(o.dimOri,o.Speed*2/3,function(){					
		 	 		if(userOptions.carousel) $('#'+carousels_opts.carouselExpanded.carouselId).appendTo(carousels_opts.carouselMain.parent).hide();		 	 		
			 		$(this).empty().remove();
			 		manualHashChange = false;
		 		});
				
	 	 	}else {
			 	oImgZoomBox.empty().remove();
				
	 	 	}	 	 	
 	 	 }
    		
		function getHash(alt, href) {
			
			alt = strtr(alt,"؊ݎةݮ '\\.:+&,/?","aacdeeeinoorstuuuyzAACDEEEINOORSTUUUYZaacdeeeinoorstuuuyzAACDEEEINOORSTUUUYZ-----------");
			
			var href_hash = href.split('&')[0].split('=')[1];
			if (href_hash === undefined) {
				href_hash = "";
			} else if (alt!="") {
				alt = alt.concat("-");
			}
			var hash = alt+href_hash;			
			
			return hash;
		}

		
		/**
		 * The plugin chain.
		 */
		 
		var ret = this.each(function() {
   			
   			var $this = $(this);
			//console.log(this);
			// do images array cause of hash recognition
			images.push(
				new Array(getHash($("img",this).attr('alt'),$(this).attr('href')), $(this).attr('href'))
			);		
			
			// build main options before element iteration		
	    	
	    	var opts = $.extend($.fn.fancyzoom.defaultsOptions||{}, userOptions||{},{dimOri:{}});
			
			
	    	//make action only on link that point to an href
   			/*{if(!/\.jpg|\.png|.gif/i.test($this.attr('href')) || $('img',$this).size()===0){
	   			return;
   			}*/
   			
   			var ret = $this.click(function(){
   				   				
   				if (userOptions.carousel) {
   					$('#'+carousels_opts.carouselExpanded.carouselId).hide().appendTo(carousels_opts.carouselMain.parent);
   				}
   					
   				var o = $.extend({},opts,userOptions);
   				// remove old shadow
				
				if ($('.fancyzoom-img-zoom-box').length>0 && o.youtube) {
					return false; 
				}
				
   				var oldImgZoom = $('#imgZoom');
				if (oldImgZoom.attr('id')=="imgZoom" && o.pngShadow) {
   					oContainer.removePngShadow();
   				}
								
				if(oLoading && oLoading.is(':visible') || timerLoadingImg){
   					//if user click on an other image, cancel the previous loading
					if(oImgZoomBox && $('img',oImgZoomBox).attr('src') != $(this).attr('href')){
	   					__cancelLoading();
					}
	   				else {//solve the double click pb
	   					return false;
	   				}
   				}
   				
				
					
					
				actualO = o;
				//if zoom box be shure to  close it
				if (actualOpenedBoxCloseFunction!=null && actualOpenedBoxCloseFunction!==undefined)
					actualOpenedBoxCloseFunction();
			
   				if(oImgZoomBox) {oImgZoomBox.empty().remove();}
   				// pri kliknuti na jiny carousel
   				
   				//$('.fancyzoom-img-zoom-box, .fancyzoom-img-close').empty().remove();
   				
				
 				//reset the img close and fix png on it if plugin available
				if($.ifixpng) {$.ifixpng(o.imgDir+'blank.gif');}
				oImgClose.appendTo('body');
					
				oImgLoader.appendTo('body').hide().attr('id','img-loader');
				
				if($.fn.ifixpng) {oImgClose.ifixpng();}
				oImgClose.hide().unbind('click').click(function(){closeZoomBox(o);});

				//reset zoom box prop and add image zoom with a margin top of 15px = imgclose height / 2  'margin-tops':(oImgClose.height()/2)+'px'
	    		oContainer  = $('<div>').attr('id','container').addClass('fancyzoom-container');
	    		oImgZoomBox = $('<div>').addClass('fancyzoom-img-zoom-box').empty().append(oContainer);
	    		
   				//oImgZoom=$('#celek').appendTo(oImgZoomBox).show();
   				
   				oImgZoom=$('<img>').attr('src',$(this).attr('href')).addClass('fancyzoom-img-zoom').click(function(){
   					closeZoomBox(o);
   					readyToFinish=false;
   				}).appendTo(oContainer).attr('id','imgZoom');
   				
   				oImgZoomWrap =  $('<div>').attr('id','imgZoomWrap');
   				
   				$(document).keypress(function(e){
   				    switch(e.which)  {  
                    	case 0:	closeZoomBox(o);
                        break;
                        case 27:	closeZoomBox(o);
                        break;                               
					}  
     			});  
     			
     			actualHref = oImgZoom.attr('src');
				actualAlt = $("img",this).attr('alt');
				
				//be shure that the image to display is loaded open the zoom box, if not display a loading Image.
   				var imgPreload = new Image();
   				imgPreload.src = $(this).attr('href');
   				
   				var $fctEndLoading = function(){
	   				if(__getFileName(imgPreload.src) == __getFileName($('img',oImgZoomBox).attr('src')) ){
	   					   					
		   				openZoomBox($this, o);
						oLoading.hide();
	   				}
   				};
   				if(imgPreload.complete)	{
   					openZoomBox($this, o);
   					
	   				//__displayLoading(imgPreload);
	   				//setTimeout($fctEndLoading,4000);;
   				}
	   			else {
	   				__displayLoading();
	   				imgPreload.onload = function(){
	   				
	   					//when loading is finish display the zoombox if user not click on cancel
	   					var $fcttime = function(){
	   						if(bCancelLoading) {bCancelLoading=false;}
	   						else {$fctEndLoading();}
	   					};
	   					$fcttime();
	   				 	//setTimeout($fcttime,4000);
	   				};
	   			}
          
   				return false;		
   			});
   		});
		// images array full, free way to handle hash
		callHashInit();
   		return ret;	
    };//end Plugin

    
    //Default Options
    $.fn.fancyzoom.defaultsOptions = {    	
    	Speed:450,    	
    	imgDir:strImgDir,
    	carousel:false,
    	pngShadow:true
 	 }; 	 
 	 
	function __posCenter(iWidth,iHeight){
		var iLeft = ($(window).width() - iWidth) / 2 + $(window).scrollLeft();
		var iTop = ($(window).height() - iHeight) / 2 + $(window).scrollTop();
		iLeft=(iLeft < 0)?0:iLeft;
		iTop=(iTop < 0)?0:iTop;		
	  		return {left:iLeft,top:iTop};
    }
    
    //
    // LOADING MANAGEMENT
    //
    var oLoading =null ;
	var bCancelLoading = false;
	var timerLoadingImg = null;
	function __displayLoading(){
		if(!oLoading){
			oLoading = $('<div>').addClass('fancyzoom-loading').css({opacity:8/10}).css(__posCenter(50,50)).html('<img  src="" />').attr('id','fancyzoom-loader').appendTo('body').click(function(){__cancelLoading();}).show();
		}
		else {
			oLoading.css(__posCenter(50,50)).show().html('<img src="'+$.fn.fancyzoom.defaultsOptions.imgDir+'blank.gif" />');
		}
		timerLoadingImg=setTimeout(__changeimageLoading,400);
	}
	function __cancelLoading(){
		bCancelLoading=true;
		oLoading.hide();
		if(timerLoadingImg){
			clearTimeout(timerLoadingImg);
			timerLoadingImg=null;
		}
	}
	
	/**
	 * Animate the png loading image.
	 */
	function __changeimageLoading(){
		if(!oLoading.is(':visible')){
			timerLoadingImg=null;
			return;
		}
		
		var $im=$('img',oLoading);
		//First call im.src ="", set it to the fire png zoom spin
		if(!$im.attr('src')){
			strImgSrc = $.fn.fancyzoom.defaultsOptions.imgDir+"zoom-spin-1.png";
		}
		//rotate the im src until 12
		else {
			tab = $im.attr('src').split(/[- .]+/);
			iImg = parseInt(tab[2]);
			iImg = (iImg < 12)? (iImg+1):1;
			strImgSrc= tab[0]+"-"+tab[1]+"-"+iImg+"."+tab[3];
		}
		var pLoad = new Image();
		pLoad.src=strImgSrc;
		var $fct = function (){
			oLoading.css(__posCenter(50,50));
			$im.attr('src',strImgSrc);
			timerLoadingImg = setTimeout(__changeimageLoading,100);
		};
		//to preserve bug if img not exist change it only if load complete.
		if(pLoad.complete){$fct();}
		else{pLoad.onload=$fct;}
	}
 	
 	function __getFileName(strPath){
 		if(!strPath) {return false;}
		var tabPath = strPath.split('/');
		return ((tabPath.length<1)?strPath:tabPath[(tabPath.length-1)]);		
 	}
 	

})(jQuery);

