// Sets (and binds on resize) the correct height to "elem" in order to fit the window
function setContentMargin(elem, position) {
  calculateMargin(elem, position);
  $(window).resize( function() {
    calculateMargin(elem, position);
  });
  $(window).scroll( function() {
    calculateMargin(elem, position);
  });
}
// Calculates the correct height to "elem" in order to fit the window
// position can be:
// "centered" 
// "footer"
function calculateMargin(elem, position) {
  var winH = $(window).height();
  var winW = $(window).width();
  var elH = elem.outerHeight();
  var elW = elem.outerWidth();

  if(elem.attr("id") == 'cde-www'){
    var marginLeft = (320 - elW)/2;
    elem.css("margin-left",marginLeft+"px");
  }
  else if(elem.attr("id") == 'social-network-box'){
    var marginLeft = (winW/2-($('#social-network-box').width()/2)-elW)-10;
    elem.css({
     "margin-left": marginLeft+"px",
     "left": "0px",
     "position": "absolute"
    });
    winH = winH - 50;
  }
  else if(elem.attr("id") == 'casse'){
  	var marginLeft = winW/2-(364/2)-elW;
    elem.css("margin-left",marginLeft+"px");
    winH = winH - 50;
  }
  else{
    var marginLeft = (364 - elW)/2;
    elem.css("margin-left",marginLeft+"px");
    winH = winH - 50;
  }
  var id = elem.attr("id");
  var minW = -1;
    
  if(position == "centered"){
    switch(id){
      case "logo":
        minW = 63;
      break;
      case "cde-www":
        minW = 347;
      break;
    }
    var marginTop = (winH - elH)/2;
    if(minW != -1){
      if(marginTop < minW){
        marginTop = minW;
      }
    }
    elem.css("margin-top",marginTop+"px");
  }
  else if(position == "footer"){
    switch(id){
      case "casse":
        minW = 282;
      break;
      case "social-network-box":
        minW = 279;
      break;
      case "email":
        minW = 550;
      break;
    }
    if(elem.attr("id") == 'casse')
      var marginTop = (winH - (elH) + 50);
    else
      var marginTop = (winH - (elH) + 45);
      
    if(minW != -1){
      if(marginTop < minW){
        marginTop = minW;
      }
    }
    elem.css("top",marginTop+"px");
  }
}

function setContentHeight(elem, top, bottom) {
  calculateHeight(elem, top, bottom);
  $(window).resize( function() {
    calculateHeight(elem, top, bottom);
  });
  $(window).scroll( function() {
    calculateHeight(elem, top, bottom);
  });
}
// Calculates the correct height to "elem" in order to fit the window
function calculateHeight(elem, top, bottom) {
  if(elem.attr("id") == "news-container"){
    var winH = $(window).height();
    var unit = 200;
    var n = 1;
    while(winH > unit*n){
      n++;
    }
    var winH = unit*(n-1);
    if(winH == 200){
      winH = 400;
    }
  }
  else{
    var winH = $(window).height();
  }
  elem.height(winH - top - bottom);
}


