// JavaScript Document
var hasLoadedFriends = false;
$(document).ready(function () {
	//facebook init
	FB.init({
		appId: '126108977407493',
		status: true,
		cookie: true,
		xfbml: true
	});
	FB.Event.subscribe('auth.login', function () {
		//window.location.reload();
		FB.getLoginStatus(function(response) {
  if (response.authResponse) {
	  checkUser();
    // logged in and connected user, someone you know
  } else {
    // no user session available, someone you dont know
  }
});
		
	});
	
	//only on index.php
	$(".moreinfo").click(function () {
		/*alert ($(this).attr('ccc:url') != '0');
		alert ($(this).attr('ccc:url'));*/
		if ($(this).attr('ccc:url') != '0') {
				window.location.href = $(this).attr("ccc:url");
			} else {
				$(this).siblings(".infocontent").toggle("slow");
				$(".thevideo").hide();
		};
		
		
	});
	
	$("#partecipobutton").click(function () {
		adduidbiglietti();
		pubblicabiglietti();
		cambiapartecipo();
		return false;	
	});
	
	$(".mostraAmici").click(function () {
		amiciEvento(this, $(this).attr("ccc:eid"), $(this).attr("ccc:class"));
		return false;
	});
	
	$(".presstitle").click(function() {
		$(this).siblings(".presscontent").toggle();
	});
	
	$(".presscontent").first().show();
	
	$(".eventtable .inputbutton").click(function () {
		rispondo_evento($(this).parents("table").attr("ccc:eid"), $(this).attr("ccc:answer"));
		return false; 
	});
	//only on loc.php
	$("#locButton").click(function () {
		var sess = FB.getSession();
		var sessuid = sess.uid;
		FB.api('/' + sessuid + '?fields=picture&type=large', function (response) {
			var theUser = sessuid;
			var theUrl = response.picture;
			$.post("addLoc.php", {
				theUser: theUser,
				theUrl: theUrl
			}, function (data) {
				//$("#loc_txt").html("La tua foto &egrave; stata salvata.<br /><b>Grazie per i tuoi 30.000 pixel!</b>");
				$("#loc_txt").html("<img src='images/grazie30000.png' />");
			});
			publishLoc();
			//publishLocLink();
		});
		return false;
	});
	//only on guests.php
	$(".oneguest").hover(
	function () {
		var thisdiv = $(this);
		var coord = thisdiv.position();
		thisdiv.find(".guestname").show('fast');
		thisdiv.after($("#tempguest").attr("class", thisdiv.attr("class")).show());
		thisdiv.css({
			width: "246px",
			height: "300px",
			border: "5px solid #ddd",
			top: (coord.top - 66) + "px",
			left: (coord.left - 39) + "px",
			position: "absolute",
			zIndex: "100"
		});
	}, function () {
		var thisdiv = $(this);
		$("#tempguest").hide();
		thisdiv.find(".guestname").hide('fast');
		thisdiv.css({
			width: "176px",
			height: "176px",
			border: "1px solid #ddd",
			top: "",
			left: "",
			position: "inherit",
			zIndex: "1"
		});
	});
	
	$("#publishcpdn").click(function() {
		publishCpdn();
		return false;
	});
	$(".onemerch a").lightBox();
	$(".oneclub a").lightBox();
	//only on gallery.php
	$(".onealbum").click(function () {
		var album = $(this).attr("ccc:aid");
		$(".onealbum").not($(this)).hide('slow', function () {
			$('#photos').show('slow', function () {
				$("#photos").load("album.php", {
					album: album
				}, function () {
					$(".aid" + album + " a").lightBox();
					$("#back").show('slow');
				})
			})
		});
	});
	$("#back").click(function () {
		$('#back').hide('slow');
		$("#photos").hide('slow', function () {
			$("#photos").html('<img src="images/caricoimmaginio.png" />');
			$(".onealbum").show('slow');
		});
	});
	
	$(".presskit .onepress:nth-child(5n)").css("marginRight", "0px");
});

