/*    4/01/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/>.
*/
// jquery no conflict. use $j or jQuery outside of ready function
var $j = jQuery.noConflict(); 
/* thanks to Antonio Terceiro for suggestion and implementation of the multi lang support*/
$j.iPikaChoose = {
	build : function(user_options)
	{
		var user_options;
		var defaults = {
			show_captions: true,
			slide_enabled: true,
			auto_play: true,
			show_prev_next: true,
			slide_speed: 5000,
			thumb_width: 73,
			thumb_height: 73,
			buttons_text: { play: "Play", stop: "Stop", previous: "Previous", next: "Next" },
			delay_caption: true,
			user_thumbs: false,
			per_page: 10
		};
		var action = {};

		return $j(this).each(
			function() {
				//bring in options
				var options = $j.extend(defaults, user_options);
				// grab our images
				var images = $j(this).children('li').children('img');
				//hide the images so the user doesn't see crap
				images.fadeOut(1);
				
				//save our list for future ref
				var ulist = $j(this);
				images.each(LoadImages);
				//start building structure
				$j(this).before("<div class='photos-wrapper'></div>");
				// houses eveything about the UL
				var main_div = $j(this).prev(".photos-wrapper");
				
				//add in slideshow elements when appropriate
				if(options.slide_enabled){
					//main_div.append("<div class='photo-play'></div>");
					var play_div = $j(this).prev(".photos-wrapper").children(".photo-play");
					play_div.html("<a class='photo_play_button'>" + options.buttons_text.play + "</a><a class='photo_stop_button'>" + options.buttons_text.stop + "</a>");
					play_div.fadeOut(1);
					var play_anchor = play_div.children('a:first');
					var stop_anchor = play_div.children('a:last');
				}
				//this div is used to make image and caption fade together
				main_div.append("<div class='photos'></div>");
				var sub_div = main_div.children(".photos");
				
				//the main image we'll be using to load
				sub_div.append("<img />");
				var main_img = sub_div.children("img");
				
				//create the caption div when appropriate
				if(options.show_captions){
					sub_div.append("<div class='photo-caption'></div>");
					var caption_div = sub_div.children(".photo-caption");
				}
				
				//navigation div ALWAYS gets created, its refrenced a lot				
				main_div.append("<div class='photo-navigation'></div>");
				var navigation_div = main_div.children(".photo-navigation");
				//fill in sub elements
				navigation_div.prepend("<a class='prev'>" + options.buttons_text.previous + "</a>  <a class='next'>" + options.buttons_text.next + "</a>");
				var previous_image_anchor = navigation_div.children('a:first');
				var next_image_anchor = navigation_div.children('a:last');
								

				// Page navigation
				var current_page = 1;
				var total_pages = jQuery("li",this).length % options.per_page == 0 ? Math.floor(jQuery("li",this).length/options.per_page) : Math.floor(jQuery("li",this).length/options.per_page) + 1;
				var pagination = "";
				for(var i=1;i<=total_pages;i++){ pagination += '<span><a href="#'+i+'">'+i+'</a></span>'; }
				var $page_nav = total_pages == 1 ? "" : jQuery('<div id="controls"><ul class="photo-navigation"><li class="prev">' + options.buttons_text.previous + '</li><li class="page-select">'+pagination+'</li><li class="next">' + options.buttons_text.next + '</li></ul></div>');
				
				//fill in sub elements
				//navigation_div.prepend("<a class='prev'>" + options.buttons_text.previous + "</a>  <a class='next'>" + options.buttons_text.next + "</a>");
				var previous_page_anchor = jQuery(".prev",$page_nav);
				var next_page_anchor = jQuery(".next",$page_nav);
				jQuery(this).after($page_nav);
				
				jQuery('.photo-navigation li.page-select a').bind("click",page_jump);
				
				
				//hide the navigation if the user doesn't want it
				if(!options.show_prev_next){
					navigation_div.css("display","none");
				}
				
				//playing triggers the loop for the slideshow
				var playing = options.auto_play;
				
				main_img.wrap("<a></a>");
				var main_link = main_img.parent("a");
				
				function LoadImages()
				{
					$j(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 w = $j(this).width();
						var h = $j(this).height();
						if(w===0){w = $j(this).attr("width");}
						if(h===0){h = $j(this).attr("height");}
						//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)
						if(rw<rh){
							//we'll use ratio later to scale and not distort
							var ratio = rh;
							var left = ((w*ratio-options.thumb_width)/2)*-1;
							left = Math.round(left);
							//set images left offset to match
							$j(this).css({left:left});
						}else{
							var 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;
							$j(this).css({top:top});
						}
						//use those ratios to calculate scale
						var width = Math.round(w*ratio);
						var height = Math.round(h*ratio);
						$j(this).css("position","relative");
						$j(this).width(width).height(height);
						var imgcss={
							width: width,
							height: height
						};
						$j(this).css(imgcss);					
						$j(this).hover(
							function(){$j(this).fadeTo(250,1);},
							function(){if(!$j(this).hasClass("photo-selected")){$j(this).fadeTo(250,0.4);}}
						);
						$j(this).fadeTo(250,0.4);	
						
						if($j(this).hasClass('photo-first')){
							$j(this).trigger("click",["auto"]);
						}
						
					});
				
					//clone so the on loads will fire correctly
					var newImage = $j(this).clone(true).insertAfter(this);
					
					$j(this).remove();
	
					//reset images to the clones
					images = ulist.children('li').children('img');
				}
			function activate()
			{
				//sets the intial phase for everything
				
				//image_click is controls the fading
				images.bind("click",image_click);
				//hiding refrence to slide elements if slide is disabled
				if(options.slide_enabled){
					if(options.auto_play){
						playing = true;
						play_anchor.hide();
						stop_anchor.show();
					}else{
						play_anchor.show();
						stop_anchor.hide();
					}
				}
				
				images.filter(":last").addClass("photo-last");
				images.filter(":first").addClass("photo-first");
				//css for the list
				var licss = {
					width: options.thumb_width+"px",
					height: options.thumb_height+"px",
					"list-style": "none",
					overflow: "hidden"
				};
				images.each(function(){
					$j(this).parent('li').css(licss);
					//fixes a bug where images don't get the correct display after loading
					if($j(this).attr('complete')==true && $j(this).css('display')=="none")
					{
						$j(this).css({display:'inline'});
					}
				});
				//previous link to go back an image
				previous_image_anchor.bind("click",previous_image);
				//ditto for forward, also the item that gets auto clicked for slideshow
				next_image_anchor.bind("click",next_image);	
				
				if(total_pages > 1) {
				//previous link to go back an image
				previous_page_anchor.bind("click",previous_page);
				//ditto for forward, also the item that gets auto clicked for slideshow
				next_page_anchor.bind("click",next_page);	
				}
				
			}//end activate function

			function image_click(event, how){
								
					var $li = jQuery(event.target).parent();					
					var index = $li.parent().children().index($li);	
					
					// figure out if new image is on a different page
					if(		(index % defaults.per_page == 0 && action.dir != "prev")
						|| 	(index % defaults.per_page == defaults.per_page - 1 && action.dir == "prev")
						||	(index == images.length-1 && action.dir == "prev")
						||	action.page == "prev"
						) {						
						if(total_pages > 1) {
							if(action.dir == "next" && action.page == "") { current_page++; current_page = current_page > total_pages ? 1 : current_page; }
							if(action.dir == "prev" && action.page == "") { current_page--; current_page = current_page < 1 ? total_pages : current_page; }							
							change_page($li,index);						
						}						
					}
					// reset all actions				
					action.dir = "";
					action.page = "";
					action.img = "";
				
					//catch when user clicks on an image Then cancel current slideshow
					if(how!="auto"){
						if(options.slide_enabled){
							stop_anchor.hide();
							play_anchor.show();
							playing=false;
						}
						main_img.stop();
						main_img.dequeue();
						if(options.show_captions)
						{
							caption_div.stop();
							caption_div.dequeue();
						}
					}
					//all our image variables
					if(options.user_thumbs)
					{		
						var image_source = $j(this).attr("ref");
					}else
					{
						var image_source = $j(this).attr("src");
					}
					var image_link = $j(this).attr("ref");
					var image_caption = $j(this).next("div").html();
								
					//fade out the old thumb
					images.filter(".photo-selected").fadeTo(250,0.4); 
					images.filter(".photo-selected").removeClass("photo-selected"); 
					//fade in the new thumb
					$j(this).fadeTo(250,1);
					$j(this).addClass("photo-selected");
					//fade the old image out and the new one in
					if(options.show_captions)
					{
						if(options.delay_caption)
						{
							caption_div.ClearTypeFadeOut({ speed: 500 });
						}
						caption_div.ClearTypeFadeOut({ speed: 500, callback: function(){
							caption_div.html(image_caption);
							caption_div.ClearTypeFadeIn({ speed: 800 });
						}});
					}
					
					main_img.fadeTo(500,0.05,function(){
						main_img.attr("src",image_source);
						main_link.attr("href", image_link);
						
						main_img.fadeTo(800,1,function(){
							if(playing){
								$j(this).animate({top:0},options.slide_speed, function(){
									//redudency needed here to catch the user clicking on an image during a change.
									if(playing){next_image_anchor.trigger("click",["auto"]);}
								});
							}
						});
					});
			}//end image_click function
			
			function next_image(event, how){
				action.dir = "next";				
				action.page = "";
				
				if(images.filter(".photo-selected").hasClass("photo-last")){
					images.filter(":first").trigger("click",how);
				}else{
					images.filter(".photo-selected").parent('li').next('li').children('img').trigger("click",how);
				}
			}//end next image function
			
			function previous_image(event, how){
				action.dir = "prev";				
				action.page = "";
				
				if(images.filter(".photo-selected").hasClass("photo-first")){
					images.filter(":last").trigger("click",how);
				}else{
					images.filter(".photo-selected").parent('li').prev('li').children('img').trigger("click",how);
				}
			}//end previous image function
			
			function next_page(event, how){
				
				action.dir = "next";
				action.page = "next";
				
				current_page++;				
				current_page = current_page > total_pages ? 1 : current_page;
				var show = ((current_page-1) * defaults.per_page);
				
				images.eq(show).trigger("click",how);

			}//end next page function
			
			function previous_page(event, how){
				action.dir = "prev";
				action.page = "prev";

				current_page--;			
				current_page = current_page < 1 ? total_pages : current_page;
				var show = (current_page-1) * defaults.per_page;
				
				images.eq(show).trigger("click",how);				
				
			}//end previous page function
			
			function page_jump() {				
				var $this = jQuery(this);				
				if($this.parent().is(".current")) { return false; }				
				current_page = $this.get(0).href.split("#")[1];
				var show = ((current_page-1) * defaults.per_page);		
				images.eq(show).trigger("click");		
				return false;			
			}
			
			function change_page($el,index) {	
			
				// hide them all				
				$el.parent().children().hide().each(function(i){
				
					// show the current page set
					if (action.page != "prev" && action.dir == "prev") {						
						// start is calculation different for last page in case not a full list
						// if index is last image ? first image is first image of last page : first image is index minus total of previous pages
						var start = index == images.length - 1 ? (total_pages - 1) * defaults.per_page : index - (total_pages - 1) * defaults.per_page;
						
						if(i >= start && i <= index) {							
							jQuery(this).show();							
						}	
						
					} else {
						if(i >= index && i < index + defaults.per_page) {
							jQuery(this).show();						
						}
					}															 
				});				
			
				// reset page from switch
				current_page = action.dir == "prev" ? current_page-- : current_page++;				
				$el.parent().next().find("li.page-select span").removeClass("current").eq(current_page-1).addClass("current");	
			
			}// end change page function
			
			function play_button(){
				main_div.hover(
					function(){play_div.fadeIn(400);},
					function(){play_div.fadeOut(400);}
				);
				play_anchor.bind("click", function(){
					main_img.stop();
					main_img.dequeue();
					if(options.show_captions)
					{
						caption_div.stop();
						caption_div.dequeue();
					}
					playing = true;
					next_image_anchor.trigger("click",["auto"]);
					$j(this).hide();
					stop_anchor.show();
				});
				stop_anchor.bind("click", function(){
					playing = false;
					$j(this).hide();
					play_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 $j.ipikachoose		
$j.fn.PikaChoose = $j.iPikaChoose.build;

(function($) {
    $.fn.ClearTypeFadeTo = function(options) {
        if (options)
                $(this)
                        .show()
                        .each(function() {
                                if (jQuery.browser.msie) {
                                        // Save the original background color
                                        $(this).attr('oBgColor', $(this).css('background-color'));
                                        // Set the bgColor so that bold text renders correctly (bug with IE/ClearType/bold text)
                                        $(this).css({ 'background-color': (options.bgColor ? options.bgColor : '#fff') })
                                }
                        })
                        .fadeTo(options.speed, options.opacity, function() {
                                if (jQuery.browser.msie) {
                                        // ClearType can only be turned back on if this is a full fade in or
                                        // fade out. Partial opacity will still have the problem because the
                                        // filter style must remain. So, in the latter case, we will leave the
                                        // background color and 'filter' style in place.
                                        if (options.opacity == 0 || options.opacity == 1) {
                                                // Reset the background color if we saved it previously
                                                $(this).css({ 'background-color': $(this).attr('oBgColor') }).removeAttr('oBgColor');
                                                // Remove the 'filter' style to restore ClearType functionality.
                                                $(this).get(0).style.removeAttribute('filter');
                                        }
                                }
                                if (options.callback != undefined) options.callback();
                        });
    };

    $.fn.ClearTypeFadeIn = function(options) {
        if (options)
                $(this)
                        .css({ opacity: 0 })
                        .ClearTypeFadeTo({ speed: options.speed, opacity: 1, callback: options.callback });
    };

    $.fn.ClearTypeFadeOut = function(options) {
        if (options)
                $(this)
                        .css({ opacity: 1 })
                        .ClearTypeFadeTo({ speed: options.speed, opacity: 0, callback: options.callback });
    };
})(jQuery);



$j(document).ready(function (){

	$j("#photos").PikaChoose();	
	
});
