$(document).ready(function(){
  
  $("a.backToTop").click(function(){
    $(document).scrollTo(0, 500);
    return false;
  })
  
  //carica il tema della galleria immagini
  Galleria.loadTheme('../../css/galleriaTheme/galleria.classic.min.js');
    
  Cufon.set('fontFamily', 'Gotham Rounded').replace('div.sectionHeader h1');
  Cufon.set('fontFamily', 'Gotham Rounded').replace('div.sectionHeader h2');
  Cufon.set('fontFamily', 'Gotham Rounded').replace('ul.nav a');
  Cufon.set('fontFamily', 'Gotham Rounded').replace('.cufon', { hover: true });
  Cufon.set('fontFamily', 'Gotham Rounded Book').replace('.cufonNav', { hover: true });
  
  resizeImageBoxesHome()
  resizeImageBoxes()
  $(window).resize(function(){
    resizeImageBoxesHome()
    resizeImageBoxes()
  })
  
  function resizeImageBoxesHome(){
    var ratio = 450 / 800;
    var width = $('.rightBox:first').width();
    var height = width * ratio;
    $('.rightBox').height(height);
    $('.boxImg').posterwall({vertical_center:1, ratio:[800,450], min_size:[500, 281], container:$('.rightBox')});
  }  
  
  
  function resizeImageBoxes(){
    var ratio = 450 / 800;
    var width = $('.imageBoxContainer').find('.imageBox:first').width();
    var height = width * ratio;
    $('.imageBoxContainer').find('.imageBox').height(height);
    $('.imageToResize').posterwall({vertical_center:1, ratio:[800,450], min_size:[300, 170], container:$('.imageBoxContainer').find('.imageBox')});
  }
  
  /*$("img.imageToResize").each(function(){
    var container = $(this).parents("div.imageBox")
    $(this).posterwall({
      vertical_center:1, 
      ratio:[800, 545], 
      min_size:[300, 204],   
      container: container
    });
  })*/
  
  //paginazione dinamica via ajax
  var currentPage = 0
  var currentPageGallery = 0
  var isLoadingPage = false;
  var isLoadingPageGallery = false;
  
  if($("#loadingRecordsGallery").length>0)
    loadGalleryPage()
  
  if($("#loadingRecordsHome").length>0)
    loadNewsHome()
    
  if($("#loadingRecords").length>0)
    loadNews()
  
  $(window).scroll(function(){    
    if($(window).scrollTop() == $(document).height() - $(window).height()){      
      if(!isLoadingPage && $("#loadingRecordsHome").length>0)
        loadNewsHome()       
      
      if(!isLoadingPage && $("#loadingRecords").length>0)     
        loadNews()              
      
      if(!isLoadingPageGallery && $("#loadingRecordsGallery").length>0)    
        loadGalleryPage()      
    }
  });
  
  
  function loadNewsHome(){
    
    $("#loadingRecordsHome").show()
    isLoadingPage = true;
    
    $.ajax({
			type: "GET",
			url: "ajax.asp?page="+(currentPage+1)+$("#loadingRecordsHome").attr("data-params"),
      dataType: "html",
			success: function(data){
        
          setTimeout( function(){
            currentPage += 1;
            isLoadingPage = false;
            $("#loadingRecordsHome").hide()
            
            $("#loadingRecordsHome").before('<div rel="'+currentPage+'" syle="display:none;">'+data+'</div>')
            
            $("div[rel='"+currentPage+"']").fadeIn(300)
            
            resizeImageBoxesHome()
            
            //$(document).scrollTo(($(window).scrollTop()+200), 800)
            
            if($("div[rel='"+currentPage+"']").find("div.rightBox").length < parseInt( $("#loadingRecordsHome").attr("data-numRecords")))
              $("#loadingRecordsHome").remove()
          
          }, 500)
      },
			error: function(XMLHttpRequest, textStatus, errorThrown){
			   alert(textStatus);
			}
		});
  }
  
  function loadNews(){
    $("#loadingRecords").show()
    isLoadingPage = true;
    
    $.ajax({
			type: "GET",
			url: "ajax.asp?page="+(currentPage+1)+$(".genricContent").attr("data-params"),
      dataType: "html",
			success: function(data){
        
          setTimeout( function(){
            currentPage += 1;
            isLoadingPage = false;
            $("#loadingRecords").hide()
            
            $("#tempContainer").html(data)
            
            
            $("#tempContainer").find("div.newsBlock").hide()          
            $("#loadingRecords").before('<div rel="'+currentPage+'">'+$("#tempContainer").html()+'</div>')
            
            $("div[rel='"+currentPage+"']").find("div.newsBlock").fadeIn(300)
            if(currentPage>1)
              $(document).scrollTo(($(window).scrollTop()+150), 800)
            
            if($("#tempContainer").find("div.newsBlock").length < parseInt( $("div.genricContent").attr("data-numRecords")))
              $("#loadingRecords").remove()
          
          }, 500)
      },
			error: function(XMLHttpRequest, textStatus, errorThrown){
			   alert(textStatus);
			}
		});
  }
  
  function loadGalleryPage(){
    if(currentPageGallery>0)
      $("#loadingRecordsGallery").show()
    else if(currentPageGallery==0)
      $("#firstLoading").fadeIn("fast")
    isLoadingPageGallery = true;
        
    $.ajax({
      url: "ajax.asp?page="+(currentPageGallery+1)+$(".imageBoxContainer").attr("data-params"),
      dataType: "json",
      success: function(data){ 
        if(data.immagini.length>0){
          var imgArray = []
          for(var i=0;i<data.immagini.length;i++){
            var img = data.immagini[i]
            imgArray.push(String(img.src))
            var imgBox = '<div class="imageBox" data-download="'+img.download+'" data-href="'+img.srcFull+'" data-page="'+String(currentPageGallery)+'" style="display:none;">'+
                            '<img src="'+img.src+'" class="imageToResize" title="'+img.descrizione+'" />'+
                            '<div class="pattern"></div>'+
                            '<div class="imgTitle">'+
                              '<h3>'+img.descrizione+'</h3>'+
                            '</div>'+
                          '</div>';
            
            $(".imageBoxContainer").find("div.c").before(imgBox)
          }
          
          $(".imageBoxContainer[rel='gallery']").find("div.imageBox[data-page='"+currentPageGallery+"']").colorbox({
            title: function(){
              var myTitle = $(this).find('h3').text();
              return "<h3 class=\"colorboxH3\">"+myTitle+"</h3>"+
                      "<a class=\"colorBoxDwn\" href=\""+$(this).attr('data-download')+"\" title=\"Download HD Image\"><img src=\"../../images/downloadHD.png\" alt=\"Download immagine HD\" /></a>"+
                      "<div class=\"c\"></div>"
              },
            href: function(){
              return $(this).attr('data-href')
            },
            photo: true,
            opacity: 0.5,
            //onComplete: function(){ $.colorbox.resize() },
            onOpen: function(){
              isLoadingPageGallery=true;
            },
            onClosed: function(){
              isLoadingPageGallery=false;
            },
            scrolling: false
          });
          
          $.loadImages(imgArray, function(){ setTimeout(function(){
            $("#firstLoading").fadeOut("fast")
            $("div.imageBox[data-page='"+currentPageGallery+"']").fadeIn(300)
            isLoadingPageGallery = false;
            resizeImageBoxes();
            if(currentPageGallery > 1)
              $(document).scrollTo(($(window).scrollTop()+$('.imageBoxContainer').find('.imageBox:first').height()), 800)
            currentPageGallery += 1;
            
            
            $("#loadingRecordsGallery").hide()
            if(String(data.finito)=="true")
              $("#loadingRecordsGallery").remove()
          }, 300)  })              
          
        }else{
          $("#firstLoading").hide()
          $("#loadingRecordsGallery").remove()
          $("div.noRecords").fadeIn("fast")
        }
      },
      error: function(){
        //alert("C'è stato un errore durnte il caricamento dei dati.")
      }
    })
  }
  
})


/*funzioni di utilità*/

function Trim(strq)
{
	while(strq.indexOf(" ")==0)
	{
		if(strq.length > 0)
			strq = strq.replace(" ", "");
		else
			break;
	}
	
	while(strq.lastIndexOf(" ")==strq.length-1)
	{
		if(strq.length > 0)
			strq = strq.substring(0, strq.length-1);
		else
			break;
	}
		
	return strq;
}

/*gestione ajax*/
$.ajaxSetup({"error":function(XMLHttpRequest,textStatus, errorThrown) {   
    //alert(textStatus);
    alert(errorThrown);
    alert("errore: "+XMLHttpRequest.responseText);
}
})

