//JQuery Gallery v1.1
function Gallery(params){
	
	//PARSE XML
	var parseXML = function(xml)
	{
		numImages = $(xml).find('item').length;
		
		var i = 0;
		
		$(xml).find('item').each(function(){

			var imagePath = imageFolder + encodeURI($(this).find('file').text());
			var linkURL =  encodeURI($(this).find('link').text());
			linkArray.push(linkURL);
			titleArray.push($(this).find('title').text());
			
			var imageHTML = "";
			
			imageHTML += '<div class="indvImageWrapper" id="imageDiv'+i+'" style="width: '+imageWidth+'px; height: '+imageHeight+'px; overflow: hidden;';
			
			if(params.transition == "fade" ||  params.transition == "blink")
			{
				var z = 100 - i;
				
				if(i == 0)
				{
					imageHTML += ' position: absolute; margin-top: 0; z-index: 500;';
				}
				else
				{
					imageHTML += ' position: absolute; margin-top: 0; z-index: '+z+';';
				}
			}
			
			imageHTML += '">';
			
			if(params.imagesClickable)
			{
				imageHTML += '<a href="' + linkURL + '">';
			}					
			imageHTML += '<img src="' + imagePath + '" />';
			if(params.imagesClickable)
			{
				imageHTML += '</a>';
			}
			
			imageHTML += '</div>';

			$($this + " .mover").append(imageHTML);
			
			$('.indvImageWrapper:last img').load(function(){
				fitImage(imageWidth, imageHeight, $(this));
				if(params.transition == "fade" ||  params.transition == "blink")
				{
					imageLoadCount++;
					if(imageLoadCount == numImages)
					{
						
						$($this + " .indvImageWrapper").css({'display' : 'none'});
						$($this + " #imageDiv" + currentNum).css({'display' : 'inline'});
					}
				}
			});
			
			
			if(nodesOn)
			{
				$($this + " .navNodes").append('<li><div class="node"><a href="#" style="display:block; width:100%; height:100%;"><div class="fadeThis"><p>h</p><span class="hover"></span></div></a></div></li>');
			
				$($this + " .fadeThis:last").each(function () {
					var $span = $($this + " > span.hover", this).css('opacity', 0);
				});
				
				var imageNum = i;
				
				$($this + " .node:last a").click(function(event){
					 event.preventDefault();
					 getImage(imageNum);
				});
			}
			
			if(thumbsOn)
			{
				$($this + " .thumbnails").append('<li class="unselected"><div class="thumbImgWrapper"><img src="' + imagePath + '" /></div></li>');
				
				var liWidth = parseInt($($this + " .thumbnails li .thumbImgWrapper").css('width'));	
				var liHeight = parseInt($($this + " .thumbnails li .thumbImgWrapper").css('height'));
										
				$('.thumbImgWrapper:last img').load(function(){cropImage(liWidth, liHeight, $(this));});
				
				var imageNum = i;
				
				$($this + " .thumbImgWrapper:last").click(function(event){
					 event.preventDefault();
					 getImage(imageNum);
				});
			}
			
			i++;
		});
		
	
		if(thumbsHide)
		{
			navNodeWrapperHoverMargin = parseInt($($this + " .navNodesWrapper").css("marginTop"));
			navBarHoverMargin = parseInt($($this + " .navBar").css("marginTop"));
			navBarHoverHeight = $($this + " .navBar").height();
			navBarOffHeight = navBarHoverHeight - (params.navBarOffMargin - navBarHoverMargin);
			
			$($this + ' .navBar').mouseenter(navOverAnim);
			$($this + ' .navNodesWrapper').mouseenter(navOverAnim);
			$($this + ' .navBar').mouseleave(navOutAnim);
			$($this + ' .navNodesWrapper').mouseleave(navOutAnim);
			navOutAnim();
	
		}
		
		$($this).mouseenter(onGalleryOver);
		$($this).mouseleave(onGalleryOut);
		onGalleryOut(true);
	 
		numImages = $(xml).find('item').length;
		
		if(linkDivOn)
		{
			var totalString = new String();
			for(var m = 0; m < linkArray.length; m++)
			{
				totalString += linkArray[m];
			}
			
			if(totalString != "")
			{
				$($this + " .linkDiv").click(function(event){
					event.preventDefault();
					getLink();
				});
			}
		}
		
		if(nodesOn)
		{
			if(params.nodesAlign != "left")
			{
				var liWidth = parseInt($($this + " .navNodes li").css('width'));
				liWidth += parseInt($($this + " .navNodes li").css('marginLeft'));
				liWidth += parseInt($($this + " .navNodes li").css('marginRight'));
				var newWidth = liWidth * numImages;
				var parentWidth = parseInt($($this + " .navNodesWrapper").css('width'));
				
				if(params.nodesAlign == "right")
				{
					$($this + " .navNodes").css('marginLeft', (parentWidth - newWidth));
				}
				else
				{
					$($this + " .navNodes").css('marginLeft', (parentWidth - newWidth) / 2);
				}
			}
		}
		
		if(thumbsOn)
		{
			if(params.thumbsAlign != "left")
			{
				var liWidth = parseInt($($this + " .thumbnails li").css('width'));
				liWidth += parseInt($($this + " .thumbnails li").css('marginLeft'));
				liWidth += parseInt($($this + " .thumbnails li").css('marginRight'));
				liWidth += parseInt($($this + " .thumbnails li").css('borderLeftWidth'));
				liWidth += parseInt($($this + " .thumbnails li").css('borderRightWidth'));
				var newWidth = liWidth * numImages;
				var parentWidth = parseInt($($this + " .thumbsWrapper").css('width'));
				
				
				if(params.nodesAlign == "right")
				{
					$($this + " .thumbnails").css('marginLeft', (parentWidth - newWidth));
				}
				else
				{
					$($this + " .thumbnails li:last-child").css('marginRight', 0);
					$($this + " .thumbnails").css('marginLeft', (parentWidth - newWidth) / 2);
				}
			}
		}
		
		if(numImages == 1)
		{
			$($this + " .navBtns").empty();
			$($this + " .navBar").empty();
		}
		getImage(0);
		
		//parseXML end
	}
	
	var getImage = function(num)
	{
		
		
		if(num == -1)
		{//left
			num = currentNum - 1;
		}
		else if(num == -2)
		{//right
			num = currentNum + 1;	
		}
		
		if(params.looping)
		{
			if(slideInterval > 0)
			{
				clearTimeout(slideTimer)
				slideTimer = setTimeout(nextImage, slideInterval);
			}
		}
		else if (num < numImages - 1)
		{
			if(slideInterval > 0)
			{
				clearTimeout(slideTimer)
				slideTimer = setTimeout(nextImage, slideInterval);
			}
		}		
		
		if(num < 0)
		{
			num = numImages - 1;
		}
		else if (num > numImages - 1)
		{
			num = 0;
		}
		
		var oldNum = currentNum+1;
		$($this + " .thumbnails li:nth-child(" + oldNum + ")").removeClass('selected').addClass('unselected')
		
		if(params.transition == "slideHorizontal")
		{
			$($this + " div.mover").stop().animate(
				{marginLeft: -(imageWidth * num)},
				{duration: params.animSpeed,
				easing: params.animTransition});
		}
		else if(params.transition == "fade")
		{
			if(currentNum != num)
			{
				$($this + " #imageDiv" + currentNum).stop();
				$($this + " #imageDiv" + currentNum).clearQueue();
				$($this + " #imageDiv" + num).stop();
				$($this + " #imageDiv" + num).clearQueue();
				//set all z-indexes to lower
				$($this + " .absoluteImage").css({'z-index' : '100'});
				
				$($this + " #imageDiv" + currentNum).css({'z-index' : '500'});
				$($this + " #imageDiv" + currentNum).css({'opacity' : '1'});
				
				$($this + " #imageDiv" + num).css({'z-index' : '499'});
				$($this + " #imageDiv" + num).css({'opacity' : '1'});
				$($this + " #imageDiv" + num).css({'display' : 'inline'});
				
				$($this + " #imageDiv" + currentNum).stop().animate(
					{opacity: 0},
					{duration: params.animSpeed,
					easing: params.animTransition,
					complete: function()	{
						$(this).css({'z-index' : '100'});
						$(this).css({'display' : 'none'});
					}
				});

			}
			
		}
		else if(params.transition == "blink")
		{
			$($this + " div.mover").stop().animate(
				{marginLeft: -(imageWidth * num)},
				{duration: params.animSpeed,
				easing: params.animTransition});
		}
		
		currentNum = num;
		
		$($this + " .textLabel p").empty();
		$($this + " .textLabel p").append(titleArray[num]);
		
		$($this + " .numberLabel p").empty();
		$($this + " .numberLabel p").append((num+1) + params.labelDelimiter + numImages);
		
		$($this + " .node .fadeThis span.hover").stop().fadeTo(200, 0);
		num++;
		$($this + " .navNodes li:nth-child(" + num + ") .fadeThis span.hover").stop().fadeTo(200, 1);
		
		
		$($this + " .thumbnails li:nth-child(" + num + ")").removeClass('unselected').addClass('selected')
		
	}
	
	var nextImage = function()
	{
		getImage(-2);
	}
	
	var getLink = function()
	{
		window.location = linkArray[currentNum];
	}
	
	var cropImage = function(maxWidth, maxHeight, image) {
		
		var width = image.width();
		var height = image.height();
		
		var ratio1 = (maxWidth + 1) / width;
		var ratio2 = (maxHeight + 1) / height;
		
		var ratio = ratio2;
		
		if(width * ratio1 >= maxWidth && height * ratio1 >= maxHeight)
		{
			ratio = ratio1;
		}
		
		image.attr('width', (width * ratio));
		image.attr('height', (height * ratio));
		image.css('marginLeft', (maxWidth - (width * ratio)) / 2);
		image.css('marginTop', (maxHeight - (height * ratio)) / 2);
	}
	
	var fitImage = function(maxWidth, maxHeight, image) {
		
		var width = image.width();
		var height = image.height();
		
		var ratio1 = maxWidth / width;
		var ratio2 = maxHeight / height;
		
		var ratio = ratio2;
		
		if(width * ratio1 <= maxWidth && height * ratio1 <= maxHeight)
		{
			ratio = ratio1;
		}
		
		image.attr('width', (width * ratio));
		image.attr('height', (height * ratio));
		image.css('marginLeft', (maxWidth - (width * ratio)) / 2);
		image.css('marginRight', (maxWidth - (width * ratio)) / 2);
		image.css('marginTop', (maxHeight - (height * ratio)) / 2);
		image.css('marginBottom', (maxHeight - (height * ratio)) / 2);
	}
	
	var navOverAnim = function()
	{
		$($this + ' .navBar').stop().animate(
			{
				marginTop: navBarHoverMargin,
				height: navBarHoverHeight
			},
			500,
			'easeOutExpo'
		);
		$($this + ' .navNodesWrapper').stop().animate(
			{
				marginTop: navNodeWrapperHoverMargin
			},
			500,
			'easeOutExpo'
		);
	}
	
	var navOutAnim = function()
	{
		$($this + ' .navBar').stop().animate(
			{
				marginTop: params.navBarOffMargin,
				height: navBarOffHeight
			},
			500,
			'easeInOutSine'
		);
		$($this + ' .navNodesWrapper').stop().animate(
			{
				marginTop: navNodeWrapperHoverMargin + (params.navBarOffMargin - navBarHoverMargin)
			},
			500,
			'easeInOutSine'
		);
	}
	
	var onGalleryOver = function()
	{
		if(params.fadeButtons)
		{
			$($this + ' .navBtns').stop().animate(
				{
					opacity: 1
				},
				200,
				'easeInOutSine'
			);
		}
		
		if(params.pauseOnHover)
		{
			clearTimeout(slideTimer);
			slideInterval = 0;
		}
	}
	
	var onGalleryOut = function(firstTime)
	{
		if(firstTime != false && firstTime != true)
		{
			firstTime = false;
		}
		
		if(params.fadeButtons)
		{
			var newAnimTime = 300;
			
			if(firstTime)
			{
				newAnimTime = 0;
			}
			
			$($this + ' .navBtns').stop().animate(
				{
					opacity: 0
				},
				newAnimTime,
				'easeInOutSine'
			);
		}
		
		if(params.pauseOnHover)
		{
			if(!firstTime)
			{
				clearTimeout(slideTimer);
				slideInterval = params.slideInterval;
				slideTimer = setTimeout(nextImage, slideInterval);
			}
		}
	}

	var $this;
	if(params.wrapper == null){ alert("Error, wrapper class not specified"); }
	else { $this = "." + params.wrapper; }
	
	if(params.xmlPath == null && params.xmlData == null){ alert("Error, xmlPath or xmlData not specified"); }
	if(params.slideInterval == null){ params.slideInterval = 7000; }
	if(params.layout == null){ params.layout = "minimal"; }
	if(params.looping == null){ params.looping = true; }
	if(params.imagesClickable == null){ params.imagesClickable = false; }
	if(params.labelDelimiter == null){ params.labelDelimiter = "/"; }
	if(params.nodesAlign == null){ params.nodesAlign = "center"; }
	if(params.thumbsAlign == null){ params.thumbsAlign = "center"; }
	if(params.navBarOffMargin == null){ params.navBarOffMargin = 200; }
	if(params.imageFolder == null){ params.imageFolder = ""; }
	if(params.transition == null){ params.transition = "slideHorizontal"; }
	if(params.fadeButtons == null){ params.fadeButtons = false; }
	if(params.pauseOnHover == null){ params.pauseOnHover = false; }
	
	if(params.animTransition == null)
	{
		if(params.transition == "slideHorizontal" || params.transition == "slideVertical")
		{
			params.animTransition = "easeOutExpo";
		}
		else
		{
			params.animTransition = "easeInOutSine";
		}
	}
	
	if(params.animSpeed == null)
	{
		if(params.transition == "slideHorizontal" || params.transition == "slideVertical")
		{
			params.animSpeed = 500;
		}
		else
		{
			params.animSpeed = 1000;
		}
	}
	
	var imageFolder = params.imageFolder;
	var numImages = 0;
	var currentNum = 0;
	var slideTimer;
	var imageWidth;
	var imageHeight;
	var moverX = 0;
	var linkArray = new Array();
	var titleArray = new Array();
	var nodesOn = true;
	var thumbsOn = false;
	var thumbsHide = false;
	var linkDivOn = false;
	var arrowsOn = true;
	var navBarHoverMargin = 0;
	var navBarHoverHeight = 0;
	var navBarOffHeight = 0;
	var navNodeWrapperHoverMargin = 0;
	var imageLoadCount = 0;
	var slideInterval = params.slideInterval;
	
	
	$($this).empty();
	
	///////////////////////////////LAYOUTS///////////////////////////////
	var htmlArray = new Array();
	//MAIN START - this part normally goes first
	htmlArray.push('<div class="galleryContainer"><div class="mover" style="width: 20000px"></div>');						/*0 */
	//MAIN START END - this part ends galleryContainer, things after this normally float over it
	htmlArray.push('</div>');																								/*1 */
	//nav button wrapper open
	htmlArray.push('<div class="navBtns">');																				/*2 */
	//nav button wrapper close
	htmlArray.push('</div>');																								/*3 */
	//nav button right
	htmlArray.push('<div class="rightBtn"><a href="#"></a></div>');															/*4 */
	//nav button left
	htmlArray.push('<div class="leftBtn"><a href="#"></a></div>');															/*5 */
	//link div for nav button wrapper
	htmlArray.push('<div class="linkDiv"></div>');																			/*6 */
	//nav bar open
	htmlArray.push('<div class="navBar">');																					/*7 */
	//nav bar close
	htmlArray.push('</div>');																								/*8 */
	//text label
	htmlArray.push('<div class="textLabel"><p></p></div>');																	/*9 */
	//number label
	htmlArray.push('<div class="numberLabel"><p></p></div>');																/*10*/
	//nav nodes
	htmlArray.push('<div class="navNodesWrapper"><ul class="navNodes"></ul><div style="clear:both;"></div></div>');			/*11*/
	//thumbnails
	htmlArray.push('<div class="thumbsWrapper"><ul class="thumbnails"></ul><div style="clear:both;"></div></div>');			/*12*/
	//clearing div
	htmlArray.push('<div style="clear:both;"></div>');																		/*13*/
	//nav left section open
	htmlArray.push('<div class="leftSection">');																			/*14*/
	//nav left section close
	htmlArray.push('</div>');																								/*15*/
	//nav right section open	
	htmlArray.push('<div class="rightSection">');																			/*16*/
	//nav right section close
	htmlArray.push('</div>');																								/*17*/
	
	var layoutArray = new Array();
	//minimal
	layoutArray.push(new Array(0,2,4,5,6,3,1,7,11,8));
	//titleOverlay
	layoutArray.push(new Array(0,1,7,4,5,9,11,8));
	//thumbOverlayLeft
	layoutArray.push(new Array(0,1,7,14,4,5,10,15,16,12,17,8));
	//thumbOverlayRight
	layoutArray.push(new Array(0,1,7,14,12,15,16,4,5,10,17,8));
	//nodesOnly
	layoutArray.push(new Array(0,1,7,11,8));
	//arrowsOnly
	layoutArray.push(new Array(0,2,4,5,6,3,1));
	//arrowsOnlyTitleAbove
	layoutArray.push(new Array(9,0,2,4,5,6,3,1));
	//thumbs
	layoutArray.push(new Array(0,1,7,12,8));
	//slideOutThumbs
	layoutArray.push(new Array(11,7,12,8,0));
	//arrowsTitleOnly
	layoutArray.push(new Array(0,2,4,5,9,6,3,1));
	//imagesOnly
	layoutArray.push(new Array(0,1));
	/////////////////////////////END LAYOUTS/////////////////////////////

	//Fill out layout html
	var layoutIndex = 0;
	switch(params.layout){
		case "titleOverlay":
			layoutIndex = 1;
			break;
		case "thumbOverlayLeft":
			layoutIndex = 2;
			nodesOn = false;
			thumbsOn = true;
			break;
		case "thumbOverlayRight":
			layoutIndex = 3;
			nodesOn = false;
			thumbsOn = true;
			break;
		case "nodesOnly":
			layoutIndex = 4;
			arrowsOn = false;
			break;
		case "arrowsOnly":
			layoutIndex = 5;
			nodesOn = false;
			break;
		case "arrowsOnlyTitleAbove":
			layoutIndex = 6;
			nodesOn = false;
			break;
		case "thumbs":
			layoutIndex = 7;
			nodesOn = false;
			thumbsOn = true;
			break;
		case "slideOutThumbs":
			layoutIndex = 8;
			nodesOn = true;
			thumbsOn = true;
			thumbsHide = true;
			break;
		case "arrowsTitleOnly":
			layoutIndex = 9;
			nodesOn = false;
			break;
		case "imagesOnly":
			layoutIndex = 10;
			nodesOn = false;
			break;
	}
	
	var mainHTML = '';
	
	var i = 0;
	$.each(layoutArray[layoutIndex], function(){
		mainHTML += htmlArray[layoutArray[layoutIndex][i]];
		if(layoutArray[layoutIndex][i] == 6)
		{
			linkDivOn = true;
		}
		i++;					  
	});
	
	$($this).append(mainHTML);
						   
	if(arrowsOn)
	{
		$($this + " .rightBtn a").click(function(event){
		 event.preventDefault();
		 getImage(-2);
	   });
	   
	   $($this + " .leftBtn a").click(function(event){
		 event.preventDefault();
		 getImage(-1);
	   });
	}
						   
	/*imageWidth = $($this).width();
	imageHeight = $($this).height();
	add above back in if things break
	*/
	imageWidth = $($this + ' .galleryContainer').width();
	imageHeight = $($this + ' .galleryContainer').height();
	
	if(params.xmlPath != null)
	{
		$.ajax({
			type: "GET",
			url: params.xmlPath,
			dataType: "xml",
			success: function(xml) {
				$(xml).find('xml').each(function(){
					parseXML($(this));	 
				});
			},
			error: function(xhr, ajaxOptions, thrownError){
				alert('Could not load XML "' + params.xmlPath + '", thrown error: ' + thrownError);
			}
		});
	}
	else if(params.xmlData != null)
	{
		parseXML(params.xmlData);
	}
	
	
}