/*********************************/			
//Facebook connect functions
/*********************************/

//Connect user to facebook
function facebook_connect(){
	FB.ensureInit(function() {
		FB.Connect.requireSession();
		FB.Connect.get_status()
	});
}

//Logout user from facebook
function facebook_logout(){
	FB.ensureInit(function() {
		FB.Connect.logout()
	});
}

//Logout user from facebook and redirect
function facebook_logout_redirect(url){
	FB.ensureInit(function() {
		FB.Connect.logoutAndRedirect(url)
	});
}

//Do action on user connection
function onConnected(user_id) { }

//get the users data from FB
function facebook_get_user_info() {
	FB.ensureInit(function() {
		var viewer  = FB.Facebook.apiClient.fql_query('SELECT name, pic_square_with_logo,profile_url FROM user WHERE uid='+FB.Facebook.apiClient.get_session().uid, function(results) {
			update_userbox( results[0].name,
			results[0].pic_square_with_logo,
			results[0].profile_url,
			'FB.Connect.logoutAndRedirect("index.php");return false;')
			}
		);
	});
}

//Do action on user logout
function onNotConnected() {  } 

//Publish feed story to own feed
function facebook_publish_feed_story(titulo, cuerpo, imagen, actionlink, url) {
	var attachment = {'href': url,'name': titulo, 'caption': cuerpo,'media': [{'type': 'image', 'src': imagen, "href": url}]};
	var actionLinks = [{ "text": actionlink, "href": url}]; 
	// Load the feed form
	FB.ensureInit(function() {
		FB.Connect.streamPublish('', attachment, actionLinks);
	});
}

//Publish feed story to friends feed
function facebook_publish_feed_story_friends(titulo, cuerpo, imagen, actionlink, url, uid) {
	var attachment = {'href': url,'name': titulo, 'caption': cuerpo,'media': [{'type': 'image', 'src': imagen, "href": url}]};
	var actionLinks = [{ "text": actionlink, "href": url}]; 
	// Load the feed form
  FB.ensureInit(function() {
		  FB.Connect.streamPublish('', attachment, actionLinks, uid); 
  });
}

//Publish feed story to own feed (Customized version)
function facebook_publish_feed_story_custom(uid, puesto, imagen) {
	var attachment = {'href': 'http://www.elmisteriodelarbol.com/?uid='+uid+'&cap=0&utm_source=Facebook&utm_medium=viral&utm_campaign=tpmini&ref=nf', 'caption': '{*actor*} ha hecho su casting para la serie elmisteriodelarbol.com e interpretará a '+puesto+'. ¿Quieres ver el resto de su casting?','properties' : {'Estreno el 14 de diciembre' : {'text' : '¿Quieres ver todo su casting?', 'href' : 'http://www.elmisteriodelarbol.com/?uid='+uid+'&cap=0&utm_source=Facebook&utm_medium=viral&utm_campaign=tpmini&ref=nf'}}, 'media': [{'type': 'image', 'src': imagen, "href":'http://www.elmisteriodelarbol.com/?uid='+uid+'&cap=0&utm_source=Facebook&utm_medium=viral&utm_campaign=tpmini&ref=nf'}]};
	var actionLinks = [{ "text": "Ver el casting", "href": 'http://www.elmisteriodelarbol.com/?uid='+uid+'&cap=0&utm_source=Facebook&utm_medium=viral&utm_campaign=tpmini'}]; 
	// Load the feed form
	FB.ensureInit(function() {
		FB.Connect.streamPublish('', attachment, actionLinks, null, '¿Qué estás pensando?');
	});
}

