var photoArr = [];
var curr = 0;
var ti = "";
var blockM = 0;

(function($){
	//Resize image on ready or resize
	$.fn.supersize = function() {	
		//Invoke the resizenow() function on document ready
		$(document).ready(function() {
			$('#supersize').resizenow(); 
		});
		//Invoke the resizenow() function on browser resize
		$(window).bind("resize", function() {
    		$('#supersize').resizenow(); 
		});


	};
	//Adjust image size
	$.fn.resizenow = function() {
		//Define starting width and height values for the original image
		//var startwidth = 1280;  
		//var startheight = 960;
		var startwidth = 1440;  
		var startheight = 1080;

		//Define image ratio
		var ratio = startheight/startwidth;
		//Gather browser dimensions
		var browserwidth = $(window).width();
		var browserheight = $(window).height();
		//Resize image to proper ratio
		if ((browserheight/browserwidth) > ratio) {
		    $(this).height(browserheight);
		    $(this).width(browserheight / ratio);
			$('#grid').height(browserheight);
			$('#grid').width(browserheight / ratio);
		    $(this).children().height(browserheight);
		    $(this).children().width(browserheight / ratio);
		} else {
		    $(this).width(browserwidth);
		    $(this).height(browserwidth * ratio);
			$('#grid').width(browserwidth);
		    $('#grid').height(browserwidth * ratio);
		    $(this).children().width(browserwidth);
		    $(this).children().height(browserwidth * ratio);
		}
		//Make sure the image stays center in the window
		$(this).children().css('left', (browserwidth - $(this).width())/2);
	        //ci va l'if per non far sparire il pulsante//	
        $(this).children().css('top', (browserheight - $(this).height())/2);
	};
})(jQuery);

function hideMenu() {
    if(blockM==0){
        blockM=1;
    	$('#menu3').animate({ opacity: 0 }, 300, function(){$('#menu2').animate({ opacity: 0 }, 300, function(){$('#menu1').animate({ opacity: 0 }, 300, function(){blockM=0;});});});
    	
    	$('#grid').css('cursor', 'pointer');
    	$('#grid').css('z-index', '50');
        
    	$('#grid').attr('title','visualizza menu').click(function() { menuBack(); });

    }
}

function menuBack() {
     if(blockM==0){
        blockM=1;
    	$('#menu1').animate({ opacity: 1 }, 300, function(){$('#menu2').animate({ opacity: 1 }, 300, function(){$('#menu3').animate({ opacity: 1 },300, function(){blockM=0;});});});
        $('#grid').unbind("click");        
/*	    $('#menu1').animate({ opacity: 1 }, 300);
	    $('#menu2').animate({ opacity: 1 }, 300);
	    $('#menu3').animate({ opacity: 1 }, 300);
*/	    $('#grid').css('z-index', '1');
	    $('#grid').css('cursor', 'default');
        
        
    }
}

function changeBkgd(bkgd,dida) {
	$("#dida").html(dida);

 	var img = new Image();
   // $(img).attr('src', 'images/'+bkgd);

	$(img).load(function () {
	     $(this).hide();	     
	     $('#supersize').html(this);
	     $(this).show();
	 }).error(function () {
	  // notify the user that the image could not be loaded
	});//chiudo error

	$("#supersize img").attr('src', 'images/'+bkgd);        
	$("div#supersize").supersize();

    hideMenu();

}

function changeBkgdNoHide(bkgd,dida) {
	$("#dida").html(dida);

 	var img = new Image();
   // $(img).attr('src', 'images/'+bkgd);

	$(img).load(function () {
	     $(this).hide();	     
	     $('#supersize').html(this);
	     $(this).show();
	 }).error(function () {
	  // notify the user that the image could not be loaded
	});//chiudo error

	$("#supersize img").attr('src', 'images/'+bkgd);        
	$("div#supersize").supersize();

}

function enableGallery(){
	$("#next").attr("onCLick","nextImg();");
	$("#prev").attr("onCLick","prevImg();");	
}

function disableGallery(){
	$("#next").removeAttr("onCLick");
	$("#prev").removeAttr("onCLick");
}

function nextImg(){
    //disabilito la galleria per 4 secondi
	disableGallery();
	setTimeout('enableGallery()',1000);
	
    //calcolo il prossimo curr		
	if(photoArr.length == 0){ curr=0;}
	else{ curr = (curr+1) % photoArr.length;}

	//metto la didascalia (e nascondo il div?)
	$("#dida").html(photoArr[curr][1]);
	//$("#dida:visible").css("dislay","none");
	
    //creo la nuova immagine
	var img = new Image();
	  $(img).load(function () {
	     $(this).hide();
	     
	     $('#supersize').html(this);
	     $(this).show();
	  }).error(function () {
	  // notify the user that the image could not be loaded
	  });
	  $("#supersize img").attr('src', 'images/'+photoArr[curr][0]);
	
    //chiamo supersize()
	$("div#supersize").supersize();

    //imposto il cursore e l'azione di aprire il menu se clicco
	$('#grid').css('cursor', 'pointer');
    $('#grid').unbind("click");
	$('#grid').click(function() { menuBack(); });	
	
    //faccio apparire/sparire la didascalia
	//setTimeout("$(\"#dida\").slideToggle(\"medium\")", 1000);
	//setTimeout("$(\"#dida\").slideToggle(\"medium\")", 4000);	
}