function showVideo(obj, url) {
	$(".thevideo").hide();
	$("#myytplayer").css("id", "nov");
	$(obj).siblings(".thevideo").show();
	var theId = $(obj).siblings(".thevideo").children(".videoContainer").attr("id");
	var params = {
		allowScriptAccess: "always"
	};
	var atts = {
		id: "myytplayer"
	};
	swfobject.embedSWF("http://www.youtube.com/v/" + url + "?autoplay=1&enablejsapi=1&playerapiid=ytplayer", theId, "425", "344", "8", null, null, params, atts);
}

function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("myytplayer");
	ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
	if (newState == 0) $(".thevideo").hide();
}

function sendmail() {
	var nome = $("#prenome").val();
	var cognome = $("#precognome").val();
	var oggetto = $("#preoggetto").val();
	var email = $("#preemail").val();
	var cell = $("#precell").val();
	var mess = $("#premess").val();
	$("#mailresult").load("mail.php", {
		nome: nome,
		cognome: cognome,
		oggetto: oggetto,
		email: email,
		cell: cell,
		mess: mess
	});
}

function checkUser() {
	var sess = FB.getSession();
	//console.log(sess);
	var sessuid = sess.uid;
	//alert(sessuid);
	var query = FB.Data.query('select name, email from user where uid={0}', sessuid);
	query.wait(function (rows) {
		var email = rows[0].email;
		var name = rows[0].name;
		$.post("checkuser.php", {
			sessuid: sessuid,
			email: email,
			name: name
		}, function (data) {
			window.location.reload();
			//alert(data);
		});
	});
}

function rispondo_evento(evento, risposta) {
	var url = '/' + evento + '/' + risposta;
	FB.api(url, 'post', function (response) {
		if (risposta == 'attending') {
			var testo = "SI";
		};
		if (risposta == 'maybe') {
			var testo = "FORSE";
		};
		if (risposta == 'declined') {
			var testo = "NO";
		};
		var html = "Hai risposto <b>" + testo + "</b>. Se vuoi puoi cambiare la risposta qui sotto.";
		//$("#eventtable"+evento).hide();
		$("#rispostaEvento" + evento).html(html);
	});
}

function fblogout() {
	FB.logout(function (response) {
		window.location.reload();
	});
}
function amiciEvento(obj, evento, classe) {
	var sess = FB.getSession();
	var sessuid = sess.uid;
	var html = '';
	var eid = evento;
	//FB.api('/'+eid+'/attending?fields=id', function(response){console.log(response);})
	var countAtt = 0;
	var countTot = 0;
	var thePA = $(obj).parents(".portaAmici");
	thePA.html('<img src="loader.gif" />');
	/*var query = FB.Data.query('select uid, rsvp_status FROM event_member WHERE eid={0} AND uid IN (SELECT uid2 FROM friend WHERE uid1={1})', eid, sessuid);
	query.wait(function (rows) {
		//console.log(rows);
		FB.Array.forEach(rows, function (row) {
			if (row.rsvp_status == 'attending') {
				if (countAtt < 34) {
					html += '<img src="http://graph.facebook.com/' + row.uid + '/picture" width="35"/>';
					countAtt++;
					countTot++;
				} else {
					countTot++;
				}
			}
		}); //rows.foreach
		thePA.html(html);
		thePA.prev("h4").append(" (" + countTot + ")");
		//console.log(countTot);
	}); //wait*/
	$.post("f_amiciEvento.php", {eventeid:eid, classe:classe}, function(data){
		for (key in data[1]) {
			html += '<img src="http://graph.facebook.com/' + data[1][key] + '/picture" width="35"/>';
		}
		thePA.prev("h4").append(" (" + data[0] + ")");
		thePA.html(html);
		//console.log(data);
		}, "json");
}

function adduidbiglietti() {
	var sess = FB.getSession();
	var sessuid = sess.uid;
	$.post("adduidbiglietti.php", {suid:sessuid});
}

function cambiapartecipo() {
	$("#partecipo").html("Grazie per aver aderito!<br />Attendi l'estrazione di sabato pomeriggio!");
}

