/*    9/28/2009
		PikaChoose
	Jquery plugin for photo galleries
    Copyright (C) 2009 Jeremy Fry

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
/* thanks to Antonio Terceiro for suggestion and implementation of the multi lang support*/



jQuery.iPikaChoose = {
	build:function(user_options)
	{
		var defaults = {
			show_captions: false,
			slide_enabled: true,
			auto_play: false,
			show_prev_next: true,
			slide_speed: 5000,
			thumb_width: 90,
			thumb_height: 60,
			buttons_text: { play: "", stop: "", previous: "Previous", next: "Next" },
			delay_caption: true,
			user_thumbs: false
		};
		
		
		//--- declare local vars ------------------------------------
		//-----------------------------------------------------------
		var liID = 0;
		var zoomVal = 0;
		var zoomIncr = 40;
		var zoomStartW = 0;
		var zoomStartH = 0;
		var imagesArrayIndex = 0;
        var imagesArray = new Array();
		var imgCnt = 0;
		var imgCnt2 = 0;
		var zoomAdj = 0;
		var zoomPercent = 100;
		//-----------------------------------------------------------
		
		return jQuery(this).each(
			
			function() {
				function LoadImages()
				{					
					jQuery(this).bind("load", function()
					{	
						//had to make a seperate function so that the thumbnails wouldn't have problems
						//from beings resized before loaded, thus not h/w
						//delete hidden image to clean up things.
						jQuery(this).parent('div').prev().remove();
						images = jQuery(this).parents('ul').find('img');
						var w = jQuery(this).width();
						var h = jQuery(this).height();
						
						if(w===0){w = jQuery(this).attr("width");}
						if(h===0){h = jQuery(this).attr("height");}
						
						//---- load image info array --------------
						/*****
						if((imgCnt % 2) == 0)
						{
							var split_src = jQuery(this).attr('src').split('/');
							//imagesArray.push({imgname:split_src[split_src.length-1], w:w, h:h});  ////////console.log(" (70). src: " + split_src[split_src.length-1]);
							imagesArray
							//window.showStatus("["+imgCnt+"]("+ jQuery(this).attr('src')+ ") w: " + w + " h: " + h);
						}
						//window.showStatus("["+imgCnt+"]("+ jQuery(this).attr('src')+ ") w: " + w + " h: " + h);							
						imgCnt++;
						***/
											
						//grab a ratio for image to user defined settings
						var rw = options.thumb_width/w;
						var rh = options.thumb_height/h;
						
						//determine which has the smallest ratio (thus needing
						//to be the side we use to scale so our whole thumb is filled)
						var ratio;
						if(rw<rh)
						{
							ratio = rh;   //we'll use ratio later to scale and not distort
							var left = Math.round( ((w*ratio-options.thumb_width)/2)*-1); //left = Math.round(left);
							jQuery(this).css({left:left}); //set images left offset to match
						}
						else
						{
							ratio = rw;
							//you can uncoment this lines to have the vertical picture centered
							//but usually tall photos have the focal point at the top...
							//var top = ((h*ratio-options.thumb_height)/2)*-1;
							//var top = Math.round(top);
							var top = 0;
							jQuery(this).css({top:top});
						}
						
						//use those ratios to calculate scale
						var width = Math.round(w*ratio);
						var height = Math.round(h*ratio);
					
						jQuery(this).css("position","relative");
						jQuery(this).width(width).height(height);  /////////console.log("@@(88) 2. @@ width: " + width + " height: " + height);
						
						jQuery(this).css({ width:width, height:height});					
						jQuery(this).hover(
							function(){jQuery(this).fadeTo(250,1);},
							function(){if(!jQuery(this).hasClass("pika_selected")){jQuery(this).fadeTo(250,0.4);}}
						);
						jQuery(this).fadeTo(250,0.4);	
						
						if(jQuery(this).hasClass('pika_first')){ jQuery(this).trigger("click",["auto"]); }
					});
				
					//clone so the on loads will fire correctly
					var newImage = jQuery(this).clone(true).insertAfter(this);
					
					jQuery(this).hide();
	
					//reset images to the clones
					images = ulist.children('li').children('img');
					
				}//___endLoadImages___
				
				
				var options = jQuery.extend(defaults, user_options);		// bring in options
				var images = jQuery(this).children('li').children('img');  	// grab our images
				images.fadeOut(1);  									 	// hide the images so the user doesn't see crap
				var ulist = jQuery(this);									// save our list for future ref
				images.each(LoadImages);                                    // ////console.log(" (149).  imagesArray.length: " + images.length);
				
				//---- fill our images array w/ the original size dimensions ---------
				//--------------------------------------------------------------------
				$("#pikame li").each(function(index, value) 
				{
					var img = new Image();
					img.src = $(this).children("img:first").attr("src"); //window.showStatus("(each) W: " + img.width + " H: "+ img.height ); //$(this).children("img:first").width );     ///children("img:first")
                    imagesArray.push({imgname:img.src, w:img.width, h:img.height});
				});
				//--------------------------------------------------------------------
				
							
				jQuery(this).before("<div class='pika_main'></div>");	// start building structure
				var main_div = jQuery(this).prev(".pika_main");   		// houses eveything about the UL
				
				//this div is used to make image and caption fade together
				main_div.append("<div id='sub_div' class='pika_subdiv'></div>");
				var sub_div = main_div.children(".pika_subdiv");
				
				//the main image we'll be using to load
				sub_div.append("<img id='pika_back_img' class='pika_back_img'/><img id='pika_main_img' class='pika_main_img' />");
				var main_img = sub_div.children("img:last");  
				var back_img = sub_div.children("img:first");
				
				//build custom overlays. These will use navigation div
				sub_div.append("<div class='pika_prev_hover'></div><div class='pika_next_hover'></div>");
				var prevHover = sub_div.find('.pika_prev_hover');
				var nextHover = sub_div.find('.pika_next_hover');
				prevHover.hide();
				nextHover.hide();
				
				//navigation div ALWAYS gets created, its refrenced a lot				
				jQuery(this).after("<div class='pika_navigation'></div>");
				var navigation_div = jQuery(this).next(".pika_navigation");
				
				//fill in sub elements
				navigation_div.prepend("<a class='nav_link_font'>" + options.buttons_text.previous + " :</a>  <a class='nav_link_font'>: " + options.buttons_text.next + "</a>");
				var previous_image_anchor = navigation_div.children('a:first');
				var next_image_anchor = navigation_div.children('a:last');
				jQuery(this).after("<div class='pika_footer'></div>");
				
				if(!options.show_prev_next){ navigation_div.css("display","none"); }  //hide the navigation if the user doesn't want it
				
				main_img.wrap("<a></a>");
				var main_link = main_img.parent("a");
				
			
			function activate()   //sets the intial phase for everything
			{				
				images.bind("click", image_click);    //image_click is controls the fading
				
				$("#zoom_in").bind("click", img_zoom_in);
				$("#zoom_out").bind("click", img_zoom_out);
				
				ulist.children("li:last").children("img").addClass("pika_last");
				ulist.children("li:first").children("img").addClass("pika_first");
				ulist.children("li").each(function(){ jQuery(this).children("span").hide(); });
				
				var divcss = {width:options.thumb_width+"px",height: options.thumb_height+"px","list-style": "none",overflow: "hidden"}; //css for the list
				var licss = {"list-style": "none",overflow: "hidden"};
				
				images.each(function(){
					jQuery(this).parent('li').css(licss);
					jQuery(this).wrap(document.createElement("div"));
					jQuery(this).parent('div').css(divcss);
					
					if(jQuery(this).attr('complete')===true && jQuery(this).css('display')=="none"){ jQuery(this).css({display:'inline'}); }  //fixes a bug where images don't get the correct display after loading
				});
				
				
				previous_image_anchor.bind("click",previous_image); //previous link to go back an image
				prevHover.bind("click",previous_image);				//ditto for forward, also the item that gets auto clicked for slideshow	
				next_image_anchor.bind("click",next_image);
				nextHover.bind("click",next_image);	
				//enable mouse tracking for the hover
				sub_div.mousemove(function(e)
				{
					var w = sub_div.width();
					var x = e.pageX - sub_div.offset().left;
   				});
   				sub_div.mouseleave(function(){ prevHover.fadeOut('fast');nextHover.fadeOut('fast'); });

			}//___activate___


			function image_click(event, how)
			{			
				liID = $(this).parent().parent().prevAll().length; //get the id of the LI element 
				
				//catch when user clicks on an image Then cancel current slideshow
				if(how!="auto")
				{
					main_img.stop();
					main_img.dequeue();
				}
				
				var image_source = (options.user_thumbs) ? jQuery(this).attr("ref") : this.src; //load first/next large image  
									
								
				var image_link = jQuery(this).attr("rel");
				var image_caption = jQuery(this).parent().next("span").html();
				
				//---- fade out the old thumb ---
				images.filter(".pika_selected").fadeTo(250,0.4); 
				images.filter(".pika_selected").removeClass("pika_selected"); 
				
				//---- fade in the new thumb ---- 
				jQuery(this).fadeTo(250,1);            
				jQuery(this).addClass("pika_selected");
				
				//set back imge = main_img
				var delay = 100;
				if(main_img.attr('opacity') < 0.8){ delay = 500; }
				back_img.attr("src", main_img.attr("src"));
				
				main_img.fadeTo(delay,0.00,function()
				{
					//make the image fade in on load, which should hopefully get rid of any jumping
					main_img.unbind('load');
								
					main_img.bind('load',function()
 					{
						main_img.fadeTo(800,1,function(){ back_img.attr("src", main_img.attr("src")); });   //reset it here to catch initial load.
						
						if(zoomVal > 0)
						{
							$(main_img).width(imagesArray[liID].w);
							$(main_img).height(imagesArray[liID].h);
							$(back_img).width(imagesArray[liID].w)
							$(back_img).height(imagesArray[liID].h);
						}
						
						//$(main_img).center1(imagesArray[liID].w, imagesArray[liID].h);
						//$(back_img).center1(imagesArray[liID].w, imagesArray[liID].h);
						
						//$(main_img).alignTop();
						//$(back_img).alignTop();
						
						zoomVal = 0;
						zoomStartW = 0;
						zoomStartH = 0;
						$("#zoom_out").hide();
					});
					
					//---- reset defaults -------------------
				   /*$("#pika_back_img").width(imagesArray[liID].w);
				   $("#pika_back_img").height(imagesArray[liID].h); 
                   
				   $("#pika_main_img").width(imagesArray[liID].w);   
				   $("#pika_main_img").height(imagesArray[liID].h); 
				   */
				   $(this).reset_defaults(imagesArray[liID].w, imagesArray[liID].h);
					//---------------------------------------
					
					main_img.attr("src",image_source);  // set to new image
					main_link.attr("href", image_link);
					  
				});
					
			}//___image_click___
			
			
			jQuery.fn.reset_defaults = function(w, h) 
			{
				$("#pika_back_img").width(w);
				$("#pika_back_img").height(h); 
				$("#pika_main_img").width(w);   
				$("#pika_main_img").height(h); 
				$(sub_div).css("left", 0);
				$(sub_div).css("top", 0);
				zoomStartW = $("#pika_main_img").width();   
				zoomStartH = $("#pika_main_img").height(); 
			}
			
			/*
			jQuery.fn.center1 = function(w, h) 
			{
				////console.log("(before): " + this.offset().left + " thisW: " + this.width() + " origW: " + w + " offset: " + $(".pika_main").offset().left + " subOff: " + $(".sub_main").offset().left); 
				window.showStatus( "(before): pmW: " + $(main_div).offset().left  + " sub_divL: "  + $(sub_div).offset().left + " sub_divtop: " + $(sub_div).offset().top + " mainDivTop: " + $(main_div).offset().top + "  w: " + w + " h: " + h);  //+ " thisW: " + this.width() + " origW: " + w + " offset: " + $(".pika_main").offset().left + " subOff: " + $(".sub_main").offset().left );
				//window.showStatus( "(before): pmW: " + $(main_div).offset().left 
				//this.css("position","relative");
				$(sub_div).css("left", 0  );
				$(sub_div).css("top", 0 );
				//var top_x = ($(".pika_main").offset().left - this.offset().left); ///100; //(600-w)/2;
				//this.css("left", "100px");
				//this.css("left","-100px");
				//
				//this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
				//this.css("left", ( $(".pika_main").width()  - this.width() ) / 2) +$(window).scrollLeft() + "px");
				//this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
			    
				////console.log("after: " +this.offset().left ); 
			    
				//---- original ****
				//
				// this.css("position","relative");
				// this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
				// this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
				// 
			    // return this;
			}
			*/
			
			function next_image(event, how){
				if(images.filter(".pika_selected").hasClass("pika_last")){ images.filter(":first").trigger("click",how); }
				else{ images.filter(".pika_selected").parents('li').next('li').find('img').trigger("click",how); }
			}
			
			function previous_image(event, how){
				if(images.filter(".pika_selected").hasClass("pika_first")){images.filter(":last").trigger("click",how);}
				else{images.filter(".pika_selected").parents('li').prev('li').find('img').trigger("click",how);}
			}
			
			
			function img_zoom_in(event, how)
			{	
			    if(zoomVal != (zoomIncr*10))
				{ 
					///window.showStatus("zoomVal: " + zoomVal + " calc: " + (zoomIncr*10) );
					zoomVal = (zoomVal + zoomIncr);
					$("#zoom_out").show();
					if(zoomVal == (zoomIncr*10)){ $("#zoom_in").hide(); }
				
					var width = ($("#pika_main_img").width() + zoomVal);
					var height = ($("#pika_main_img").height() + zoomVal); 
					$("#pika_back_img").hide();
					$("#pika_main_img").animate({width:width, height:height}, 400);
					$("#pika_back_img").animate({width:width, height:height}, 400);
					$("#pika_back_img").show();
				}
			}
			
			function img_zoom_out()
			{
				if(zoomVal != 0)
				{ 
					var width = ($("#pika_main_img").width() - zoomVal);
					var height = ($("#pika_main_img").height() - zoomVal);
					zoomVal = (zoomVal - zoomIncr);
					zoomVal == 0 ?  $("#zoom_out").hide() : $("#zoom_out").show();
					$("#zoom_in").show();
					$("#pika_back_img").hide();
					$("#pika_main_img").animate({width:width, height:height}, 400);
					$("#pika_back_img").animate({width:width, height:height}, 400);
					$("#pika_back_img").show();
				}
			}
			
			/*
			function img_zoom_in(event, how){	
				$("#zoom_out").show();
				if(zoomPercent == 190){ $("#zoom_in").hide(); }
				zoomAdj = zoomAdj+5;
				zoomPercent = zoomPercent+10;
				$("#pika_back_img").hide();
				$("#pika_main_img").animate({width:zoomPercent+"%", top:0, left:(zoomAdj*-1)+"%"}, 400);
				$("#pika_back_img").animate({width:zoomPercent+"%", top:0, left:(zoomAdj*-1)+"%"}, 400);
				$("#pika_back_img").show();
			}

			function img_zoom_out(){ 
				$("#zoom_in").show();
				if(zoomPercent == 110){$("#zoom_out").hide();}
				zoomAdj = zoomAdj-5;
				zoomPercent = zoomPercent-10;
				$("#pika_back_img").hide();
				$("#pika_main_img").animate({width:zoomPercent+"%", top:0, left:(zoomAdj*-1)+"%"}, 400);
				$("#pika_back_img").animate({width:zoomPercent+"%", top:0, left:(zoomAdj*-1)+"%"}, 400);
				$("#pika_back_img").show();
			}	
			*/
			activate();

		});//___end return this.each___
	}//___end build function____
};//___end jquery.ipikachoose___	

jQuery.fn.PikaChoose = jQuery.iPikaChoose.build;