function getTwitterMexs(){
	$("<div id='twitterContainer' style='position: absolute; opacity: 0; text-align: center'></div>").appendTo("body");
	$("<div id='twitterBox' style='text-align: center'><img src='images/ajax-loader-small-black.gif' style='margin-top: 22px'></div>").appendTo('#twitterContainer');
	$("<div id='twitterTriangle'><img src='images/triangolino.png'/></div>").appendTo("#twitterContainer");
  //get the position of the placeholder element
	var pos = $(".social-network-button.twitter-button").offset();  
	var width = $(".social-network-button.twitter-button").width();
	//show the menu directly over the placeholder
	$("#twitterContainer").css( { "left": (pos.left- 5) + "px", "bottom": "38px" } );
	$("#twitterContainer").show(1000);
	$("#twitterContainer").animate({bottom: "+=5px", "opacity": 1}, { duration: 1000, queue: false });

	$.ajax({
   type: "GET",
   url: "http://www.chiavedies.it/twitter_test.php",
   data: "",
   success: function(request){
   		// creo un ul
   		var ul = $("<ul></ul>").hide();

      $(request).find("status").each(function() {
      		var li = $("<li></li>");
          var el = $(this);
          var txt = el.find('text').text();
          if(txt.indexOf("http") != -1){
          	var before = txt.substring(0,txt.indexOf("http"));
          	var restante = txt.substring(txt.indexOf("http"),txt.length-1);
          	if(restante.indexOf(" ") != -1){
          		var http = restante.substring(0, restante.indexOf(" "));
          		var after = restante.substring(restante.indexOf(" "), restante-length-1);
          	}
          	else{
          		var http = restante;
          		var after = "";
          	}
          	
          	txt = before+" <a href='"+http+"' target='_blank' class='twitter-link'>"+http+"</a> "+after;
          }
          var data = el.find('created_at:first').text();
          var span1 = $("<span class='twitter-text'></span>").html(txt+" ").appendTo(li);
          var link = 'http://www.twitter.com/ChiaveDiEs/statuses/'+el.find('id:first').text();
          var span2 = $("<span class='twitter-data'></span>");
          $("<a href='"+link+"' target='_blank'>"+difference(data)+"</a>").addClass('twitter-data').appendTo(span2);
          span2.appendTo(li);
          
          // aggiungo l'elemento all'ul
          li.appendTo(ul);
      });
      $('#twitterBox > img').remove();  
      
      ul.appendTo("#twitterBox");
      
      $("<div></div>").addClass('twitter-follow-us').appendTo('#twitterBox');
      $("<a></a>").attr({
      	href: 'http://www.twitter.com/ChiaveDiEs',
      	target: '_blank'
      }).text('Seguici su Twitter >>').appendTo(".twitter-follow-us");
      
      
      ul.show(500);
      $("#twitterContainer").css( { "left": ($("#twitterContainer").offset().left - $("#twitterContainer").width()/2 -7) + "px" } );
      $('#twitterBox').fadeIn(500);
      
      document.getElementById("twitter-button").setAttribute("onclick", "hideTwitterMexs(); return false;" );
   }
 });
}

function hideTwitterMexs(){
	var e = document.getElementById("twitterContainer");
	e.parentNode.removeChild(e);
	document.getElementById("twitter-button").setAttribute("onclick", "getTwitterMexs(); return false;" );
}

function difference(oldtime) {
	var nowtime = new Date();
	oldtime = new Date(oldtime);
	var milliseconds1 = oldtime.getTime();
	var milliseconds2 = nowtime.getTime();
	var difference = milliseconds2 - milliseconds1;
	var daysDifference = Math.floor(difference/1000/60/60/24);
	difference = difference - daysDifference*1000*60*60*24
	var hoursDifference = Math.floor(difference/1000/60/60);
	difference = difference - hoursDifference*1000*60*60
	var minutesDifference = Math.floor(difference/1000/60);
	difference = difference - minutesDifference*1000*60
	var secondsDifference = Math.floor(difference/1000);
	// This next line below looks for entries over a day old
	if (daysDifference > 1) return(daysDifference + ' days, ' + hoursDifference + ' hours, ' + minutesDifference + ' minutes ago');
	else if (hoursDifference < 1) return(minutesDifference + ' minutes ago');
	else if (hoursDifference < 4) return(hoursDifference + ' hours, ' + minutesDifference + ' minutes ago');
	else if (hoursDifference < 24) return(hoursDifference + ' hours ago');
	else return(' ');
} 

function showMailForm(){
	$('#mailForm').css({ display: 'block', "z-index": 10 });
	$("#mailForm").animate({top: "-=5px", "opacity": 1}, { duration: 1000, queue: false });
}
function hideMailForm(){
	$("#mailForm").animate({top: "+=5px", "opacity": 0, "z-index": -1}, { duration: 1000, queue: false });
	setTimeout("$('#mailForm').css({ display: 'block', 'z-index': -1 })",1000);
}

function setFlickrContent(api_key, photoset_id){

	var url = "http://api.flickr.com/services/rest/?";
	var resource = "method=flickr.photosets.getPhotos";
	var format = "&format=json";
	var link = url + resource + "&api_key="+api_key+"&photoset_id="+photoset_id+format;
	toLog(link);
	$('<script>').attr("src",link).appendTo('head');
}