function publishLoc() {

var publish = {
  method: 'stream.publish',
  message: 'Ho prenotato un posto sulla locandina di fine stagione. Prenotalo anche tu! http://tinyurl.com/jubiloc',
  attachment: {
    name: 'jubilee - 17 MEGAPIXEL DI AMICI',
    caption: 'La tua faccia sulla locandina di fine stagione!',
    description: (
      'Quest\'anno abbiamo deciso di dedicare la locandina di fine stagione a voi, amici del jubilee. L\'avatar di ognuno di voi occuperà circa 30.000 pixel e tutti insieme riusciremo a raggiungere la fatidica soglia dei 17.000.000 di pixel, per realizzare una locandina che entrerà nella storia!'
    ),
    href: 'http://www.jubileegroup.it/jubilee/locandina.php',
	media: [{ 
        'type': 'image', 
        'src': 'http://www.jubileegroup.it/jubilee/images/attachloc.jpg', 
        'href': 'http://www.jubileegroup.it/jubilee/locandina.php'}]
  },
  action_links: [
    { text: 'Prenota un posto', href: 'http://www.jubileegroup.it/jubilee/locandina.php' }
  ]
};

FB.ui(publish,
   function(response) {
     if (response && response.post_id) {
       //
     } else {
       publishLocLink();
     }
   }
);
}

function publishCpdn() {

var publish = {
  method: 'stream.publish',
  message: 'Vuoi una t-shirt del jubilee in omaggio? Vai su http://tinyurl.com/capodannojubilee e condividi la pagina su facebook!',
  attachment: {
    name: 'JUBILEE CAPODANNO 2011 - FREE DRINK ALCOLICO - 30 EURO',
    caption: 'BE FREE! Il capodanno firmato jubilee',
    description: (
      'BE FREE. Senza mille giri di parole una notte speciale in cui bere anche oltre le 3! FREE BAR ALCOLICO. BEVI RESPONSABILMENTE!'
    ),
    href: 'http://www.jubileegroup.it/jubilee/cpdn2011.php',
	media: [{ 
        'type': 'image', 
        'src': 'http://www.jubileegroup.it/jubilee/images/cpdn/inserzionefb2.jpg', 
        'href': 'http://www.jubileegroup.it/jubilee/cpdn2011.php'}]
  },
  action_links: [
    { text: 'Scopri i dettagli', href: 'http://www.jubileegroup.it/jubilee/cpdn2011.php' }
  ]
};

FB.ui(publish,
   function(response) {
     if (response && response.post_id) {
       var sess = FB.getSession();
	   var sessuid = sess.uid;
	   aggiornaCpdn(sessuid);
     }
   }
);
}

function aggiornaCpdn(suid) {
	$.post("aggiornaCpdn.php", {suid:suid}, function(data){
		//console.log(data);
		//alert(data.quanti);
		var html = "Hai condiviso <b>"+data.quanti+"</b> volte. Puoi condividere dopo le <b>"+data.tempo+"</b>.";
		$("#cpdnresult").html(html);
		}, "json");
}

function istruzioni(chi, pass) {
	alert("Puoi ritirare la tua T-SHIRT durante la serata dell'8 gennaio 2011\npresso l'area servizi del jubilee.\nComunica questi dati:\nUSER: "+chi+"\nPASS: "+pass+"\nGrazie per la collaborazione!");
}

function publishLocLink() {
	var loclink = "http://www.jubileegroup.it/jubilee/locandina.php";
	FB.api('/me/feed?link='+loclink, 'post');
}

function pubblicabiglietti() {
	var loclink = "http://www.jubileegroup.it/jubilee/10biglietti.php";
	FB.api('/me/feed?link='+loclink, 'post');
}

function postMessage(mMsg, mCaption, mDesc, mLink, mName){

    FB.api('/me/feed', 'post', {
    
           message: mMsg,
           name: mName,
           caption: mCaption,
           description: (mDesc),
           link: mLink
         
       },
       function(response) {
          if (!response || response.error) {
            alert('Error occured');
          } else {
            alert('Post ID: ' + response);
          }
        }
    ); 
    
}

function deletePress(pressId) {
	$.post("deletePress.php", {pressId:pressId}, function(data) {
			$("#press"+pressId).hide();
		});
}
