/**
* 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
* rev: 1.1
* Add title if alt in the img
* rev 1.2
* Correction of the image dimension and close button on top right of the image
* rev 1.3
* now fancyzoom can be apply on an image, no need any more link wrapper
* rev 1.4 correct the bug for the overlay in ie6
* rev 1.6 (09/2009), lot of impovement, now image get out of its context.
*/

var elementsWithHandlers = new Array();

(function($) {

	$.fn.kitaFancyZoom = function(userOptions) {
		//the var to the image box div
	 	var oOverlay = $('<div>').css({
			height: '100%',
			width: '100%',
   			position:'fixed',
   			zIndex:100,
			left: 0,
			top: 0
			,cursor:"pointer"
		});

		function openZoomBox(imgSrc,o){
			if(o.showoverlay) {
				oOverlay.appendTo('body').click(function(){closeZoomBox(o);});
				if( $.browser.msie && $.browser.version < 7 ){
					oOverlay.css({position:'absolute',height:$(document).height(),width:$(document).width()});
				}
			}

			var oImgZoomBox = o.oImgZoomBox;
			var strTitle = o.title ? o.title : imgTarget.attr('alt');

			if(strTitle){
				var oTitle = $('<div class="kitaFancyZoomTitle">'+strTitle+'</div>').css({marginTop:10,marginRight:15});

				if(o.color && o.color != '' && o.color != 'undefined'){
					oTitle.css('color', o.color);
				}

				if(o.marginRight && o.marginRight != '' && o.marginRight != 'undefined'){
					oTitle.css('margin-right', o.marginRight);
				}

				oTitle.appendTo(oImgZoomBox);
			}

            		//calculate the start point of the animation, it start from the image of the element clicked
            		pos = imgSrc.offset();
			o=$.extend(o,{imgSrc:imgSrc,dimOri:{width:imgSrc.outerWidth(),height:imgSrc.outerHeight(),left:pos.left,top:pos.top,'opacity':1}});

			if(!imgSrc.is('img')){
				o.dimOri = $.extend(o.dimOri,{width:0,height:0});
			}

			//calculate the end point of the animaton
			oImgZoomBox.css({'text-align':'center','border':'0px solid red'}).appendTo('body');
			var iWidth = oImgZoomBox.outerWidth();
			var iHeight = oImgZoomBox.outerHeight();

			//the target is in the center without the extra margin du to close Image
			dimBoxTarget=$.extend({},{width:iWidth,height:iHeight,'opacity':1}, __posCenter((iWidth),(iHeight+30)));

            		var $fctEnd = function(){
            			//end of open, show the shadow
            			if($.fn.shadow && o.shadow && !$.browser.msie){ $('img:first',oImgZoomBox).shadow(o.shadowOpts);}

				if(o.Speed>0 && !$.browser.msie) {$('div',oImgZoomBox).fadeIn('slow');}
				else {$('div',oImgZoomBox).show();}
            		};


            		$('div',oImgZoomBox).hide();//cache le titre

            		//cache l'image source
            		if(o.imgSrc.is('img')){o.imgSrc.css({'opacity':0});}

            		var oImgDisplay = $('img:first', oImgZoomBox).css({'width':'100%','height':'auto'});

  			if(o.Speed > 0) {
  				oImgZoomBox.css(o.dimOri).animate(dimBoxTarget,o.Speed,$fctEnd);
  			} else {
  				oImgZoomBox.css(dimBoxTarget);
  				$fctEnd();
  			}

			oImgZoomBox.click(function(){closeZoomBox(o);});
		}//end openZoomBox

 	 	/**
 	 	 * First hide the closeBtn, then remove the ZoomBox and the overlay
 	 	 * Animate if Speed > 0
 	 	 */
		function closeZoomBox(o){
 	 	 	var oImgZoomBox = o.oImgZoomBox;
	 	 	$('div',oImgZoomBox).remove();

	 	 	var endClose = function(){
	 	 		oImgZoomBox.empty().remove();
	 	 		o.imgSrc.css('opacity',1);
	 	 	};

			if(o.Speed > 0){
				var pos = oImgZoomBox.offset();
		 	 	var iPercent = 0.15;
		 	 	var oDimPlus = {
		 	 		width:(oImgZoomBox.width()*(1+iPercent)),
		 	 		height:(oImgZoomBox.height()*(1+iPercent)),
		 	 		left:(pos.left-(oImgZoomBox.width()*(iPercent/2))),
		 	 		top:(pos.top-(oImgZoomBox.height()*(iPercent/2)))
		 	 	};

		 	 	oImgZoomBox.animate(oDimPlus,o.Speed*0.2,function(){
			 	 	oImgZoomBox.animate(o.dimOri,o.Speed,function(){endClose();});
					if(o.showoverlay) {oOverlay.animate({'opacity':0},o.Speed,function(){$(this).remove();});}
		 	 	});
	 	 	} else {
			 	endClose();
				if(o.showoverlay) {oOverlay.remove();}
			}
		}

		/**
		 * The plugin chain.
		 */
   		return this.each(function() {
   			var $this = $(this);
   			var imgTarget = $this.is('img') ? $this:($('img:first',$this).length==0) ? $this : $('img:first',$this);
   			var imgTargetSrc=null;
   			if($this.attr('href')) {imgTargetSrc = $this.attr('href');}

   			/**
   			 * We must check to see if the element we are looking at already has a handler associated with it.  If it does we do not want to
   			 * add another handler because if we do then when that element is clicked on, multiple lightboxes will be created.
   			 */
   			var elementsWithHandlersLength = elementsWithHandlers.length;
   			var alreadyFound = false;

   			for(var i=0;i<elementsWithHandlersLength;i++){
   				if(elementsWithHandlers[i] == imgTargetSrc){
   					alreadyFound = true;
   					break;
   				}
   			}

   			if(!alreadyFound){
   				elementsWithHandlers.push(imgTargetSrc);

				// build main options before element iteration
				var opts = $.extend({},$.fn.kitaFancyZoom.defaultsOptions, userOptions||{},{dimOri:{},
					oImgZoomBoxProp:{position:'absolute',left:0,top:0}
				});

				if($this.is('img')){
					imgTargetSrc = $this.css('cursor','pointer').attr('src');
				}

				oOverlay.css({
					opacity: opts.overlay,
					background:opts.overlayColor
				});

				//make action only on link that point to an image
				if( !/\.jpg|\.jpeg|\.png|\.gif/i.test(imgTargetSrc) ){
					return true;
				}

				$this.click(function(){
					var o = $.extend({},opts,userOptions);

					//remove the overlay and Reset
					if(o.showoverlay && oOverlay) {oOverlay.empty().remove().css({'opacity':o.overlay});}

					//reset zoom box prop and add image zoom with a margin top of 15px = imgclose height / 2
					var oImgZoomBox=$('<div class="jqfancyzoombox"></div>').css(o.oImgZoomBoxProp);
					o = $.extend(o,{oImgZoomBox:oImgZoomBox});

					var oImgZoom=$('<img />').attr('src',imgTargetSrc).click(function(){closeZoomBox(o);}).prependTo(oImgZoomBox);
					/** Manage zIndex **/
					var imagezindex= opts.imagezindex;
					oOverlay.css('zIndex', imagezindex-1);
					oImgZoomBox.css('zIndex',imagezindex);

					//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 = imgTargetSrc;
					var $fctEndLoading = function(){
						if(bCancelLoading) {bCancelLoading=false;}
						else {
							if(__getFileName(imgPreload.src) == __getFileName($('img:first',oImgZoomBox).attr('src')) ){
								fctCalculateImageSize(o.autoresize);
								openZoomBox(imgTarget, o);
							}
						}
					};
					var fctCalculateImageSize = function (autoresize) {
						//calcul de la taille de l'image
						if(autoresize){
							var divCalculate = $('<div></div>').css({position:'absolute','top':0,'left':0,opacity:0,'border':'0px solid red'});
							var bResize = false;
							oImgZoom.appendTo(divCalculate);
							divCalculate.appendTo('body');
							imWidth = oImgZoom.width();
							imHeight = oImgZoom.height();
							maxWidth = $(window).width()*0.9;
							maxHeight = $(window).height()-100;
							if( maxHeight < imHeight ){
								bResize = true;
								oImgZoom.height(maxHeight);
								imWidth= (imWidth*maxHeight)/imHeight;
								oImgZoom.width(imWidth);
								if( maxWidth < imWidth ){
									oImgZoom.width(maxWidth);
									oImgZoom.height(imHeight*maxWidth/imWidth);
								}
							}else if( maxWidth < imWidth ){
								bResize = true;
								oImgZoom.width(maxWidth);
								oImgZoom.height(imHeight*maxWidth/imWidth);
							}
							divCalculate.remove();
						}
						oImgZoom.prependTo(oImgZoomBox);
					};

					if(imgPreload.complete)	{
						fctCalculateImageSize(o.autoresize);
						openZoomBox(imgTarget, o);
						/*__displayLoading(imgPreload);
						setTimeout($fctEndLoading,4000);*/
					}
					else {
						imgPreload.onload = function(){
							//when loading is finish display the zoombox if user not click on cancel
							$fctEndLoading();
						};
					}
					return false;
				});
			}
   		}
   	);//end return this
    };//end Plugin


    //Default Options
    $.fn.kitaFancyZoom.defaultsOptions = {
    	overlayColor: '#000',
    	overlay: 0.6,
    	imagezindex:60,
    	showoverlay:true,
    	Speed:400,
    	shadow:true,
    	shadowOpts:{ color: "#000", offset: 4, opacity: 0.2 },
    	autoresize: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 bCancelLoading = false;

 	function __getFileName(strPath){
 		if(!strPath) {return false;}
		var tabPath = strPath.split('/');
		return ((tabPath.length<1)?strPath:tabPath[(tabPath.length-1)]);
 	}

})(jQuery);
