/**
 * uGallery jQuery plugin
 * This is a modified plugin:
 * - added support for captions
 * - added autoplay function
 */
(function($){
	var settings = {
		width: 620,
		height: 350,
		thumbWidth: 140,
		thumbHeight: 90,
		thumbOpacity: 1,
		thumbHoverOpacity: 1,
		displayAlt: true,
		loopDelay: 10000,
		autoplay: true,
		currentImage: 0
	}
	
	$.uGallery = function(userSettings){
		var images = [];
		var caption = [];
		$.extend(settings, userSettings);
    	// parse input structure to caption
    	$("ul.gal>li>div.captionT").each(function(index, element){
			caption[index] = $(element).attr("capt", $(element).get()[0].innerHTML);
		});
		// parse input structure to images
		$("ul.gal>li>img").each(function(index, element){
			images[index] = $(element)
				.css({width: element.width+"px", height: element.height+"px"})
				.attr("src", $(element).attr("src"))
				.attr("alt", $(element).attr("alt"))
				.attr("cap", caption[index].attr("capt"))
				.attr("index", index);
		});
		// recreate gallery structure using divs 
		$("ul.gal").replaceWith("<div class='gal'><div class='gal-main-viewer'></div><div class='gal-thumbs-wrapper'><div class='gal-thumbs'></div></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>");
		// style the gallery
		setupCSS(images);
		// bind click event to the thumb containers
		$("div.gal-thumb").each(function(i) {
			$(this).bind("click", function(e) {
				if (typeof(e.detail) == 'undefined' || e.detail==1) {
					clickHandler(images[i]);
				}
			});
		});
		// display the first thumb image in main viewer
		$("div.gal-thumbs>div.gal-thumb:first").trigger('click');
		
		// create thumb strip moving behaviour on mousemove
    	/*
    	$("div.gal-thumbs").bind("mousemove", function(e){
			var thumbs = $("div.gal-thumbs");
			viewWidth = settings.width;
			contentWidth = parseInt(thumbs.css('width'));
			movableWidth = contentWidth - viewWidth;
			var margin = -Math.round((e.clientX / viewWidth) * movableWidth) + 50;
			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("fast", settings.thumbHoverOpacity); }, 
			function(){ $(this).fadeTo("slow", settings.thumbOpacity); }
		);
		
		// get all thumbs
		settings.thumbs = [];
		$("div.gal-thumbs>div.gal-thumb").each(function(index, element) {
			settings.thumbs[index] = $(element);
		});
		// initiate the autoplay
		if (settings.autoplay) {
			settings.playtimer=setTimeout(function(){showNext();},settings.loopDelay);
		}
	}

	/**
	 * add autoplay function
	 */
	showNext = function(){
		var nextImage = settings.currentImage; nextImage++;
		if (nextImage == settings.thumbs.length) {
			nextImage = 0;	
		}

        if (settings.thumbs[nextImage]) {
            settings.thumbs[nextImage].trigger('click');
        }
        
		settings.playtimer=setTimeout(function(){showNext();},settings.loopDelay);	
	}
	
	/**
	 * creates proportionally resized image with onclick showing full image in image viewer
	 */
	makeThumb = function(img, thumbs){
		var image = $("<img src='"+$(img).attr("src")+"' alt='"+$(img).attr("alt")+"' class='captify' />");
		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){
			clickHandler(img);
		});
		*/
		return image;
	}
	
	clickHandler = function(img) {
		var image = $("<img src='"+$(img).attr("src")+"' alt='"+$(img).attr("alt")+"' />");
		image.css(proportionalDimensions(img, {x: settings.width, y: settings.height}));
		var alt = $("<div class='gal-alt'><div class='gal-alt-background'/><div class='gal-alt-content'>"+$(img).attr("cap")+"</div></div>");
		alt.css({
			clear: "both",
			width: settings.width+"px"
		});
		alt.show();
		$("div.gal-main-viewer").fadeOut("normal", function(){
			$(this).html(image).hide().fadeIn("normal").append(alt);
			if(settings.displayAlt){
				$("div.gal-alt").animate({marginTop: "-110px"}, 0);
			}
		});
		settings.currentImage = $(img).attr("index");
	}
	
	
	/**
	 * 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: "1px solid #CCC",
			padding: "3px",
			overflow: "hidden"
		});

		$("div.gal").css({
			width: settings.width+"px",
			overflow: "hidden"
		});

		$("div.gal-main-viewer").css({
			width: settings.width+"px",
			height: settings.height+"px",
			"text-align": "center",
			overflow: "hidden",
			margin: "auto"
		});

		$("div.gal-thumbs-wrapper").css({
			width: (settings.width -10) +"px",
			margin: "auto",
			overflow: "hidden",
			"padding": "5px 5px 5px 5px"
		});

		$("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)