//Publish feed story to friends feed (Customized version)
function facebook_publish_feed_story_friends_custom(actor, puesto, imagen, uid, cuid, done) {
	var attachment = {'href': 'http://www.elmisteriodelarbol.com/?uid='+cuid+'&cap=0&utm_source=Facebook&utm_medium=viral&utm_campaign=tpmini&ref=nf', 'caption': '{*actor*} ha escogido a '+actor+' para que interprete a '+puesto+' en la serie elmisteriodelarbol.com.', 'properties' : {'Estreno el 14 de diciembre' : {'text' : '¿Quieres ver todo su casting?', 'href' : 'http://www.elmisteriodelarbol.com/?uid='+cuid+'&cap=0&utm_source=Facebook&utm_medium=viral&utm_campaign=tpmini&ref=nf'}},'media': [{'type': 'image', 'src': imagen, "href":'http://www.elmisteriodelarbol.com/?uid='+cuid+'&cap=0&utm_source=Facebook&utm_medium=viral&utm_campaign=tpmini&ref=nf'}]};
	var actionLinks = [{ "text": "Ver el casting", "href": 'http://www.elmisteriodelarbol.com/?uid='+cuid+'&cap=0&utm_source=Facebook&utm_medium=viral&utm_campaign=tpmini'}];
	// Load the feed form
	FB.ensureInit(function() {
		FB.Connect.streamPublish('', attachment, actionLinks, uid, '¿Qué estás pensando?', hideFriends(done));
	});
}

function hideFriends(id) {
	document.getElementById(id).style.display = "none";
	document.getElementById(id+"done").style.display = "block";
}

//Check if two UID are friends
function facebook_are_friends (uid, uid2){
	FB.ensureInit(function() {
		FB.Facebook.apiClient.fql_query("SELECT uid2 FROM friend WHERE uid1 ="+uid+" AND uid2 ="+uid2,
			function(rows) {
				var lh = rows.length;
				if (lh === 1) return true;
		});
	});
	return false;
}

 function error_dialog(title, text){
	var dialog = new FB.UI.FBMLPopupDialog(title, 'Aceptar');
	var fbml = text;
	dialog.setFBMLContent(fbml);
	dialog.setContentWidth(445);
	dialog.setContentHeight(75);
	dialog.set_placement(FB.UI.PopupPlacement.topCenter);
	dialog.show();
} 

/*********************************/			
//Casting Javascript functions
/*********************************/

//Show hide the correct firend selector
function show_friend_selector(sel_id){
	for (i=1; i <7; i++) {
		document.getElementById('friend_sel'+i).style.display='none';
	}
	document.getElementById(sel_id).style.display='block';
}

//Validate the friend selector
function validate_friend_selector(rad_id){
	var rad = document.getElementsByName(rad_id);
	var result = getCheckedValue(rad);
	if(result == ""){
		return false;
	}else{ 				
		document.getElementById("characterImg").style.display = "none";
		document.getElementById("marcoRecortar").style.display = "block";
		document.getElementById("back").src = "";
		return false;
	}
}

/*********************************/			
//General Javascript functions
/*********************************/

//Check if a radio object has any value
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}
//En cas de refresh mante seleccionat el mateix amic
function selectorInit() {
	var rad = document.getElementsByName('friend_rad');
	var selectedId = getCheckedValue(rad);
	if(selectedId != "") {
		document.getElementById('friend_div_'+selectedId).style.background = '#333333';
		document.getElementById("moveMe").style.display = "none";
		document.getElementById("characterImg").style.display = "none";
		document.getElementById("marcoRecortar").style.display = "block";
		getPic(selectedId);
	}
}
//Marca l'amic seleccionat a la llista d'amics
function destacar(element) {
	var temp = document.getElementById('friend_selected');
	var contenedor;
	
	document.getElementById("moveMe").style.display = "none";
	document.getElementById("characterImg").style.display = "none";
	document.getElementById("marcoRecortar").style.display = "block";
	
	if (temp.value != element && temp.value != ""){
		document.getElementById('friend_div_'+temp.value).style.background = 'none';
	}
	
	temp.value = element;
	document.getElementById('friend_div_'+element).style.background = '#333333';
	document.getElementById('friend_rad_'+element).checked = true;
	document.getElementById("back").style.display = "none";
	getPic(element);
}
function nuevoAjax(){
	var xmlhttp=false;
 	try {
 		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 	} catch (e) {
 		try {
 			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 		} catch (E) {
 			xmlhttp = false;
 		}
  	}

	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
 		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}
