var numItems;
var description;
var goto;
var opened = false;
var tempY;

String.prototype.replaceAt=function(index, char) {
      return this.substr(0, index) + char + this.substr(index+char.length);
   }


$(document).ready(function() {

	var img;
	var tempIndex;
	
	
	$.address.strict(0); 
	

	$('body').append('<div id="container"><table id="containerTable" border="0" height="100%"><tr><td id="number" style="vertical-align: top; text-align: right"></td><td rowspan=3 id="imgcont" style="text-align: center"><div id="imgdiv"></div></td><td class="tabella" style="vertical-align: top"><img id="closebtn" class="pointer" src="/templates/rdc/images/close.png" /></td></tr><tr><td align="left" ><img src="/templates/rdc/images/arrowSx.png" class="arrows pointer" id="previous" style="opacity: 0;"></td><td class="tabella"><img id="next" class="arrows pointer" src="/templates/rdc/images/arrowDx.png" /></td></tr><tr><td></td><td class="tabella" style="vertical-align: bottom; text-align: left"></td></tr><tr><td></td><td id="imagedesc" style="text-align: center"></td><td><p id="share" class="pointer"><a href="http://www.facebook.com/sharer.php?u='+encodeURIComponent(window.location)+'" target="_blank">Share</a></p></td></tr></table></div><div id="shadow"></div><div id="loader" style="width :15px; height: 15px;"></div> <div id="desc"></div>');
	
	if($.browser.mozilla){
		$("#shadow").css('opacity', '1');
	}	
		
   	$('#loader').css('opacity', '0');
   	
   	if($.browser.safari){
   		$('#loader').css('margin-top', $(window).height() / 2 + $('body').scrollTop() - 7);
		$('#desc').css('margin-top', $(window).height() / 2 + $('body').scrollTop() - 0);
   	} else{ 
   		$('#loader').css('margin-top', $(window).height() / 2 + $('body,html').scrollTop());
		$('#desc').css('margin-top', $(window).height() / 2 + $('body,html').scrollTop());
   	} 
   	
   	$('#loader').css('margin-left', $(window).width() / 2);

	
	$("#containerTable").hide();
	$("#shadow").css("height", $(window).height()).hide();
	
						 
	(function($) {
	
		$('#nav3 a').click( function(event){
			   
			/* $('html, body').animate({scrollTop:0}, {duration:1000, easing:"quartEaseOut"});	*/
			//	$("html, body").animate({ scrollTop: 0 }, "fast");
 			// return false;
		});
		  
		  
	  	$.fn.sorted = function(customOptions) {
	    	var options = {
	      		reversed: false,
	      		by: function(a) { return a.text(); }
	    	};
	    	$.extend(options, customOptions);
	    	$data = $(this);
	    	arr = $data.get();
	    	arr.sort(function(a, b) {
	      		var valA = options.by($(a));
	      		var valB = options.by($(b));
	      		if (options.reversed) {
	        		return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;				
	      		} else {		
	        		return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;	
	      		}
	    	});
	    	return $(arr);
	  	};
	})(jQuery);

  	var $filter = $('#nav3 a, #rightcol a');
  	var $portfolio = $('#items');
  	var $data = $portfolio.clone();
  	
  	//console.log($("#items img").attr('title'));
  	
  	$("#items li").each(function(n) {
  		$(this);
            //$(this).attr("alt", $(this).attr("title"));
    });
  
  
  	$.address.change(function(event) {
  	
  		var value = event.value;
  		
  		var tempURL = String(window.location);
  		
  		if (tempURL.indexOf("%3F") != -1) tempURL = tempURL.replace("%3F","?");
  		
  		if (tempURL.split("?").length -1 > 1) document.location = (tempURL.replaceAt(tempURL.indexOf("?"),"#"));
  	

  		if (value == 'All' || value == "" || value.slice(0,value.indexOf("?")) == 'All' || value.slice(0,value.indexOf("?")) == "" ) {
  	 		var $filteredData = $data.find('li').not('li[data-type*=None]');
  	 	} else {
  	 		if (value.indexOf("?") != -1) var $filteredData = $data.find('li[data-type*=' + capitaliseFirstLetter(value.slice(0,value.indexOf("?"))) + ']');
  	 		else var $filteredData = $data.find('li[data-type*=' + capitaliseFirstLetter(value) + ']');
  	 	}
  	 	
  	 	if (value.indexOf("?") == -1 && value != "") {
  	 		$('#nav3 a').each(function (){
  	 			
 				if ($('span' ,this).html() == capitaliseFirstLetter(value)) $(this).addClass('selected');
 				else $(this).removeClass('selected');
 			});
  	 	} else {
  	 		$('#nav3 a').each(function (){
 				if (value == "" && $('span' ,this).html() == "All") $(this).addClass('selected');
 			});
  	 	}
  	 	
  	 
  	 	if ($.address.parameter("image") != undefined) {
  	 		
  	 		if($.browser.safari) tempY = $('body').scrollTop();
  	 		else tempY = $('body,html').scrollTop();
  	 		
  	 		
  	 		$("#shadow").css("height", $(document).height());
  	 		if ($('#shadow').css('display') == 'none') $('#shadow').fadeIn(500, function (){
  	 			$('body,html').scrollTop(0);
  	 			$('html').css('overflow-y','hidden');
  	 		});
  	 		$('#loader').animate({opacity:"1"},{duration:500});
  	 		
  	 		$('#share').show();
  	 
  		 	//openImage($.address.parameter("image"))
  	 		var bigPath = ($('li[data-id="' + $.address.parameter("image") + '"] img').attr('src'));
  	 		description = ($('li[data-id="' + $.address.parameter("image") + '"] img').attr('alt'));
  	 		if (description == "") description = ($('li[data-id="' + $.address.parameter("image") + '"] img').attr('title'));
  	 		
  	 		openImage(bigPath.replace('thumb','big'));
  	 		//console.log($.address.parameter("image"));
  	 	} else {
  	 		closeBig();
  	 	}
  		
  		if (tempIndex == 0) $('#previous').animate({opacity:"0"},{duration:400});
		else $('#previous').animate({opacity:"1"},{duration:400});
		if (tempIndex == numItems - 1) $('#next').animate({opacity:"0"},{duration:400});
		else $('#next').animate({opacity:"1"},{duration:400});
			
 		/* $filter.click(function(e) {
	  	postionMe();
		//	console.log("ecco") 	
							
    	if ($($(this)).attr("title") == 'all') {
      		var $filteredData = $data.find('li');
    	} else {
      	var $filteredData = $data.find('li[data-type=' + $($(this)).attr("title") + ']');
    	}
		*/
	 
	
		$portfolio.quicksand($filteredData, {
			duration:600,
      		easing: 'easeInQuint',
 			adjustHeight:'dynamic',
	    	useScaling: true
	  		},function () {
					 myTime = 400;
        		postionMe(myTime);
				
				$("#items img").not('li[data-type*=None] img').simpletooltip();
				
			   	numItems = $("#items").children("li").not('li[data-type*=None]').length;
			   	tempIndex = $('#items li').index($('li[data-id="' + $.address.parameter("image") + '"]'));
			   
				if (tempIndex == 0) $('#previous').animate({opacity:"0"},{duration:400});
				else $('#previous').animate({opacity:"1"},{duration:400});
				if (tempIndex == numItems - 1) $('#next').animate({opacity:"0"},{duration:400});
				else $('#next').animate({opacity:"1"},{duration:400});
		
				$('li[data-type*=None] img').css('cursor','default');
				var $ciccio = $('#items li').not('li[data-type*=None]');
 				$ciccio.click(function (event) {
  					$.address.parameter("image", $(this).attr("data-id"));
  				});
			   
			   /*	$("#items img").each(function() {
            		$(this).attr("alt", $(this).attr("title"));
    			});*/
    
				//   $(".box img").width(160).height(120);
			   
				 /*   $("#content").find("#items img").width(160);
				   $("#content").find("#items img").height(160);*/
				  // $("#nav3 li a").trigger("click")
			} 
		);	

	 /* $('#content, #footer').delay(0).css(
        { 'opacity': '0', 'visibility': 'visible'})*/
        
        var closebtnclick = function() {
    		$.address.value(value.slice(0,value.indexOf("?")));
    		$('html').css('overflow-y','scroll');
    		opened = false;
		};
		var closepress = function() {
    		closeBig();
		};
		$("#closebtn").click(closebtnclick);
        $("#closebtn").hover(
        	function () {
			    $(this).attr('src','/templates/rdc/images/closeOver.png');
			  }, 
			  function () {
			    $(this).attr('src','/templates/rdc/images/close.png');
			  }	
        );
        $("#previous").hover(
        	function () {
			    $(this).attr('src','/templates/rdc/images/arrowSxOver.png');
			  }, 
			  function () {
			    $(this).attr('src','/templates/rdc/images/arrowSx.png');
			  }	
        );
        $("#next").hover(
        	function () {
			    $(this).attr('src','/templates/rdc/images/arrowDxOver.png');
			  }, 
			  function () {
			    $(this).attr('src','/templates/rdc/images/arrowDx.png');
			  }	
        );
        
        var openpress = function() {
        	$("#closebtn").click(closepress);
        	$('#share').hide();
        	
        	if($.browser.safari) tempY = $('body').scrollTop();
  	 		else tempY = $('body,html').scrollTop();
        	
        	$("#shadow").css("height", $(document).height());
  	 		if ($('#shadow').css('display') == 'none') $('#shadow').fadeIn(500, function (){
  	 			$('body,html').scrollTop(0);
  	 			$('html').css('overflow-y','hidden');
  	 		});
     
  	 		$('#loader').animate({opacity:"1"},{duration:500});
  	 		var bigPath = ($(this).attr('src'));
  	 		description = ($(this).next());
  	 		$('#next').css('opacity','0');
  	 		$('#previous').css('opacity','0');
  	 		openImage(bigPath.replace('tmb','big'));
        };
        $('.press p img').click(openpress);
        
        function moveDown() {
        	if($.browser.safari) $('body').scrollTop(tempY);
  	 		else $('body,html').scrollTop(tempY);
  	 		if ($("#shadow").css('display') == 'block') $("#shadow").fadeOut({duration:100});
  	 		$("#shadow").css("height", $(window).height());
  	 		$('#loader').animate({opacity:"0"},{duration:1});
        }
        
		function closeBig(){
			if ($("#containerTable").css('display') == 'table') $("#containerTable").fadeOut(500, function () {
				
				moveDown();
			});
  	 		else if ($("#containerTable").css('display') == 'block') $("#containerTable").fadeOut(500, function () {
  	 			moveDown();
  	 		});
  	 		
		};										   
});
				
		
		var nextclick = function(event) {
			
		    if (tempIndex < numItems - 1) {
		    		goto = 'left';
					tempIndex++;
					$.address.parameter("image", $('#items li').eq(tempIndex).attr("data-id"));
				}
		};
		$("#next").click(nextclick);
		
		
		var previousclick = function(event) {
		    	if (tempIndex >= 1) {
		    		goto = 'right';
					tempIndex--;
					$.address.parameter("image", $('#items li').eq(tempIndex).attr("data-id"));
				}
		};
		$("#previous").click(previousclick);	
		
		
						 
//  $("#nav3 li a:first").trigger("click");	
	$(window).resize(function() {
		$("#shadow").css("height", $(window).height());
		resizeImage(img);
		if($.browser.safari){
		   	$('#loader').css('margin-top', $(window).height() / 2 + $('body').scrollTop());
				$('#desc').css('margin-top', $(window).height() / 2 + $('body').scrollTop());
		} else{ 
			
		   	$('#loader').css('margin-top', $(window).height() / 2 + $('body,html').scrollTop());
			$('#desc').css('margin-top', $(window).height() / 2 + $('body,html').scrollTop());
		}
		try {
			$('.tabella').css('height', img.height / 3);
		} catch (err) {
			// error
		}
   		$('#loader').css('margin-left', $(window).width() / 2);
		//$('#desc').css('margin-left', ($(window).width() / 2) - (descWidth/2)  );
	});
	
	function openImage(path) {
	
		var direction;
		var tempX;
				
		if (goto == 'left') {
			//direction = left;
			tempX = -$(window).width() / 2 - $('#bigimage').width() / 2;
		} else {
			//diretion = right;
			tempX = +$(window).width() / 2 + $('#bigimage').width() / 2;
		} 
		
		$('#imagedesc').html('');

	if (img == undefined || !opened) {
	
		
		$('#imgcont').animate({opacity:"0"},{duration:700, complete: function () {
			$('#loader').show();
			img = new Image();
    	//	$('#imgcont').html("<div id='imgdiv'></div>");
    		
    		if (!opened) $('#imgdiv').html(img);
    		else $('#imgdiv').append(img);
    		
			$('#imgdiv').hide();
    		
    		opened = true;
    	
       		$(img).attr('src', path/* +'?'+Math.random()*Math.random()*/).load(function() {
       		
       			$('#share a').attr('href', 'http://www.facebook.com/sharer.php?u='+encodeURIComponent(window.location));
    			
    			if ($("#containerTable").css('display') == 'none') $("#containerTable").show();
    			$(this).attr('id', 'bigimage');
    			$('#imagedesc').html(description);
    			width = img.width;    // Current image width
    			height = img.height;
    			ratio = width / height;
    			$('#desc').css('opacity','0');
			//	$('#desc').html(tempHTML);
				descWidth = $('#desc').width();
			
			//	$('#number').html(tempIndex + 1);
    			resizeImage(img);
    		//	$('#containerTable').show();
    			$('#loader').hide();
 	   			$('#imgcont').animate({opacity:"1"},{duration:500});
 			//	$('#loader').animate({opacity:"0"},{duration:100, easing:"quartEaseIn"});
			});
		}});
	
	} else {
	
	
		$('#bigimage').animate({left:tempX},{duration:400/*, easing:"quartEaseIn"*/, complete: function () {  // via delay e sistemare senza perdita tempo ma occhio a quando risale dove aggancia
		var oldx = $('#bigimage').css('left');
			$('#loader').show();
			
		// Animation complete
       	//	$("#containerTable").hide();
    	//	$('#imgcont').empty();
    		img = new Image();
    
    	//	$('#imgcont').html("<div id='imgdiv'></div>");
    		$('#imgdiv').html(img);
    		
    		$('#imgdiv').hide();
    		
       		$(img).attr('src', path +'?'+Math.random()*Math.random()).load(function() {
       		
       			$('#share a').attr('href', 'http://www.facebook.com/sharer.php?u='+encodeURIComponent(window.location));
    			
    			if ($("#containerTable").css('display') == 'none') $("#containerTable").show();
    			$(this).attr('id', 'bigimage');
    			$('#imagedesc').html(description);
    			width = img.width;    // Current image width
    			height = img.height;
    			ratio = width / height;
    			$('#desc').css('opacity','0');
			//	$('#desc').html(tempHTML);
				descWidth = $('#desc').width();
				$('#loader').hide();
			//	$('#number').html(tempIndex + 1);
    			resizeImage(img);
    			$('#bigimage').css('left', oldx);
    			$('#bigimage').css('left', - parseInt($('#bigimage').css('left')));	
    			$('#bigimage').animate({left:0},{duration:400});
			}); 
		}});

	
	}
	
}
	
	function resizeImage(event) {
	
		var maxWidth = $(window).width() - 200; // Max width for the image
        var maxHeight = $(window).height() - 70;    // Max height for the image  // 110
        
        try {
        	width = img.width;    // Current image width
   			height = img.height;  // Current image height
   			
   			// Check if the current width is larger than the max
	        if(width >= height){
	            if (maxWidth / ratio < maxHeight) {
	            	event.width = maxWidth; // Set new width
	            	event.height = event.width / ratio;  // Scale height based on ratio
	            //	$("#imgdiv").css("width",maxWidth);
	            	$("#imgdiv").css("height",event.width / ratio);
	            } else {
	            	event.height = maxHeight;   // Set new height
	            	event.width = event.height * ratio;    // Scale width based on ratio
	            	
	            	$("#imgdiv").css("height",maxHeight);
	            //	$("#imgdiv").css("width",event.height * ratio);
	            }
	            
	        } else {
	            event.height = maxHeight;   // Set new height
	            event.width = event.height * ratio;    // Scale width based on ratio
	        
	            $("#imgdiv").css("height",maxHeight);
	         //   $("#imgdiv").css("width",event.height * ratio);
	            
   		
   		//$('#closebtn').parent().css('height', ((event.height / 2) - 25));
	        } 
	        
	        if($.browser.safari){
				$('#container').css('margin-top', $(window).height() / 2 - event.height / 2+ $('body').scrollTop() - 15);
				$('#loader').css('margin-top', $(window).height() / 2 + $('body').scrollTop());
			} else{ 
				$('#container').css('margin-top', $(window).height() / 2 - event.height / 2+ $('body,html').scrollTop() - 15);
				$('#loader').css('margin-top', $(window).height() / 2 + $('body,html').scrollTop());
			}
        		
   			//	$('#container').css('margin-left', $(window).width() / 2 - $('#containerTable').width() / 2);
				
			$('.tabella').css('height', event.height / 3);   
			$('#imgdiv').show();
   		} catch (err) {
   		
   		}
	}


  });

function capitaliseFirstLetter(string)
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}



$(function(){
// $("#nav3 li a").trigger("click");		
	 
/*  $(window).hashchange( function(){
					  $(".one").trigger("click");			
								 
    var hash = location.hash;
    document.title = 'RdC - ' + ( hash.replace( /^#/, '' ) || 'blank' ) + '.';
    $('#menu a').each(function(){
      var that = $(this);
      that[ that.attr( 'href' ) === hash ? 'addClass' : 'removeClass' ]( 'selected' );
    });
  })
  $(window).hashchange();*/
});

	