function jsonFlickrApi(data){
			/*
				s	quadratino 75 x 75
				t	miniatura, 100 sul lato piť lungo
				m	piccolo, 240 sul lato piť lungo
				-	medio, 500 sul lato piť lungo
				b	grande, 1024 sul lato piť lungo (solo per immagini originali molto grandi)
				o	immagine originale jpg, gif o png, in base al formato di origine
			*/
		var ul = $("<ul>").attr("id","gallery").css({display: "none"});
		
		$.each(data.photoset.photo, function(i,item){
			var li = $('<li>');
			if(i == 0){
				$('#menu-img').attr("href","http://farm"+item.farm+".static.flickr.com/"+item.server+"/"+item.id+"_"+item.secret+".jpg").attr("title",item.title).attr("rel","cde");
				toLog("http://farm"+item.farm+".static.flickr.com/"+item.server+"/"+item.id+"_"+item.secret+".jpg");
			}
			else{
			//  http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)
			var a = $('<a>').attr("id","img").attr("href","http://farm"+item.farm+".static.flickr.com/"+item.server+"/"+item.id+"_"+item.secret+".jpg").attr("title",item.title).attr("rel","cde").html("pppp");
			a.appendTo(li);
			li.appendTo(ul);
			}
		});
		ul.appendTo("body");
		$("[rel='cde']").colorbox({rel:'cde'});

}

function checkForm(){
	if($('#mex_name').attr('value')	 == ""){
		$('#mex_name').css({border: '#E27E20 1px solid'});
		$('#mex_name').focus();
		return false;
	}
	else if($('#mex_emailbox').attr('value')	 == ""){
		$('#mex_emailbox').css({border: '#E27E20 1px solid'});
		$('#mex_emailbox').focus();
		return false;
	}
	else if($('#mex_mex').attr('value')	 == ""){
		$('#mex_mex').css({border: '#E27E20 1px solid'});
		$('#mex_mex').focus();
		return false;
	}
	var name = $('#mex_name').attr('value');
	var email =  $('#mex_emailbox').attr('value');
	var testo = $('#mex_mex').attr('value');
	testo = testo.replace(/\&/g,"'e-");
	testo = testo.replace(/\?/g,encodeURIComponent("?"));
	testo = testo.replace(/\"/g,"''");
	jQuery.ajax({
   	type: "GET",
   	url: "http://www.chiavedies.it/web/mail.php",
   	data: "name="+name+"&email="+email+"&mex="+testo,
   	success: function(data){
   		alert(data);
    	if(data == "true"){
				$('#formAlert').html("Messaggio inviato");
				setTimeout("resetForm()",2000);
			}
			else if(data == "mail false"){
				$('#formAlert').html("La mail che hai inserito non &egrave; valida");
				$('#mex_emailbox').css({border: '#E27E20 1px solid'});
				$('#mex_emailbox').focus();
			}
			else{
				$('#formAlert').html("Ops, si &egrave; verificato un errore. Prova a inviarci una mail all'indirizzo sottostante.");
				//setTimeout("resetForm()",2000);
			}
  	}
 	});
}

function resetForm(){
	hideMailForm();
	$('#mex_name').attr('value','');
	$('#mex_name').css({border: 'none'});
	$('#mex_emailbox').attr('value','');
	$('#mex_emailbox').css({border: 'none'});
	$('#mex_mex').attr('value','');	
	$('#mex_mex').css({border: 'none'});
	$('#formAlert').html("");
}

var CDEPLAYER = new Player();
	 	
window.onload = function(){
	CDEPLAYER.init();
	
	$('#email').click(function(){
		showMailForm();
	});
	 
  setContentMargin($('#logo'), "centered");
  setContentMargin($('#cde-www'), "centered");
  setContentMargin($('#email'), "footer");
  setContentMargin($('#social-network-box'), "footer");
  setContentMargin($('#casse'), "footer");
  
  setContentHeight($('#news-box'), 0, 210);
  setContentHeight($('#news-container'), 0, 200);
  
  // t-shirt a random
  var imgArray = ["t-shirt_black_thumb.png","t-shirt_colored_thumb.png","t-shirt_white_thumb.png"];
  var randomnumber=Math.floor(Math.random()*2)+1;
  $('#t-shirt-img').attr("src","images/"+imgArray[randomnumber]);
  
  //t-shirt open window with big images
  $('.t-shirt-img').each(function(i, img){
    img.onclick = function(){
      window.open(this.src.replace("_medium",""),'Maglietta dei Chiave di Es','width=610,height=640');
      return false;
    };

  });
  
  setFlickrContent("e6733d39571ea5670bbcac7ead70579a","72157622938256294");
  
  $("#caricamento").fadeOut("slow");
  
  
}
