/*nav handler*/
var pages = [],
 _gaq = _gaq || [];
$(function(){
	$("nav a[href]").live('click',pageChange);
	$("body").data("loadingPage", "");
	enableGalleryFeatures();
	$('.videoswitch').click(function(e){
		e.preventDefault();
		$('.ad,.videoswitch').slideUp("slow",function(){$(this).remove()});
	})
});
function pageChange(e){
	function loadPage(pageLoading){
		$("nav a").blur();//remove underline
		$("body").data("loadingPage", "");//mark page as displayed
		
		//add article tag if not there, = accessing from fotoView
		if(!$('article').length)
			$("nav").after($("<article>").hide().css('opacity','0'));
		
		if(pageLoading.uid=="pricing")
		{
			$('li.pricing ul a')
				.css({"margin-top":-20,display:'block'})
				.animate({marginTop:0}, "slow");
			$('#photos').animate({height:'hide'},"slow",function(){
				//console.log('photos hidden');
				$(this).hide();
				setTimeout(function(){disableFotoView(e,true)},0);
			});
		}
		else
		{
		//images should load ASA click on nav was done
		//images should be displayed when the article slid up
		// • without transition if currentPage.pricing
		// • crossfaded otherwise
			var currentElements = $("#photos li");
			if(!currentElements.length)
				$("#content").append(
					$("<ul>",{id:"photos"}).append(
						$("<li>").append(
							$("<a>",{href:pageLoading.photos[0].href}).append(
								$("<img>",{
									src: pageLoading.photos[0].mediumSrc,
									alt: pageLoading.photos[0].caption
								})
							)
						)
					).hide()
				);
			
			//remove or add li elements as needed
			var difference = pageLoading.photos.length+1-currentElements.length,
				isMedium;
			if(difference<0)//remove unnecessary photos
				$("#photos li:gt("+pageLoading.photos.length+")")
					.slideUp('slow',function(){$(this).remove()});
			else if(difference>0)//create new elements
			{
				var dom = document.createDocumentFragment(),
					newPhotos = pageLoading.photos.slice(-difference);
				for(i in newPhotos)
				{
					dom.appendChild(
						$("<li>").append(
							$("<a>",{href: newPhotos[i].href}).append(
								$("<img>",{
									src: newPhotos[i].src,
									alt: newPhotos[i].caption,
									title: newPhotos[i].caption
								})
							)
						)[0]
					);
				}
				$("#photos")[0].appendChild(dom);
				
				var newElements = pageLoading.photos.length-difference;
				$("#photos li:gt("+newElements+")").hide().slideDown('slow');
			}
			
			enableGalleryFeatures();
			
			//crossfade thumbnails
			if(currentPage!='pricing')
				for(i in pageLoading.photos)
					crossfade(pageLoading.photos[i], '#photos li a:eq('+(Number(i)+1)+')');
			else//instead of crossfading them, replace them
				for(i in pageLoading.photos)
				{
					var photo = pageLoading.photos[i];
					$("<img>")
					.attr({"src":photo.src,"alt":photo.caption,"title":photo.caption})
					.appendTo(
						$('#photos li a:eq'+"("+(Number(i)+1)+")").attr("href",photo.href)
					)
					.css({position:'',top:'',opacity:1})
					.parent().children('img:first').remove();
					$('#photos li').find('h3').text(photo.caption);
				}
			
			//refresh medium image 
			//setTimeout to avoid having it take the big image instead of medium while coming off fotoView
			//but it doesn't work
			if(currentPage!='photo')
				//setTimeout(function(){$("#photos li:not(:first) a:first").mouseenter();},600)
			//else
				$("#photos li:not(:first) a:first").mouseenter();
		}
			if(currentPage=='pricing')
				$('li.pricing ul a')
					.animate({marginTop:-20}, "slow",
						function(){$(this).css({display:'none'})});
		function showContent(){
			$("#content").removeClass().addClass(pageLoading.uid);
		  var height = $('article').hide().html(pageLoading.content)
		  	.css({height:""}).show().height();
		  $('article').height(0).animate({height:height,opacity:1},'slow',resetHeight);
		  
		  //when current==pricing, photos are hidden
		  if(currentPage=='pricing')
		  	$('#photos').animate({height:'show'},'slow');
		  $.address.value(pagelid+"/"); 
		}
		//from pricing to fotoView is not considered 
		if(currentPage!='photo')
			//slideUp, load, slideDown
			$('article').animate({height:0, opacity:0.01},'slow',showContent);
		else
		{
			if(pageLoading.uid=="pricing")
			{
				//set up to make it slide down from fotoView
				$('article').css({height:0,opacity:0.01});
				
				//set width to prevent shrinking after class is removed
				$('#photos').css({width:780});
				
				//load article and slideDown
				showContent();
			}
			else
			{
				//load article right away
				$('article').html(pageLoading.content);
				
				//and reduce the size of the image to show the article
				disableFotoView(e);
			}
		}
		
		//fix the current page's link in the nav
		$("nav li a:not([href])").each(function(){ 
			var text = $(this).text();
			$(this)
				.css({"margin-right":14})
				.text(text.substr(0,text.length-2))
				.attr("href",$(this).attr("class"))
				.removeAttr("class")
				.animate({"margin-right":0},'slow');
		});
		
		
		//fix the loading page's link in the nav
		$(a).animate({"margin-right":14},"slow",function(){
			$(a).attr("class",$(a).attr("href"))
			.removeAttr("href")
			.css({"margin-right":0,opacity:""})
			.text($(a).text()+" »");
		});
	}
	if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey) return;
	e.preventDefault();
	//if an article is already loading or fotoView is loading, stop
	if($("article:animated,#photos:animated").length) return;
	
	var a = this,
		pagelid = this.href.split('/').reverse()[1],
		currentPage = $('#content').attr('class'),
		lang = $('html').attr("lang"),
		url = "http://www.hotelteti.com/"+lang+"/"+pagelid+"/dynamic/",
		loadingPage = $("body").data("loadingPage");
		
	if(loadingPage==pagelid) return; //if the same page is loading, do nothing
	else if(loadingPage!="") $("nav a").css("opacity",""); //reset current loading page link color
	
	$("body").data("loadingPage",pagelid);
	
	//grey link while it's loading
	$(this).animate({opacity:.5},100);
	function downloadPage(url,triesLeft)
	{
	$.getJSON(url,function(data,textStatus){
			if(textStatus!="success")
			{
				if(!triesLeft--)
					downloadPage(url,triesLeft);
			}
			else
			{
				pages[pagelid] = data;
				if($("body").data("loadingPage")==pagelid)
					loadPage(data);//if the received page is the latest called, load
			}
		});
	}
	if(typeof pages[pagelid] == "undefined")//if it's not cached
		downloadPage(url,2);
	else
		loadPage(pages[pagelid]);
		
	trackView("/"+lang+"/"+pagelid+"/");
}
function getLinkedImageData(th){
	var imagename = th.href.split('/').reverse()[1],
	img = $("img",th)[0],
	isBig = $("#content.photo").length ;
	imageurl = "http://www.hotelteti.com/photos/"+
		(isBig?"":"medium/")+imagename+".jpg",
	caption = img.alt;
	return {src:imageurl,href:th.href,caption:caption,name:(isBig?"":"medium-")+imagename};
}
function mouseOverThumbnails(){	/*mini gallery effects*/
	if($("#photos:animated,article:animated").length) return;
	var image = getLinkedImageData(this);
	$($("#photos").data("loadingImage")).unbind();//removes the old image onload callback
	$("#photos").data("loadingImage", new Image());
	$($("#photos").data("loadingImage"))
		.load(function(){
			crossfade(image,'#photos li a:first');
		})
		.attr("src",image.src);
}
function crossfade(photo,position){
	$("<img>")
		.attr({"src":photo.src,"alt":photo.caption,"title":photo.caption})
		.appendTo($(position).attr("href",photo.href))
		.css({position:'absolute',top:0,opacity:0})
		.animate({opacity:1},500,function(){
			$(this).css({position:"",top:""})
				.parent().children('img:first').remove();
		})
		.parents('li').find('h3').text(photo.caption);
}
function enableFotoView(e){
	e.preventDefault();
	if($("#photos:animated,article:animated").length) return;
	disableImgOnloadCallback();//prevents smallimage load into big space
	var selected = this;
	$("#photos").animate({width:780,paddingLeft:0},{duration:"slow",queue:false});
	$("article").animate({width:0,opacity:0.01},function(){$(this).hide().width("");});
	$("#photos li:first img:last").animate({width:730},{duration:"slow",queue:false,complete:function(){
		var bigurl = selected.href.split('/').reverse()[1];
		this.src = "/photos/"+bigurl+".jpg";
		trackView("/photo/"+bigurl+"/");
		preload();
		//resetWidth(this);
	}})
	.after("<h3>"+$("img",this)[0].alt+"</h3>");
	$("#content").removeClass().addClass("photo");
	$("#photos li:first,nav li a:not([href])").bind("click.disableFotoView",disableFotoView);//todo,triggers disableFotoView for some reason
	$("#photos li a").unbind('click').click(function(e){e.preventDefault();});
}
function disableFotoView(e,notAnimated){
	e.preventDefault();
	if($("#photos:animated").length) return;
	disableImgOnloadCallback();//prevents bigimage load into small space
	var photosCSS = {width:450,paddingLeft:""};
	function afterFX(){
		//resetWidth(this);
		$("#photos h3").remove();
		//$("#photos li:not(:first) a:first").mouseenter();//refresh data
	}
	if(notAnimated)//pageLoading==pricing, article already shown
	{
		$("#photos").css(photosCSS);
		$("#photos li:first img").css({width:430});
		//$("#photos li:first img").css({width:430});
		afterFX();
	}
	else
	{
		$("#photos").animate(photosCSS,"slow",resetWidth);//todo,check "this" 
		$("article").css({width:0}).show().animate({width:329,opacity:1},800,resetWidth);
		$("#photos li:first img").animate({width:430},{duration:"slow",queue:false,complete:afterFX});
		//console.log("now");
	}
	$("#content").removeClass("photo");
	$("#photos li:first,nav li a").unbind('click.disableFotoView');
	$("#photos li a").unbind('click').click(enableFotoView);
}
function enableGalleryFeatures(){
	$("#photos li a").unbind().click(enableFotoView);
	$("#photos li:not(:first) a").mouseenter(mouseOverThumbnails);
	setTimeout(preload,1000);
}
function preload(){
	var $storage = $("#photos");
	//console.log("+++","preloading")
	$("#photos li a").each(function(){
		var self = this,
		image = getLinkedImageData(this),
		storedImage = $storage.data(image.name);
		//console.log("___",image.name);
		if(!storedImage)
		{
			$storage
				.data(image.name, new Image());//create image
			$($storage.data(image.name))
				.load(function(){
					//console.log("^^^",image.name);
					//$(self).find("img").css("opacity",0.3);
				})
				.attr("src",image.src);
		}
		//else $(self).find("img").css("opacity",0.3);
	})
}
function resetWidth(){
	if(!arguments.length) e = this;
	else e = arguments[0];
	$(e).width("");
}
function resetHeight(){
	if(!arguments.length) e = this;
	else e = arguments[0];
	$(this).height("");
}
function trackView(view)
{
	_gaq.push(['_trackPageview',view]);
}
function disableImgOnloadCallback(){
	$($("#photos").data("loadingImage")).unbind();
}

//history event handlers 
$.address.externalChange(function(event) {//on browser back/forward
	var pagelid = event.value.split('/').reverse();
	if(pagelid.length>2)//if anchor is present
	{//use anchor
		pagelid = pagelid[1];
		$("nav a[href*="+pagelid+"],nav a[class*="+pagelid+"]").click();
	}
	else
	{//use page url
		pagelid = document.location.toString().split('/').reverse()[1];
		$("nav a[href*="+pagelid+"],nav a[class*="+pagelid+"]").click();
	}
}); 