/*    12/03/2008
		PikaChoose
	Jquery plugin for photo galleries
    Copyright (C) 2008 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/>.
*/


jQuery.iPikaChoose = {
	build : function(user_options)
	{
		var user_options;
		var defaults = {
			show_captions: true,
			show_prev_next: true,
			slide_speed: 5000,
			thumb_width: 50,
			thumb_height: 42
		};

		return jQuery(this).each(
			function() {
				//bring in options
				var options = jQuery.extend(defaults, user_options);
				// grab our images
				var jQueryimages = jQuery(this).children('li').children('img');
				//hide the images so the user doesn't see crap
				jQueryimages.fadeOut(1);
				//save our list for future ref
				var jQueryulist = jQuery(this);

				//start building structure
				jQuery(this).before("<div class='pika_main'></div>");
				// houses eveything about the UL
				var jQuerymain_div = jQuery(this).prev(".pika_main");
				
				//add in slideshow elements when appropriate
				if(options.slide_enabled){
					jQuerymain_div.append("<div class='pika_play'></div>");
					var jQueryplay_div = jQuery(this).prev(".pika_main").children(".pika_play");
					jQueryplay_div.html("<a class='pika_play_button'><img src='' alt='Play'></a><a class='pika_stop_button'></a>");
					jQueryplay_div.fadeOut(1);
					var jQueryplay_anchor = jQueryplay_div.children('a:first');
					var jQuerystop_anchor = jQueryplay_div.children('a:last');
				}
				//this div is used to make image and caption fade together
				jQuerymain_div.append("<div class='pika_subdiv'></div>");
				var jQuerysub_div = jQuerymain_div.children(".pika_subdiv");
				
				//the main image we'll be using to load
				jQuerysub_div.append("<img />");
				var jQuerymain_img = jQuerysub_div.children("img");
				
				//create the caption div when appropriate
				if(options.show_captions){
					jQuerysub_div.append("<div class='pika_caption'></div>");
					var jQuerycaption_div = jQuerysub_div.children(".pika_caption");
				}
				
				//navigation div ALWAYS gets created, its refrenced a lot				
				jQuery(this).after("<div class='pika_navigation'></div>");
				var jQuerynavigation_div = jQuery(this).next(".pika_navigation");
				//fill in sub elements
				jQuerynavigation_div.prepend("<a>Anterior</a> :: <a>Proxima</a>");
				var jQueryprevious_image_anchor = jQuerynavigation_div.children('a:first');
				var jQuerynext_image_anchor = jQuerynavigation_div.children('a:last');
				
				//hide the navigation if the user doesn't want it
				if(!options.show_prev_next){
					jQuerynavigation_div.css("display","none");
				}
				
				//jQueryplaying triggers the loop for the slideshow
				var jQueryplaying = options.auto_play;
				
				jQuerymain_img.wrap("<a></a>");
				var jQuerymain_link = jQuerymain_img.parent("a");
				
			function activate(){
				//sets the intial phase for everything
				
				//image_click is controls the fading
				jQueryimages.bind("click",image_click);
				//hiding refrence to slide elements if slide is disabled
				if(options.slide_enabled){
					if(options.auto_play){
						jQueryplaying = true;
						jQueryplay_anchor.hide();
						jQuerystop_anchor.show();
					}else{
						jQueryplay_anchor.show();
						jQuerystop_anchor.hide();
					}
				}
				
				//resizes and centers thumbs
				prep_thumbs();
				//previous link to go back an image
				jQueryprevious_image_anchor.bind("click",previous_image);
				//ditto for forward, also the item that gets auto clicked for slideshow
				jQuerynext_image_anchor.bind("click",next_image);	
			}//end activate function
			
	
			function prep_thumbs(){
					//now we know the first and last images
					jQueryimages.filter(":last").addClass("pika_last");
					jQueryimages.filter(":first").addClass("pika_first");
					//parse images
					jQueryimages.each(function(){
											var licss = {
							width: options.thumb_width+"px",
							height: options.thumb_height+"px",
							"list-style": "none",
							overflow: "hidden"
						};
						jQuery(this).parent('li').css(licss);
						jQuery(this).hover(
							function(){jQuery(this).fadeTo(250,1);},
							function(){if(!jQuery(this).hasClass("pika_selected")){jQuery(this).fadeTo(250,0.4);}}
						);
						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

							var jQueryw = jQuery(this).width();
							var jQueryh = jQuery(this).height();
							if(jQueryw===0){jQueryw = jQuery(this).attr("width");}
							if(jQueryh===0){jQueryh = jQuery(this).attr("height");}
							//grab a ratio for image to user defined settings
							var jQueryrw = options.thumb_width/jQueryw;
							var jQueryrh = options.thumb_height/jQueryh;
							
							//determine which has the smallest ratio (thus needing
							//to be the side we use to scale so our whole thumb is filled)
							if(jQueryrw<jQueryrh){
								//we'll use ratio later to scale and not distort
								var jQueryratio = jQueryrh;
								var jQueryleft = ((jQueryw*jQueryratio-options.thumb_width)/2)*-1;
								jQueryleft = Math.round(jQueryleft);
								//set images left offset to match
								jQuery(this).css({left:jQueryleft});
							}else{
								var jQueryratio = jQueryrw;
								//you can uncoment this lines to have the vertical picture centered
								//but usually tall photos have the focal point at the top...
								//var jQuerytop = ((jQueryh*jQueryratio-options.thumb_height)/2)*-1;
								//var jQuerytop = Math.round(jQuerytop);
								jQuerytop = 0;
								jQuery(this).css({top:jQuerytop});
							}
							//use those ratios to calculate scale
							var jQuerywidth = Math.round(jQueryw*jQueryratio);
							var jQueryheight = Math.round(jQueryh*jQueryratio);
							jQuery(this).css("position","relative");
							jQuery(this).width(jQuerywidth).height(jQueryheight);
							var imgcss={
								width: jQuerywidth,
								height: jQueryheight
							};
							jQuery(this).css(imgcss);					
							
							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
						jQuery(this).clone(true).insertAfter(this);
						
						jQuery(this).remove();
						//reset images to the clones
						jQueryimages = jQueryulist.children('li').children('img');
					});

			}//end fix thumbs functions
			function image_click(event, how){
					//catch when user clicks on an image Then cancel current slideshow
					if(how!="auto"){
						if(options.slide_enabled){
							jQuerystop_anchor.hide();
							jQueryplay_anchor.show();
							jQueryplaying=false;
						}
						jQuerysub_div.stop();
						jQuerysub_div.dequeue();
					}
					//all our image variables
					var jQueryimage_source = jQuery(this).attr("src");
					var jQueryimage_link = jQuery(this).attr("ref");
					var jQueryimage_caption = jQuery(this).attr("title");
								
					//fade out the old thumb
					jQueryimages.filter(".pika_selected").fadeTo(250,0.4); 
					jQueryimages.filter(".pika_selected").removeClass("pika_selected"); 
					//fade in the new thumb
					jQuery(this).fadeTo(250,1);
					jQuery(this).addClass("pika_selected");
					//fade the old image out and the new one in
					jQuerysub_div.fadeTo(500,0.05,function(){
						jQuerymain_img.attr("src",jQueryimage_source);
						jQuerymain_link.attr("href", jQueryimage_link);
						if(options.show_captions){jQuerycaption_div.html(jQueryimage_caption);}
					});
					jQuerysub_div.fadeTo(800,1,function(){
						if(jQueryplaying){
							jQuery(this).animate({top:0},options.slide_speed, function(){
								//redudency needed here to catch the user clicking on an image during a change.
								if(jQueryplaying){jQuerynext_image_anchor.trigger("click",["auto"]);}
							});
						}
					});
			}//end image_click function
			
			function next_image(event, how){
				if(jQueryimages.filter(".pika_selected").hasClass("pika_last")){
					jQueryimages.filter(":first").trigger("click",how);
				}else{
					jQueryimages.filter(".pika_selected").parent('li').next('li').children('img').trigger("click",how);
				}
			}//end next image function
			
			function previous_image(event, how){
				if(jQueryimages.filter(".pika_selected").hasClass("pika_first")){
					jQueryimages.filter(":last").trigger("click",how);
				}else{
					jQueryimages.filter(".pika_selected").parent('li').prev('li').children('img').trigger("click",how);
				}
			}//end previous image function
			
			function play_button(){
				jQuerymain_div.hover(
					function(){jQueryplay_div.fadeIn(400);},
					function(){jQueryplay_div.fadeOut(400);}
				);
				jQueryplay_anchor.bind("click", function(){
					jQueryplaying = true;
					jQuerynext_image_anchor.trigger("click",["auto"]);
					jQuery(this).hide();
					jQuerystop_anchor.show();
				});
				jQuerystop_anchor.bind("click", function(){
					jQueryplaying = false;
					jQuery(this).hide();
					jQueryplay_anchor.show();
				});
			}
			if(options.slide_enabled){play_button();}
			activate();

		});//end return this.each
	}//end build function
	
	//activate applies the appropriate actions to all the different parts of the structure.
	//and loads the sets the first image
};//end jquery.ipikachoose		
jQuery.fn.PikaChoose = jQuery.iPikaChoose.build;