/**
 * uGallery jQuery plugin
 * Author: Miro Zoricak (zoricak at udesign.sk)
 * Website: http://zori.udesign.sk
 * v 1.0 beta
 */
(function($){
	var settings = {
		width: 420,
		height: 320,
		step:   51.5,//91.5,
		thumbWidth: 80,
		thumbHeight: 75,
		thumbOpacity: 0.5,
		thumbHoverOpacity: 1,
		displayAlt: true,
		site_path: "",
		imageCount: 0,
		currentImage: 0
	}
	
	$.uGallery = function(userSettings){
		settings.full_step = (((settings.thumbWidth + 10) * 6) + 6);
	
		var images = [];
		$.extend(settings, userSettings);
		// parse input structure to images
		$("ul.gal>li>img").each(function(index, element){
			settings.imageCount++;
			images[index] = $(element)
				.css({width: element.width+"px", height: element.height+"px"})
				.attr("src", $(element).attr("src"))
				.attr("alt", $(element).attr("alt"))
				.attr("title", settings.imageCount);
		});
		// recreate gallery structure using divs
		$("#loader").remove();
		
		if (settings.is_smartphone){
			$("ul.gal").replaceWith("<div class='gal'><div class='gal-thumbs-wrapper'><a href='#' id='right-move-button' onclick='rightMove(); return false;'><img id='rightArrow' src='" + settings.site_path + "/lib/js/right.png' alt='right'></a><div class='gal-thumbs'></div><a href='#' id='left-move-button' onclick='leftMove(); return false;' style='display:none'><img id='leftArrow' src='" + settings.site_path + "/lib/js/left.png' alt='left'></a></div><div class='gal-main-viewer'></div></div>");
		}else{
			$("ul.gal").replaceWith("<div class='gal'><div class='gal-thumbs-wrapper'><a href='#' id='right-move-button' onclick='rightMove(); return false;'><img id='rightArrow' src='" + settings.site_path + "/lib/js/right.png' alt='right'></a><div class='gal-thumbs'></div><a href='#' id='left-move-button' onclick='leftMove(); return false;' style='display:none'><img id='leftArrow' src='" + settings.site_path + "/lib/js/left.png' alt='left'></a></div><div class='gal-main-viewer'></div></div>");
//			$("ul.gal").replaceWith("<div class='gal'><div class='gal-thumbs-wrapper'><div class='gal-thumbs'></div></div><div class='gal-main-viewer'></div></div>");
		}
		for(var i = 0; i < images.length; i++){ // fill it with images
			$("div.gal-thumbs").append(makeThumb(images[i]));
		}
		
		$("div.gal-thumbs>img").wrap("<div class='gal-thumb'></div>");
		// display the first thumb image in main viewer
		$("div.gal-thumbs>div.gal-thumb:first>img").trigger('click');
		// style the gallery
		setupCSS(images);


		$(document).keydown(function (event) {
			if (!document.getElementById) return;
		
		    if (window.event) event = window.event;
	        switch (event.keyCode ? event.keyCode : event.which ? event.which : null)
	        {
	            case 0x25:
	                smallLeftMove();
	                break;
	            case 0x27:
					smallRightMove();
	                break;
	        }			
		})
		
		
		var thumbs = $("div.gal-thumbs");
		var offset = $("div.gal-thumbs-wrapper").offset().left;
		var viewWidth = settings.width;
		var contentWidth = parseInt(thumbs.width()) - viewWidth + settings.step + 0.5;
		// create thub strip moving behaviour on mousemove
		if (!settings.is_smartphone){
			$("div.gal-thumbs").bind("mousemove", function(e){
				var thumbs = $("div.gal-thumbs");
				
				var margin = -Math.round(contentWidth * ((e.clientX - offset)/viewWidth));
				
				if ((e.clientX - offset) < 30) {
					$("#left-move-button").hide();
				} else {
					$("#left-move-button").show();
				}
				
				if ((e.clientX - offset - $("div.gal-thumbs-wrapper").width()) > -30) {
					$("#right-move-button").hide();
				} else {
					$("#right-move-button").show();
				}

				thumbs.css({"margin-left": margin+"px"});	

			});
			
		}
		// fade thumbs to the initial state
		$("div.gal-thumb>img").fadeTo("slow", settings.thumbOpacity);
		// add thumb highlight onmouseover behaviour
		$("div.gal-thumb>img").hover(
			function(){ $(this).fadeTo("slow", settings.thumbHoverOpacity); }, 
			function(){ $(this).fadeTo("slow", settings.thumbOpacity); }
		);
	}

	
	/**
	 * crates proportionally resized image with onclick showing full image in image viewer
	 */
	makeThumb = function(img){
		var image = $("<img src='"+$(img).attr("src")+"' alt='"+$(img).attr("alt")+"' title='"+$(img).attr("title")+"' />");
		image.css(proportionalDimensions(img, {x: settings.thumbWidth, y: settings.thumbHeight}));
		image.css({msInterpolationMode: "bicubic"}); // smooth out thumbs in IE7
		image.bind("click", img, function(e){
			$("div.gal-thumb").css({"border-bottom-color": "#252525"});
			$(this).parent().css({"border-bottom-color": "white"});
			var image = $("<img src='"+$(img).attr("src")+"' alt='"+$(img).attr("alt")+"' />");
			image.css(proportionalDimensions(img, {x: settings.width - 20, y: settings.height - 20}));
			var alt = $("<div class='gal-alt'><p style='font-size:10pt;'>"+$(img).attr("alt")+"</p></div>");
			alt.css({
				clear: "both", 
				width: settings.width-40+"px", 
				padding: "10px", 
				"background-color": "black", 
				"margin": "auto",
				color: "white"
			});
			alt.fadeTo(0, 0.6);
			//$("div.gal-main-viewer").html(image).fadeOut("fast").fadeIn("slow").append(alt);			

			$("div.gal-main-viewer").fadeTo("fast",0.2).html(image);
			
			//sleep(600);

			$("div.gal-main-viewer").fadeTo("slow",1).append(alt);
			
			if(settings.displayAlt){
                        	$("div.gal-alt").animate({marginTop: "-"+(20+alt.height())+"px"}, 600);
                        }
			settings.currentImage = $(img).attr("title");
			return false;
		});	
		return image;
	}
	
	leftMove = function(){
		var thumbs = $("div.gal-thumbs");
		var contentWidth = parseInt(thumbs.css('width'));
		var viewWidth = settings.width;		
		var margin_left_old = parseInt(thumbs.css("margin-left"));
		margin_left_old = isNaN(margin_left_old) ? 0 : margin_left_old;
		var margin_left = margin_left_old +  settings.full_step;
		
		if (margin_left_old < 0)
		{
			if (margin_left < -0.5) {
				thumbs.css({"margin-left": margin_left+"px"});
				$("#right-move-button").show();
			}else{
				$("#left-move-button").hide();
				thumbs.css({"margin-left": "0px"});
			}
		}else{
			$("#left-move-button").hide();
		}
		return false;
	}
	
	rightMove = function(){
		var thumbs = $("div.gal-thumbs");
		var contentWidth = parseInt(thumbs.css('width'));
		var viewWidth = settings.width;		
		var margin_left_old = parseInt(thumbs.css("margin-left"));
		margin_left_old = isNaN(margin_left_old) ? 0 : margin_left_old;


		var margin_left = margin_left_old - settings.full_step;

		if (-margin_left < (contentWidth + settings.full_step - viewWidth))
		{
			$("#left-move-button").show();
			thumbs.css({"margin-left": margin_left+"px"});
		}
		if ((margin_left +  (contentWidth + settings.full_step - viewWidth)) < settings.full_step){
			$("#right-move-button").hide();
		}
		
		return false;
	}
	
	
	smallLeftMove = function(){
		
		if (settings.currentImage > 1) {
			settings.currentImage--;
			$("div.gal-thumbs>div.gal-thumb>img[title='"+(settings.currentImage)+"']").trigger('click');
			
			var thumbs = $("div.gal-thumbs");
			var contentWidth = parseInt(thumbs.css('width'));
			var viewWidth = settings.width;		
			var margin_left_old = parseInt(thumbs.css("margin-left"));
			margin_left_old = isNaN(margin_left_old) ? 0 : margin_left_old;
			var step = (settings.thumbWidth + 11)*(settings.currentImage-1)-((settings.thumbWidth + 11)*2);
			var margin_left = -step; 
			
			//if (margin_left_old < ((settings.thumbWidth + 11)*2))
			if (((settings.imageCount - settings.currentImage) < (settings.imageCount-2)) && ((settings.imageCount - settings.currentImage) > 2))
			{
				if (margin_left < -0.5) {
					thumbs.css({"margin-left": margin_left+"px"});
					$("#right-move-button").show();
				}else{
					$("#left-move-button").hide();
					thumbs.css({"margin-left": "0px"});
				}
			}else{
				$("#left-move-button").hide();
			}
				
		}
		return false;
	}
	
	smallRightMove = function(){
		
		if (settings.currentImage < settings.imageCount) {
			settings.currentImage++;
			$("div.gal-thumbs>div.gal-thumb>img[title='"+(settings.currentImage)+"']").trigger('click');
			
			
			var thumbs = $("div.gal-thumbs");
			var contentWidth = parseInt(thumbs.css('width'));
			var viewWidth = settings.width;		
			var margin_left_old = parseInt(thumbs.css("margin-left"));
			margin_left_old = isNaN(margin_left_old) ? 0 : margin_left_old;
			
			var step = (settings.thumbWidth + 11)*(settings.currentImage-1)-((settings.thumbWidth + 11)*2);
	
			var margin_left = -step;

			if (((settings.imageCount - settings.currentImage) < (settings.imageCount-2)) && ((settings.imageCount - settings.currentImage) > 2))
			{
				$("#left-move-button").show();
				thumbs.css({"margin-left": margin_left+"px"});
			}
			if ((margin_left +  (contentWidth + step - viewWidth)) < step){
				$("#right-move-button").hide();
			}
			
				
		}
		
		return false;
	}
	
	
	/**
	 * proportionally recalculates width and height of an image to fit the fitInto parameter
	 */
	proportionalDimensions = function(img, fitInto){
		if(typeof fitInto != "object"){
			fitInto.x = settings.thumbWidth;
			fitInto.y = settings.thumbHeight;
		}
		var _old = {x: parseInt($(img).css("width")), y: parseInt($(img).css("height"))};
		var _new = {x:0,y:0};
		var ratio = _old.x / _old.y;
		if(_old.x > _old.y){
			_new.x = fitInto.x;
			_new.y = (fitInto.x/ratio);
		}
		else{
			_new.x = (fitInto.y*ratio);
			_new.y = fitInto.y;
  		}
  		// center image vertically
  		var marginTop = 0;
  		if(_new.y < fitInto.y){
  			marginTop = Math.round((fitInto.y - _new.y)/2);
  		}
		return {width: _new.x+"px", height: _new.y+"px", "margin-top": marginTop+"px"};
	}
	
	/**
	 * style the gallery
	 */
	setupCSS = function(images){
		$("div.gal-thumb").css({
			"float": "left", 
			"width": settings.thumbWidth+"px", 
			"height": settings.thumbHeight+"px", 
			"text-align": "center", 
			"margin-left": "3px",
			"border-top": "2px solid #252525",
			"border-left": "1px solid #252525",
			"border-right": "1px solid #252525",
			"padding-bottom": "7px",
			"border-bottom": "2px solid #252525",			
			"padding": "3px",
			"overflow": "hidden"
		});
		
		$("div.gal").css({
			width: settings.width+"px",
			overflow: "hidden"
		});
		
		$("div.gal-main-viewer").css({
			width: settings.width-20+"px", 
			height: settings.height-20+"px", 
			"text-align": "center",
			overflow: "hidden",
			margin: "auto"
		});
		
		$("div.gal-thumbs-wrapper").css({
			width: settings.width-20+"px", 
			margin: "auto", 
			overflow: "hidden",
			"padding-top": "5px",
			"padding-bottom": ($.browser.msie ? "30px" : "20px")
		});
		
		$("div.gal-thumbs").css({
			height: settings.thumbHeight+"px", 
			width: images.length*(settings.thumbWidth + 11)+20+"px"
		});
		
		$("div.gal-thumb>img").css("background-color", "black");
	}
})(jQuery)

function sleep(delay)
{
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

