/*!
 * slideViewerPro 1.0
 * Examples and documentation at: 
 * http://www.gcmingati.net/wordpress/wp-content/lab/jquery/svwt/
 * 2009 Gian Carlo Mingati
 * Version: 1.0.4 (12-AUGUST-2009)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires:
 * jQuery v1.3.2 or later
 * Option:
 * jQuery Timers plugin | plugins.jquery.com/project/timers (for autoslide mode)
 * 
 */
jQuery.extend(
	// from the jquery.easing plugin
	jQuery.easing, {
		easeInOutExpo: function (x, t, b, c, d) {
			if (t==0) return b;
			if (t==d) return b+c;
			if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
			return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
		}
	}
);

var j = 0;
jQuery.fn.slideViewerPro = function(settings) {
	settings = jQuery.extend({
		galBorderWidth: 6,
		thumbsTopMargin: 3, 
		thumbsRightMargin: 3,
		thumbsBorderWidth: 3,
		buttonsWidth: 20,
		galBorderColor: "#ff0000",
		thumbsBorderColor: "#d8d8d8",
		thumbsActiveBorderColor: "#ff0000",
		buttonsTextColor: "#ff0000",
		thumbsBorderOpacity: 1.0, // could be 0, 0.1 up to 1.0
		thumbsActiveBorderOpacity: 1.0, // could be 0, 0.1 up to 1.0
		easeTime: 750,
		asTimer: 4000,
		thumbs: 5,
		thumbsPercentReduction: 12,
		thumbsVis: true,
		easeFunc: "easeInOutExpo",
		leftButtonInner: "-", //could be an image "<img src='images/larw.gif' />" or an escaped char as "&larr";
		rightButtonInner: "+", //could be an image or an escaped char as "&rarr";
		autoslide: false,
		typo: false,
		typoFullOpacity: 0.9,
		shuffle: false
	}, settings);
		
	return this.each(
		function() {
			function shuffle(a) {
			    var i = a.size();
			    while (--i) {
			        var j = Math.floor(Math.random() * (i));
			        var tmp = a.slice(i, i+1);
			        a.slice(j, j+1).insertAfter(tmp);
			    }
			} 
			
			/**
			 * Aplica o posicionamento centralizado das imagens.
			 */
			function applyNewPosition(lis, pictWidth, pictHeight) {
				if (lis != null) {
			        for (var i = 0; i < lis.size(); i ++) {
			        	var li = $(lis.get(i));
			        	
			        	var imgs = li.find("img");
			        	for (var j = 0; j < imgs.size(); j ++) {
			        		var img = $(imgs.get(j));
			        		
			        		img.css("margin-top", calcMarginTop(img, pictHeight, pictWidth));
			        		
			        		var containerImg = img.parent();
			        		containerImg.css("position", "relative");
			        		containerImg.css("width", pictWidth);
			        		containerImg.css("height", pictHeight);
			        		containerImg.css("text-align", "center");
			        	}
			        }
		        }	
			}
			
			var container = jQuery(this);
			(!settings.shuffle) ? null : shuffle(container.find("li"));
			container.find("img.ldrgif").remove();
			container.removeClass("svwp").addClass("slideViewer");	
			container.attr("id", "svwp" + j);
			
	        var pictWidth = 0, pictHeight = 0;	        
	        if (settings.pictWidth == null 
	        		&& settings.pictHeight == null) {
	            container.find("img").each(
	        		function (pos, img) {
		                img = $(img);
		                pictWidth = Math.max(pictWidth, img.width()); 
		                pictHeight = Math.max(pictHeight, img.height()); 
		            }
	    		);
	        } else {
	            pictWidth = settings.pictWidth;
	            pictHeight = settings.pictHeight;
	        }
			
	        var lis = container.find("li");
	        
	        applyNewPosition(lis, pictWidth, pictHeight);       
	        
	        var pictEls = lis.size();	        
			(pictEls >= settings.thumbs) ? null : settings.thumbs = pictEls;
			var slideViewerWidth = pictWidth * pictEls;
			var thumbsWidth = Math.round(pictWidth * settings.thumbsPercentReduction/100);
			var thumbsHeight =  Math.round(pictHeight * settings.thumbsPercentReduction/100);
			var pos = 0;
			var r_enabled = true;
			var l_enabled = true;
			container
				.find("ul")
				.css("width", slideViewerWidth)
				.wrap(jQuery("<div style='width:" + pictWidth + "px; overflow: hidden; position: relative; top: 0; left: 0'>"));
			container.css("width" , pictWidth);
			container.css("height" , pictHeight);
			
			container.each(
				function(i) {
					function authorityMixing() {
						//right btt
						(pos == pictEls-settings.thumbs) ? jQuerybtr.addClass("r_dis") : jQuerybtr.removeClass("r_dis");
						(pos == pictEls-settings.thumbs) ? r_enabled = false : r_enabled = true;
						//left btt
						(pos == 0) ? jQuerybtl.addClass("l_dis") : jQuerybtl.removeClass("l_dis");
						(pos == 0) ? l_enabled = false : l_enabled = true;
					}
					
					function doThumbStructure(currentContainer, thumbsWidth, thumbsHeight) {
						currentContainer.find("li").each(
							function(n) {
								var srcImgThumb = jQuery(this).find("img").attr("src");
								var altImgThumb = jQuery(this).find("img").attr("alt");
								if (settings.resizeImg) {
				                    jQuery("div#thumbSlider" + j + " ul")
				                    	.append(
			                    			"<li style='width:" + thumbsWidth + "px; height: " + thumbsHeight + "px; padding: 0px;'>" + 
				                    			"<a title='" + altImgThumb + "' href='#' style='width:" + thumbsWidth + "px; height: " + thumbsHeight + "px; margin-top: 0px; padding: 0px;'>" +
				                    				"<div class='tmbrdr'>" +					                    				 
					                    				"<img onload='doLoadImgThumb(this, {width: " + (thumbsWidth - (settings.thumbsBorderWidth * 2)) + ", height: " + (thumbsHeight - (settings.thumbsBorderWidth * 2)) + "});' src='" + srcImgThumb + "' style='padding: 0px;' />" +
			                    					"</div>" +		                    				
				                    			"<\/a>" + 
			                    			"<\/li>");
								} else {
				                    jQuery("div#thumbSlider" + j + " ul")
				                    	.append(
			                    			"<li style='width:" + thumbsWidth + "px; height: " + thumbsHeight + "px; padding: 0px;'>" + 
				                    			"<a title='" + altImgThumb + "' href='#' style='width:" + thumbsWidth + "px; height: " + thumbsHeight + "px; margin-top: 0px; padding: 0px;'>" +
			                    					"<div class='tmbrdr'>" +					                    				
				                    					"<img onload='doLoadImgThumb(this, null);' width='" + thumbsWidth + "' height='" + thumbsHeight + "' src='" + srcImgThumb + "' style='padding: 0px;' />" +
			                    					"</div>" +				                    			
				                    			"<\/a>" + 
			                    			"<\/li>");
								}
							}
						);	
					}					
					
					if(settings.typo) {
						jQuery(this).find("img").each(
							function(pos, img) {
								
				                var imgWrapped = $(img);
				                
				                //
				                var typoWidth = settings.pictWidth - 12;
				                var typoHeight = 12;
				                
				                //
				                var newSpan = $("span#labelImg" + pos);
				                
				                newSpan.attr("class", "typo");
				                newSpan.css("width", typoWidth);
				                newSpan.css("height", typoHeight);
				                newSpan.append(imgWrapped.attr("alt"));
				                newSpan.css("position", "absolute");
				                newSpan.css("text-align", "left");				                
				                newSpan.css("padding", 6);
				                newSpan.css("background", "#000");
				                newSpan.css("color", "#FFF");
				                newSpan.css("font", "normal 10px Verdana");
				                newSpan.css("margin-right", 0);
				                newSpan.css("margin-bottom", 0);
				                newSpan.css("opacity", settings.typoFullOpacity);
				                
				                var newContainerSpan = newSpan.parent();
				                newContainerSpan.css("position", "absolute");
				                newContainerSpan.css("margin-right", 0);
				                newContainerSpan.css("margin-bottom", 0);	
				                newContainerSpan.css("margin-left", 0);
				                newContainerSpan.css("margin-top", -(newSpan.innerHeight()));
							}
						);
					}
				
					jQuery(this).after("<div class='thumbSlider' id='thumbSlider" + j + "'><ul><\/ul><\/div>");
					jQuery(this).next().after("<a href='#' class='left' id='left" + j + "'><span>" + settings.leftButtonInner + "</span><\/a><a href='#' class='right' id='right" + j + "'><span>"+settings.rightButtonInner+"<\/span><\/a>");
					
					// Monta cada item do thumbnail.
					doThumbStructure($(this), thumbsWidth, thumbsHeight);				
				
					jQuery("div#thumbSlider" + j + " a")
						.each(
							function(z) {			
								jQuery(this).bind("click", function() {
									jQuery(this)
										.find("div.tmbrdr")
											.css(
												{
													borderColor: settings.thumbsActiveBorderColor, 
													opacity: settings.thumbsActiveBorderOpacity
												});
									jQuery(this)
										.parent()
											.parent()
												.find("div.tmbrdr")
													.not(jQuery(this).find("div.tmbrdr"))
														.css(
															{
																borderColor: settings.thumbsBorderColor, 
																opacity: settings.thumbsBorderOpacity
															});
									var cnt = -(pictWidth * z);
									(cnt != container.find("ul").css("left").replace(/px/, "")) ? container.find("span.typo")
										.animate(
											{
												"opacity": 0
											}, 
											0) : null;
									container.find("ul")
										.animate(
											{ 
												left: cnt
											}, 
											settings.easeTime, 
											settings.easeFunc, 
											function() { 
												container.find("span.typo")
													.animate(
														{
															"opacity": settings.typoFullOpacity
														}, 250)
											}
										);		
									return false;
								}
							);
						}
					);
					
					// shortcuts to +/- buttons
					var jQuerybtl = jQuery("a#left" + j);	
					var jQuerybtr = jQuery("a#right" + j);	
					
					// right/left
					jQuerybtr.bind("click", 
						function(){
							if (r_enabled) (pictEls-pos > settings.thumbs*2 || pictEls%settings.thumbs == 0)? pos += settings.thumbs : pos += pictEls % settings.thumbs;
							r_enabled = false;
							jQuery(this)
								.prev()
									.prev()
										.find("ul:not(:animated)")
											.animate(
												{ 
													left: -(thumbsWidth + settings.thumbsRightMargin) * pos
												}, 
												500,
												settings.easeFunc, 
												function() { 
													authorityMixing();
												}
											);					
							return false;
						}
					);
					
					jQuerybtl.bind("click", 
						function() {	
							if (l_enabled && pos!=0) (pictEls-pos > settings.thumbs || pictEls%settings.thumbs == 0)? pos -= settings.thumbs : pos -= pictEls % settings.thumbs;
							l_enabled = false;
							jQuery(this)
								.prev()
									.find("ul:not(:animated)")
										.animate(
											{ 
												left: -(thumbsWidth+settings.thumbsRightMargin)*pos
											}, 
											500, 
											settings.easeFunc,
											function() { 
												authorityMixing();
											}
										);			
							return false;
						}
					);
					
					//CSS	defs @ runtime
					var tBorder = settings.thumbsBorderWidth;					
					
					jQuery(".slideViewer a img").css({border: "0"});					
					jQuery("div#svwp"+ j).css({border: settings.galBorderWidth + "px solid " + settings.galBorderColor});
					
					var contBorder = settings.galBorderWidth;					
					if (jQuery.browser.msie
							&& settings.isModal) {
						$("#svwp" + j).css("left", "8px");
						contBorder += 8;
					}
					jQuery("div#thumbSlider" + j)
						.css(
							{
								position: "relative", 
								left: contBorder, 
								top: settings.thumbsTopMargin + "px", 
								width: settings.thumbs * thumbsWidth + ((settings.thumbsRightMargin * settings.thumbs) - settings.thumbsRightMargin), 
								height: thumbsHeight, 
								textAlign: "center", 
								overflow: "hidden", 
								margin: "0 auto"
							}
						);
					
					jQuery("div#thumbSlider" + j + " ul").css(
						{
							width: (thumbsWidth * pictEls) + settings.thumbsRightMargin * pictEls, 
							position: "relative"
						});
					jQuery("div#thumbSlider" + j + " ul li").css(
						{
							marginRight: settings.thumbsRightMargin,
							padding: 0
						}); 
							
					jQuery("div#thumbSlider" + j)
						.find("div.tmbrdr")
							.css(
								{
									position: "relative", 
									width: (thumbsWidth - tBorder * 2) + "px", 
									height: (thumbsHeight - tBorder * 2) + "px",
									border: settings.thumbsBorderWidth + "px solid " + settings.thumbsBorderColor, 
									opacity: settings.thumbsBorderOpacity,
									textAlign: "left"
								});
					
					var rbttLeftMargin = (pictWidth/2) + (jQuery("div#thumbSlider" + j).width()/2) + settings.thumbsRightMargin + contBorder;
					var lbttLeftMargin = (pictWidth/2) - (jQuery("div#thumbSlider" + j).width()/2) - (settings.buttonsWidth + settings.thumbsRightMargin) + contBorder;			
					var innerImgH = jQuery("a#right" + j + " span img").attr("height");
					
					jQuery("a#left" + j).css({display: "block", textAlign: "center", width: settings.buttonsWidth + "px" , height: thumbsHeight+"px",  margin: -(thumbsHeight-settings.thumbsTopMargin) +"px 0 0 "+lbttLeftMargin+"px", textDecoration: "none", lineHeight: thumbsHeight+"px", color: settings.buttonsTextColor});
					jQuery("a#right" + j).css({display: "block", textAlign: "center", width: settings.buttonsWidth + "px", height: thumbsHeight+"px" , margin: -(thumbsHeight) +"px 0 0 "+rbttLeftMargin+"px", textDecoration: "none", lineHeight: thumbsHeight+"px", color: settings.buttonsTextColor});			
					jQuery("a#left" + j + " span img").css({margin: Math.round((thumbsHeight/2)-(innerImgH/2))+"px 0 0 0"});
					jQuery("a#right" + j + " span img").css({margin: Math.round((thumbsHeight/2)-(innerImgH/2))+"px 0 0 0"});
		
					authorityMixing();
		
					if(settings.autoslide) {							
						var i = 1;
						
						jQuery("div#thumbSlider" + j).everyTime(settings.asTimer, "asld", function() {			
			  			jQuery(this).find("a").eq(i).trigger("click");
			  			if(i == 0)
			  			{
							pos = 0;
							l_enabled = false;
							jQuery("div#thumbSlider" + j).find("ul:not(:animated)").animate({ left: -(thumbsWidth+settings.thumbsRightMargin)*pos}, 500, settings.easeFunc, function(){authorityMixing();});
			  			}
			  			else l_enabled = true;
			  			
							(i%settings.thumbs == 0)? jQuery(this).next().next().trigger("click") : null;
							(i < pictEls-1)?	i++ : i=0;		  			
						});		
						
						//stops autoslidemode	
						jQuery("a#right" + j).bind("mouseup", function(){
							jQuery(this).prev().prev().stopTime("asld");
				    	});
							
						jQuery("a#left" + j).bind("mouseup", function(){
							jQuery(this).prev().stopTime("asld");	
						});
						jQuery("div#thumbSlider" + j + " a").bind("mouseup", function(){
							jQuery(this).parent().parent().parent().stopTime("asld");
						});
					}
					var uiDisplay = (settings.thumbsVis)? "block":"none";
					jQuery("div#thumbSlider" + j + ", a#left" + j + ", a#right" + j).wrapAll("<div style='width:"+ pictWidth +"px; display: "+uiDisplay+"' id='ui"+j+"'><\/div>");			
					jQuery("div#svwp"+ j + ", div#ui" + j).wrapAll("<div style='width:"+ pictWidth +"px'><\/div>");
					
				}			
			);
			(jQuery("div#thumbSlider" + j).width()+(settings.buttonsWidth*2) >= pictWidth)? alert("ALERT: THE THUMBNAILS SLIDER IS TOO WIDE! \nthumbsPercentReduction and/or buttonsWidth needs to be scaled down!") : null;
			
			j++;
		}
	);	
};

