$(function(){
	
	var $loading = $('#ajax-loading-alt');
	var photos = window.arr_photos;
	
	var len = photos.length;
	var index = 0;
	var loading = false;
	var photo = null;
	var $prev = $('div.content-arrow.go-prev');
	var $next = $('div.content-arrow.go-next');
	var $img = $('div#content-img img');
	var $photocounter = $("#pc-text");
	
	
	var change_index = function(move){
		if (move != 1 && move != -1){ move = 0; }	
		index = index + move;
		if (index < 0){ index = len-1; }
		if (index >= len){ index = 0; }	
		return index;		
	};
	
	var set_loading = function(){		
		$loading.show(10,function(){
		
			photo = null;
			photo = new Image();
			photo.onload = set_loaded;
			photo.src = photos[index];
			
			if (len > 1) {
				$photocounter.text("Foto "+(index+1)+"/"+len);
			}
		});

	};
	
	var set_loaded = function(){
		$loading.hide(10, function(){
			$img.attr('src', photo.src);
			loading = false;
			
			if (window.VillaMap && !window.VillaMap.initialized){ 
				setTimeout(function(){
					VillaMap.init(); 
				}, 1000);
			}
		});
	};
	
	var change_photo = function(move, hide_text){
		if (loading)
			return;
		
		loading = true;
		
		if (typeof(hide_text)!='undefined' && hide_text == true)
			$('div#content-text').hide();
			
		change_index(move);
		set_loading();
	};
	
	
	//
	//MAIN
	//
	$('a#toggle-footer-other').click(function(){
		$(this).hide();
		$('span#footer-other').show();
	});
	
	$('img#banner-residenze').height( $('img#banner-casupola').height() +2  );
	
	$('div#content-text-close a').click(function(){
		$('div#content-text').hide();
	}).attr('title','Nascondi');
	
	$('div#nav ul li a, div#sub-nav ul li a').each(function(){
		var text = $.trim($(this).attr('href'));
		if (text.indexOf($.trim(window.curr_menu), 0) != -1){
			$(this).addClass("navcurrent");
			return false;
		}
	});
	
	$('div#content div.content-arrow')
		.hover(function(){$(this).css('opacity', 0.5);}, function(){$(this).css('opacity', 1);})
		.mousedown(function(){$(this).css('opacity', 0.8);})
	 	.mouseup(function(){$(this).css('opacity', 0.5);});
	
	//IE fix
	(function(){
		if ($.browser.msie) {
			$('#content-text')
				.height(366)
				.css('margin-left',0)
				.css('opacity', 0.8)
				.css('border-left', '1px solid #666');
		}
	})();


	if (len > 1)
	{
		$prev.click(function(){ change_photo(-1, true); });
		$next.click(function(){ change_photo(+1, true); });
		$("div#content-img img").click(function(e){ e.preventDefault(); e.stopPropagation(); change_photo(+1, true); });
		
		$photocounter.text("Foto "+(index+1)+"/"+len);
	}else
	{
		$prev.css('visibility','hidden');
		$next.css('visibility','hidden');
	}
	
	index = -1;
	change_photo(+1, false);
	
});

