// JavaScript Document
function Gallery (wrapper, color)
{
	var DISPLAY_COUNT = 4;
	
	var _wrapper = $(wrapper);
	var _path;
	var _xml;
	var _currentNode;
	var _thumbX = 0;
	var _galleryControl;
	var _thumbOpen = true;
	var _total;
	var _mousePos;
	var _timer;
	var _xmlIndex;
	var _color = color;
	var _bandText;
	
	var offset;
	var increment;
	var pos;
	var animate = false;
	
	/* Public Methods
	***********************************************************************************/
	this.createGallery = function (path, xml, index)
	{
		/* clear **/
		killGallery ();
		
		/* params **/
		_path = path;
		_xml = xml;
		_thumbOpen = true;
		_currentNode = _xml.find("project:eq(" + index + ")");
		_total = _currentNode.children("images").find("item").length;
		_mousePos = {x: 0, y:0};
		_xmlIndex = index;
		
		/* methods **/
		parseXML ();
	}
	
	
	/* Private Methods
	***********************************************************************************/
	function parseXML ()
	{
		/* XML Params **/
		var title = _currentNode.find("title").find("pt").text();
		var situation = _currentNode.attr("situation");
		var kinded = _currentNode.attr("kinded");
		var sizeSqm = _currentNode.attr("sizeSqm");
		var launchDate = _currentNode.attr("launchDate");
		var total = _currentNode.children("images").find("item").length;
		
		var i = 0;
		var gif = DISPLAY_COUNT - total;
		
		_bandText = title + " - " + situation + " - " + kinded + " - " + sizeSqm + "mē - " + launchDate;
		
		/* Gallery **/
		_wrapper.append("<div class='inner_gallery'></div>");
		
		/* Controls **/
		_wrapper.append("<div class='bt_left'></div>");
		_wrapper.append("<div class='bt_right'></div>");
		_wrapper.append("<div class='bt_close'></div>");
		
		/* Thumbs **/
		_wrapper.append("<div class='thumb_gallery'></div>");
		$(".thumb_gallery", _wrapper).append("<div class='thumb_gallery_wrapper'></div>");
		$(".thumb_gallery_wrapper", _wrapper).append("<div class='thumb_gallery_inner'></div>");
		$(".thumb_gallery_wrapper", _wrapper).append("<div class='thumb_gallery_band'></div>");
		
		/* Description **/		
		$(".thumb_gallery_band", _wrapper).append("<div class='description'></div>");
		$(".thumb_gallery_band", _wrapper).append("<div class='band_open_close'></div>");
		
		$(".thumb_gallery_band", _wrapper).append("<div class='share_icons'></div>");
		$(".share_icons", _wrapper).append("<div class='facebook'></div>");
		$(".share_icons", _wrapper).append("<div class='twitter'></div>");
		$(".share_icons", _wrapper).append("<div class='mail'></div>");
		
		$(".thumb_gallery_band", _wrapper).append("<div class='thumb_gallery_band_bg'></div>");
		$(".thumb_gallery_band .description", _wrapper).html("<span>" + _bandText + "</span>");
		
		/* LOOP images - thumbs
		****************************************************************************/
		_currentNode.children("images").find("item").each(function ()
		{
			$(".inner_gallery", _wrapper).append("<div class='item_gallery' style=\"background: url('" + _path + $(this).attr("image") + "') no-repeat 50% 50%;\"></div>");
			
			var html = "";
			html += "<div rel='" + i + "' class='item_thumb' style=\"background: url('" + _path + $(this).attr("thumb") + "') no-repeat 50% 50%;\">";
			html += "	<div class='item_tv_noise'></div>";
			html += "</div>";
			$(".thumb_gallery_inner", _wrapper).append(html);
			
			i++;
		});
		
		$(".item_tv_noise").fadeOut(0);
		
		/* GIF
		****************************************************************************/
		for(var j = 0; j < gif; j++)
		{
			var html = "";
			html += "<div class='item_thumb' rel='none'>";
			html += "	<div class='item_tv_hover'></div>";
			html += "	<div class='item_tb_image' style=\"background: url('library/img/pages/home/ui/noise.gif')\"></div>";
			html += "</div>";
		
			$(".thumb_gallery_inner", _wrapper).append(html);
		}
		
		/* resize Inner **/
		$(".inner_gallery", _wrapper).css("width", _total * $(".item_gallery", _wrapper).width() );
		$(".thumb_gallery_inner", _wrapper).css("width", (_total + (gif > 0 ? gif : 0)) * ($(".item_thumb", _wrapper).width() + 2));		
		
		/* Open Tab **/
		posY = navigator.userAgent.match(/iPad/i) != null ? 115 : 0;
		scrollObjects($(".thumb_gallery_wrapper", _wrapper), "y", posY, 0);
		
		/* Controls **/
		setupControls ();
	}
	
	function changeImageGallery (value)
	{
		$.address.value(_xmlIndex + "/" + value);
	}
	
	/* Animations
	*****************************************/
	function moveGallery(event, phase, direction, distance)
	{
		if( phase == "move" && (direction == "left" || direction == "right") )
		{
			if (direction == "left") scrollObjects($(".inner_gallery", _wrapper), "x", (_galleryControl.getIndex() * $(".item_gallery", _wrapper).width()) + distance, 0);
			else if (direction == "right") scrollObjects($(".inner_gallery", _wrapper), "x", (_galleryControl.getIndex() * $(".item_gallery", _wrapper).width()) - distance, 0);
		}
		else if ( phase == "cancel")
		{
			scrollObjects($(".inner_gallery", _wrapper), "x", _galleryControl.getIndex() * $(".item_gallery", _wrapper).width(), 200);
		}
		else if ( phase == "end" )
		{
			if (direction == "right") _galleryControl.backImage();
			else if (direction == "left") _galleryControl.forwardImage();
		}
	}
	
	function moveThumbs (event, phase, direction, distance)
	{
		var minX = $(".thumb_gallery", _wrapper).width() - $(".thumb_gallery_inner", _wrapper).width();
		
		if( phase == "move" && (direction == "left" || direction == "right") )
		{
			if (direction == "left") 
			{
				if(_thumbX + distance > -minX) { return; }
				scrollObjects($(".thumb_gallery_inner", _wrapper), "x", _thumbX + distance, 0);
			}
			else if (direction == "right") 
			{
				if(_thumbX - distance < 0) { return; }
				scrollObjects($(".thumb_gallery_inner", _wrapper), "x", _thumbX - distance, 0);
			}
		}
		else if ( phase == "end" )
		{
			if (direction == "left")
			{
				if(_thumbX + distance > -minX) {
					_thumbX = -minX;
				} else {
					_thumbX = _thumbX + distance;
				}
			}
			else if (direction == "right") 
			{
				if(_thumbX - distance < 0) {
					_thumbX = 0;
				} else {
					_thumbX = _thumbX - distance;
				}
			}
		}
	}
	
	/* Setup Controls
	*****************************************/
	function setupControls ()
	{
		/* Remove Events **/
		$(".item_thumb", _wrapper).unbind("mouseenter");
		$(".item_thumb", _wrapper).unbind("mouseleave");
		$(".item_thumb", _wrapper).unbind("click");
		$(".thumb_gallery_band", _wrapper).unbind("click");
		$(".bt_close", _wrapper).unbind("click");
		
		if(navigator.userAgent.match(/iPad/i) != null) 
		{
			$(".bt_right", _wrapper).hide();
			$(".bt_left", _wrapper).hide();
			$(".inner_gallery", _wrapper).swipe({ triggerOnTouchEnd : true, swipeStatus : moveGallery, allowPageScroll:"horizontal", threshold:200 });
			$(".thumb_gallery_inner", _wrapper).swipe({ triggerOnTouchEnd : true, swipeStatus : moveThumbs, allowPageScroll:"horizontal", threshold:0 });		
		}
		else 
		{
			imageScrolling();
		}
		
		/* Controls **/
		_galleryControl = new GalleryControl ($(".bt_left", _wrapper), $(".bt_right", _wrapper), _total, 0, changeImageGallery, false);
		
		$(".bt_close", _wrapper).click(function () 
		{ 
			scrollObjects($(".inner_page"), "x", 0, 500); 
			if(_timer != null) clearInterval(_timer);
			$.address.value("");
		});
		
		$(".bt_left", _wrapper).mouseenter(function () { $(this).css("background-color", _color); });
		$(".bt_left", _wrapper).mouseleave(function () { $(this).css("background-color", "#FFF"); });
		
		$(".bt_right", _wrapper).mouseenter(function () { $(this).css("background-color", _color); });
		$(".bt_right", _wrapper).mouseleave(function () { $(this).css("background-color", "#FFF"); });
		
		/* Thumbs **/
		$(".item_thumb", _wrapper).mouseenter(function () {  /*if($(this).attr("selected") != "true") */$(".item_tv_noise", this).fadeTo(200, .4); });
		$(".item_thumb", _wrapper).mouseleave(function ()	{ /*if($(this).attr("selected") != "true") */$(".item_tv_noise", this).fadeOut(200); });
		$(".item_thumb", _wrapper).click(function () { _galleryControl.setIndex(parseInt($(this).attr("rel"))); });
		
		/* Bandage **/
		$(".band_open_close", _wrapper).click(function ()
		{
			var posY;
			
			if(_thumbOpen) {
				posY = navigator.userAgent.match(/iPad/i) != null ? 2 : 112;
				scrollObjects($(".thumb_gallery_wrapper", _wrapper), "y", posY, 300);
				$(".band_open_close", _wrapper).css("background-position", "0 -13px");
			} else {
				posY = navigator.userAgent.match(/iPad/i) != null ? 115 : 0;
				scrollObjects($(".thumb_gallery_wrapper", _wrapper), "y", posY, 300);
				$(".band_open_close", _wrapper).css("background-position", "0 0");
			}
			
			_thumbOpen = !_thumbOpen;
		});
		
		/* Share **/
		$(".facebook").click(function ()
		{
			var image = _path + _currentNode.children("images").find("item:eq(" + _galleryControl.getIndex() + ")").attr("image");
			window.open("http://www.facebook.com/sharer.php?s=100&p[title]=Guilherme Torres&p[url]=http://www.guilhermetorres.com.br&p[summary]=" + _bandText + "&p[images][0]=http://agenciasmart.com.br/clientes_smart/gt/www/" + image);
		});
		
		$(".twitter").click(function ()
		{
			window.open("http://twitter.com/share?url=http%3A%2F%2Fwww.guilhermetorres.com.br&text=" + _bandText);
		});
	}
	
	function selectItem (index)
	{
		/*$(".item_thumb", _wrapper).each(function () 
		{ 
			$(".item_tv_noise", this).fadeOut(200); 
			$(this).attr("selected", "false");
		});
		
		$(".item_thumb:eq(" + index + ")", _wrapper).attr("selected", "true");
		$(".item_thumb:eq(" + index + ") .item_tv_noise", _wrapper).fadeTo(200, .4);*/
	}
	
	function imageScrolling()
	{
		_timer = setInterval(animateThumb, 10);
		
		$(".thumb_gallery_inner").mousemove(function(event)
		{
			_mousePos.x = event.pageX - 280;
			_mousePos.y = event.pageY;
			animate = true;
		});
		
		$(".thumb_gallery_inner").mouseleave(function(event)
		{
			animate = false;
		});		
	}
	
	function animateThumb ()
	{
		if(!animate) return;
		pos = (($(".thumb_gallery").width() / 2) - _mousePos.x) * 0.02;
		$(".thumb_gallery_inner").css("margin-left", parseInt($(".thumb_gallery_inner").css("margin-left")) + pos);
		
		if(parseInt($(".thumb_gallery_inner").css("margin-left")) > 0) $(".thumb_gallery_inner").css("margin-left", 0);
		if(parseInt($(".thumb_gallery_inner").css("margin-left")) < $(".thumb_gallery").width() - $(".thumb_gallery_inner").width())
		{
			$(".thumb_gallery_inner").css("margin-left", $(".thumb_gallery").width() - $(".thumb_gallery_inner").width());
		};
	}
	
	/* Dispose
	*****************************************/
	function killGallery ()
	{
		_wrapper.empty();
		$(".item_thumb", _wrapper).unbind("mouseenter");
		$(".item_thumb", _wrapper).unbind("mouseleave");
		$(".item_thumb", _wrapper).unbind("click");
		$(".thumb_gallery_band", _wrapper).unbind("click");
		$(".bt_close", _wrapper).unbind("click");
		if(_timer != null) clearInterval(_timer);
	}
	
	/* jQuery Address
	****************************************/
	this.updateAddress = function (currentAddress, previousAddress, currentStage)
	{
		if(currentAddress[currentStage] != previousAddress[currentStage])
		{
			scrollObjects($(".inner_gallery", _wrapper), "x", parseInt(currentAddress[1]) * $(".item_gallery", _wrapper).width(), 500);
			selectItem (parseInt(currentAddress[currentStage]));
		}
	}
}