function calcMarginTop(img, maxHeight, maxWidth) {
	// Posicionamento baseado nas margens da imagens frente ao container na qual ela 
	// se encontra. No caso, a margem do topo da imagem é igual a metade da área total do
	// container menos a metade do tamanho da imagem.
	if ((maxHeight - img.height()) > 0) {
		var halfTotalHeight = maxHeight / 2;
		var halfImgHeight = img.height() / 2;
		return halfTotalHeight - halfImgHeight;
	} else {
		return 0;
	}
}

function doLoadImgThumb(img, thumbSizeData) {
	img = $(img);
	if (img != null
			&& thumbSizeData != null
			&& img.width() > 0
			&& img.height() > 0) {		
		
		// Ajusta o comprimento até que a razão da diferença entre o tamanho máximo e o comprimento da imagem seja um valor inteiro.
		var isLoading = true;
		do {
			resizeImg(img, thumbSizeData);			
			var horizontalMargin = (thumbSizeData.width - img.width()) / 2;						
			if (horizontalMargin % 1 == 0) {
				isLoading = false;
				if (horizontalMargin > 0) {
			    	img.css("margin-left", horizontalMargin + "px"); 
			    }
			} else {
				img.width(img.width() - 1);
			}
		} while(isLoading);
		
		// Ajusta a altura até que a razão da diferença entre o tamanho máximo e a altura da imagem seja um valor inteiro.
		var isLoading = true;
		do {
			resizeImg(img, thumbSizeData);
			
			var newMarginTopValue = calcMarginTop(img, thumbSizeData.height, thumbSizeData.width);
			
			if (newMarginTopValue % 1 == 0) {
				isLoading = false;
				if (newMarginTopValue > 0) {
			    	img.css("margin-top", newMarginTopValue + "px"); 
			    }
			} else {
				img.height(img.height() - 1);
			}
		} while(isLoading);
	}
}