function prevImg(){
    //disabilito la galleria per 4 sec
	disableGallery();
	setTimeout('enableGallery()',1000);
	
    //calcolo il nuovo curr
	if(photoArr.length == 0){ curr=0;}
	else if(curr>0){ curr = (curr-1)}
	else{curr = photoArr.length-1;}
	
    //carico la didascalia e nascondo il div
	$("#dida").html(photoArr[curr][1]);
	//$("#dida:visible").css("dislay","none");;

    //creo la nuova immagine
	var img = new Image();
	  $(img).load(function () {
	     $(this).hide();
	     
	     $('#supersize').html(this);
	     $(this).show();
	  }).error(function () {
	  // notify the user that the image could not be loaded
	  });
	  $("#supersize img").attr('src', 'images/'+photoArr[curr][0]);
	
    //chiamo supersize
	$("div#supersize").supersize();
    
    //modifico il cursore
	$('#grid').css('cursor', 'pointer');
    
    $('#grid').unbind("click");
	$('#grid').click(function() { menuBack(); });	
	
    //faccio apparire/sparire la didascalia
	//setTimeout("$(\"#dida\").slideToggle(\"medium\")", 1000);
	//setTimeout("$(\"#dida\").slideToggle(\"medium\")", 4000);	

}

function toggleMenu(divid) {
   
	if (divid == "#menu1_content" || divid == "#text" ) {
		$("#menu2:visible").slideToggle("medium");
		$("#menu3:visible").slideToggle("medium");
	}
	if (divid == "#menu2") {
		$("#menu2:visible").slideToggle("medium");
		$("#menu3:visible").slideToggle("medium");
		$("#text:visible").slideToggle("medium");
	}
    
	$("#text").removeAttr("class");
	//$("#dida:visible").slideToggle("medium");
	$(divid).find("span.plus_add").remove();
	$(divid).slideToggle("medium");
	return false;
}


function setupThumb() {
	// manage image thumbnails opacity
	$('.thumb').mouseover(function() {
		$(this).animate({ opacity: 1 }, 300);
		return false; 
		});
	$('.thumb').mouseout(function() {
		$(this).animate({ opacity: 0.85 }, 300);
		return false; 
		});
}

function setupGallery() {
        
	$("#gallery_left").click(function() { 
        largW = $(window).width();

        left = $("#gallery_content").css('margin-left').split("px");
        left = left[0]-1+1;

        ldiv =  $("#gallery_content").css('width').split("px");      
        ldiv = ldiv[0]-1+1;

        if(ldiv<=largW){
            $("#gallery_left").css('display','none');
        }
        else{

            if(left>=0)
                left = 0;
            else{
                
                if(-left<=largW){
                    left = 0
                    $("#gallery_left").css('display','none');
                }
                else{ left = left+largW; }
            $("#gallery_right").css('display','block');
         }
         $("#gallery_content").animate({ "margin-left": (left)+'px' }, 400);                                                         
        }

	});

    //ci va l'if per non far sparire il pulsante//
	$("#gallery_right").click(function() { 

        largW = $(window).width();

        left = $("#gallery_content").css('margin-left').split("px");
        left = left[0]-1+1;

        ldiv =  $("#gallery_content").css('width').split("px");      
        ldiv = ldiv[0]-1+1;

        if(ldiv<=largW){
            $("#gallery_right").css('display','none');
        }
        else{

            if((-(left)+largW)>= ldiv)
                left = -(ldiv-largW);
            else{
                left = left-largW;
                if(ldiv+left<largW){
                    left = -(ldiv-largW);
                    $("#gallery_right").css('display','none');
                }
            $("#gallery_left").css('display','block');
            }
            $("#gallery_content").animate({ "margin-left": (left)+'px' }, 400);                                                         
        }
	});
  
        
	$("#gallery_content a").click(
        function() {
            curr = ($(this).attr("ord"))-1; 
            //$("div#supersize").supersize();
            $("div#supersize").resizenow();
            changeBkgd($(this).attr('rel'), photoArr[curr][1]);
            
            
        }
    );
    
}

function showGallery(id) {
	$('#galleries a').removeClass('active');
	id = id.replace("pj_", "");
//	alert('gallery: '+id);
	$('#fotogallerydata').load('fotogallery.php', { 'id' : id });
//    changeBkgd(photoArr[0][0],photoArr[0][1]);    
}

function checkStudio(button){
        if(ti!="" && button=="studio"){
            $('#menu4').html("<img src=\"images/currImg/"+ti+"\"/>");
            $('#menu4').slideToggle('medium');        
        }

}