//Canvia la imatge del mini_lienzo
function getPic(id){
	FB.ensureInit(function() {
		FB.Facebook.apiClient.fql_query("SELECT id, name, pic_big FROM profile WHERE id="+id,
		function(rows) {
			var silueta;
			if (rows[0].pic_big == "http://static.ak.fbcdn.net/pics/d_silhouette.gif") 	silueta = "http://elmisteriodelarbol.com/casting/img/fb_perfil.jpg";
			else																		silueta = rows[0].pic_big;
			
			//Variables init imagenes
			var photo  = silueta;
			var type = document.getElementById("char").value;
			var capaW = parseInt(document.getElementById("moveMe").style.width);
			var capaH = parseInt(document.getElementById("moveMe").style.height);
			var starty = parseInt(document.getElementById("lienzo").offsetHeight);
			var startx = parseInt(document.getElementById("lienzo").offsetWidth);

			$("#slider-range-min").hide();
			contenedor = document.getElementById('lienzo');
			
			contenedor.innerHTML = '<div style="height: 100%; width: 100%; background: transparent url(img/ajax-loader.gif) no-repeat center center;"></div>';
			document.getElementById("char_form_sub").style.background = "transparent url(img/bg_boton_siguiente.gif) no-repeat scroll 0 0"; 
			document.getElementById("char_form_sub").style.color = "#000000";
			document.getElementById("char_form_sub").disabled = true;
			document.getElementById("char_form_sub").style.cursor = "default";
			//Crida lajax per canvia la imatge a retallar al min_lienzo
			ajax=nuevoAjax();
			ajax.open("POST", "ajax.php",true);
			ajax.onreadystatechange=function() {
				if (ajax.readyState==4) {
					contenedor.style.display = "none";
					contenedor.innerHTML = ajax.responseText
					updateMoveId (document.getElementById('moveMe'));
					updateNoMoveId (document.getElementById('back'))
					
					noMovMeId.style.display = "none";
					
					//Init hidden inputs
					document.getElementById("path").value = silueta;
					document.getElementById("name").value = rows[0].name;
					document.getElementById("cuid").value = rows[0].id;
					document.getElementById("bm0").value = parseInt(noMovMeId.style.width);
					document.getElementById("bm1").value = parseInt(noMovMeId.style.height);
					contenedor.style.display = "block";
					document.getElementById("char_form_sub").style.background = "transparent url(img/bg_boton_siguiente_active.gif) no-repeat scroll 0 0"; 
					document.getElementById("char_form_sub").style.color = "#ffffff";
					document.getElementById("char_form_sub").disabled = false;
					document.getElementById("char_form_sub").style.cursor = "pointer";
					
					var bm0 = parseInt(noMovMeId.style.width);
					var bm1 = parseInt(noMovMeId.style.height);
					var ratio = 1;
					var MAX_WIDTH = 280;
					var MAX_HEIGTH;
					ratio = bm1/ bm0;
					ratio2 = bm0/ bm1
					MAX_HEIGTH = (MAX_WIDTH*ratio);
					$("#slider-range-min").show();
					$(function() {
						//Espera que es carregui la imatge de fons
						$('#back').load(function() {
							noMovMeId.style.display = "block";
							noMovMeId.style.top = parseInt((document.getElementById("lienzo").offsetHeight/2)-(document.getElementById("back").height/2))+'px';//450"125px";//160
							noMovMeId.style.left = parseInt((document.getElementById("lienzo").offsetWidth/2)-(document.getElementById("back").width/2)-document.getElementById("moveMe").offsetWidth)+'px';
							//Carrega l'slider
							$("#slider-range-min").slider({
									range: "min",
									value: MAX_HEIGTH,
									min: 100,
									max: MAX_HEIGTH,
									slide: function(event, ui) {
										var mb21 = ui.value;
										var mb20 = mb21 * ratio2;
													
										var mog;
										document.getElementById("back").style.top = parseInt((document.getElementById("lienzo").offsetHeight/2)-(ui.value/2))+'px';
										noMovMeId.style.height = mb21+'px';

										document.getElementById("back").style.left = parseInt((document.getElementById("lienzo").offsetWidth/2)-(mb20/2)-(document.getElementById("moveMe").offsetWidth))+'px';
										noMovMeId.style.width = mb20+'px';

										document.getElementById("bm0").value = mb20;
										document.getElementById("bm1").value = mb21;
									}
							});
						});noMovMeId.src = noMovMeId.src; //Trigger onload event if image is cached
					});
					$('#slider-range-min').slider('option', 'max', MAX_HEIGTH);
					$('#slider-range-min').slider('value', MAX_HEIGTH);	
				}
			}
			ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			ajax.send("photo="+photo+"&type="+type+"&capaW="+capaW+"&capaH="+capaH+"&starty="+starty+"&startx="+startx);
		});
	});
}