function loadMenu(button) {
	// hide eventually open menu div
    //alert($("#menu4").css("opacity"));
    f1=f2=false;

    if(!($("#menu4").css("display")=="none")){
	    $("#menu4").slideToggle("medium", function(){if($("#menu2").css("opacity")==1){$("#menu2").slideToggle("medium");}});
        f1=true;    
    }
    
    
    if(!($("#menu3").css("display")=="none")){
        $("#menu3").slideToggle("medium", function(){if($("#menu2").css("opacity")==1){$("#menu2").slideToggle("medium");}});
        f2=true;
    }	


    if(!f1 && !f2 && !($("#menu2").css("display")=="none")){
        $("#menu2").slideToggle("medium");
    }
    //setTimeout("$(\"#menu2:visible\").slideToggle(\"medium\")",400);
	
	// load and toggle new content
	if ($(button).attr('class') != 'active') {
		url = 'menu.php?m='+$(button).attr('rel');
		setTimeout("$(\"#menu2\").load(url,function(){ $('#menu2').slideToggle('medium', function(){checkStudio('"+$(button).attr('rel')+"');}); bindMenuActions(); });", 800);


		// active class for buttons
		$('.menuitems a').removeClass('active');
		$(button).addClass('active');
	} else {
		$('.menuitems a').removeClass('active');
	}
	
}

function bindMenuActions() {
	// re-bind actions
	$('#menu2 a').click(function() { loadPrj($(this)) });
}

function loadPrj(button) {
	$('#categories a').removeClass('active');
	$(button).addClass('active');
	// hide eventually open detail div
	$("#menu3:visible").slideToggle("medium");
    t = $('#categories a.active').html();
	//$("#projects").load('projects.php',{'t':t});
	//setTimeout("$(\'#projects a\').click(function() { loadDetail($(this)); })", 200);
    if($(button).attr("id")!="regesto"){
        setTimeout("$(\"#projects\").load('projects.php',{'t':t})", 200);            
    }
}

function loadDetail(button) {
	$('#projects a').removeClass('active');
	$(button).addClass('active ' + $(button).attr("class"));
	// hide eventually open detail div
	$("#menu3:visible").slideToggle("medium");
    if($(button).attr("class").indexOf("NOFG")==-1)
        setTimeout("$(\"#menu3\").load('detail.php',{'id':$(\"#projects a.active\").attr(\"id\")} ,function(){ $('#menu3').slideToggle('medium'); setupThumb(); setupGallery() });", 400);
	//setTimeout("$(\"#menu3\").load('detail.php',function(){ $('#menu3').slideToggle('medium'); setupThumb(); setupGallery() });", 400);
}

function loadDetailReg(id) {
    setTimeout("$(\"#menu3\").load('detail.php',{'id':'"+id+"'} ,function(){ $('#menu3').slideToggle('medium'); setupThumb(); setupGallery() });", 400);
	//setTimeout("$(\"#menu3\").load('detail.php',function(){ $('#menu3').slideToggle('medium'); setupThumb(); setupGallery() });", 400);
}

function loadRegCat(button){
	$('#projects a').removeClass('active');
	$(button).addClass('active');
	// hide eventually open detail div
	$("#menu3:visible").slideToggle("medium");
/*    setTimeout("$(\"#menu3\").load('detail.php',{'id':$(\"#projects a.active\").attr(\"id\")} ,function(){ $('#menu3').slideToggle('medium'); setupThumb(); setupGallery() });", 400);
  */  
}

function loadStaff() {
	setTimeout("$(\"#menu4\").load('staff.php',{'id':$(\"#projects a.active\").attr(\"id\")} ,function(){ $('#menu4:hidden').slideToggle('medium'); });", 400);
}

function loadTeam() {
	setTimeout("$(\"#menu4\").load('team.php',{'id':$(\"#projects a.active\").attr(\"id\")} ,function(){ $('#menu4:hidden').slideToggle('medium'); });", 400);
}

function sendMail(){
     if(!$('#contact-form').attr('id')) return ;   
     var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
     var address = $('#email').attr("value");

     if($('#name').attr("value")==""){
        alert('Nome non valido');
        return false;
     } 
     else if(reg.test(address) == false) {
        alert('Indirizzo email non valido');
        return false;
     }
     else if($('#message').attr("value")==""){
        alert('Inserire un testo per il messaggio');
        return false;
     } 
     else{
        $.post("menu.php?m=sendmail", $('#contact-form').serialize(), function(data){alert(data);});
     }
}

$(document).ready(function() {
	// apply supersize to background div
 //   $.post("menu.php?m=getHomeFG",{},function(data){photoArr = data; alert(photoArr);})
 //   $("div#supersize img").attr("src", "images/"+photoArr[0][0]);
    changeBkgdNoHide(photoArr[0][0],photoArr[0][1]);    
	
	//$("div#supersize").supersize();
	// bind cllick actions
	$('.menuitems a').click(function() { loadMenu($(this)); });
    $("#logo").css("cursor", "pointer").click(function(){menuBack();})

	// enable gallery
	enableGallery();

	$(document).keyup(function(e){
	    switch (e.keyCode){ 
	       	case 37:
				prevImg();
				break;
			case 39:
				nextImg();
				break;
	    }
	});
    
   

});

