// JavaScript Document

function fbs_click() {
	u=location.href;
	t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}
	function objetoAjax(){
		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;
	}
	
var xmlDoc=false;
var gecko= (document.implementation && document.implementation.createDocument) ? true:false;
var ie= (window.ActiveXObject && document.all) ? true:false;

	
	function get_cines(){

		divResultado = document.getElementById('busqueda_cines');
		criterio = document.getElementById('criterio_cines').value;
		if(criterio!=""){
			document.getElementById('busqueda_cines').style.display="block";
		}else{
			document.getElementById('busqueda_cines').style.display="none";
		}
		
		var lista = "<ul>";
		var cines = xmlDoc.getElementsByTagName('cine');
		for(i=0;i<cines.length;i++){
			var nombre = cines[i].getElementsByTagName('nombre');
			var direccion = cines[i].getElementsByTagName('direccion');
			var id = cines[i].getElementsByTagName('id');
			
			var nombre = nombre[0].firstChild.nodeValue;
			var direccion = direccion[0].firstChild.nodeValue;
			var id = id[0].firstChild.nodeValue;
			var buscar=nombre.toLowerCase();
				if (buscar.indexOf(criterio)!=-1) {
					lista += "<li><a href=\"peliculas/cine/"+id+"\"><h1>"+nombre+"</h1></a><h2>"+direccion+"</h2></li>";
				}
		}
		lista += "</ul>";

		divResultado.innerHTML = unescape(lista);
    }
	
	function loadAddresses(){
		// For Gecko Browsers
		if (gecko){
			xmlDoc = document.implementation.createDocument("", "", null);
			xmlDoc.async=false;
			
		}else if (ie){// For IE/Win
			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async=false;		
		}
		
	  //xmlDoc = document.implementation.createDocument("", "", null);
	  xmlDoc.onload = get_cines;
	  xmlDoc.load("templates/trailers/xml/cines_xml.xml");
	}

	function favorito(id){
		divResultado = document.getElementById('favoritos');
		valores = "&id_pelicula="+id;
		var d = new Date();
		nocache = d.getTime();
		ajax=objetoAjax();
		ajax.open("POST", "templates/trailers/ajax/favorito.php", true);
		ajax.onreadystatechange=function(){
			if (ajax.readyState==1){
            	divResultado.innerHTML = "<center>Agregando a favorito...<\/center>";
	        }
			if(ajax.readyState==4){
			   divResultado.innerHTML = unescape(ajax.responseText);
			}
		}
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		ajax.send("nocahe="+nocache+""+valores);
		
	}
	
	function comments(uid){
		//divResultado = document.getElementById('favoritos');
		xid = document.getElementById('id_pelicula').value;
		valores = "&uid="+uid+"&xid="+xid;
		var d = new Date();
		nocache = d.getTime();
		ajax=objetoAjax();
		ajax.open("POST", "templates/trailers/ajax/comments.php", true);
		ajax.onreadystatechange=function(){
			if (ajax.readyState==1){
            	//divResultado.innerHTML = "<center>Agregando a favorito...<\/center>";
	        }
			if(ajax.readyState==4){
			   //alert(unescape(ajax.responseText)) ;
			}
		}
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		ajax.send("nocahe="+nocache+""+valores);
		
	}
	
	function publicar_muro(text){
		codigo_feed = 99582253727;
		var nombre 		= document.getElementById('pelicula').value;
		var url 		= document.getElementById('url').value;
		var descripcion = document.getElementById('descripcion').value;
		var imagen 		= document.getElementById('imagen').value;
		var plantilla = {
						"pelicula":nombre,
						"url":url,
						"comentario":text,
						"images":[{"src":"http://www.trailers.cl/plataforma/upload/mini/mini_"+imagen, "href":url}]
						};
						
		FB.Connect.showFeedDialog(codigo_feed, plantilla);		
	}
	
	function miscines_2(id, num){
		divResultado = document.getElementById('favoritos_'+num);
		valores = "&id_cine="+id;
		var d = new Date();
		nocache = d.getTime();
		ajax=objetoAjax();
		ajax.open("POST", "templates/trailers/ajax/micine.php", true);
		ajax.onreadystatechange=function(){
			if (ajax.readyState==1){
            	divResultado.innerHTML = "<center>Agregando a favorito...<\/center>";
	        }
			if(ajax.readyState==4){
			   divResultado.innerHTML = unescape(ajax.responseText);
			}
		}
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		ajax.send("nocahe="+nocache+""+valores);
		
	}
	function miscines(id){
		divResultado = document.getElementById('favoritos');
		valores = "&id_cine="+id;
		var d = new Date();
		nocache = d.getTime();
		ajax=objetoAjax();
		ajax.open("POST", "templates/trailers/ajax/micine.php", true);
		ajax.onreadystatechange=function(){
			if (ajax.readyState==1){
            	divResultado.innerHTML = "<center>Agregando a favorito...<\/center>";
	        }
			if(ajax.readyState==4){
			   divResultado.innerHTML = unescape(ajax.responseText);
			}
		}
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		ajax.send("nocahe="+nocache+""+valores);
		
	}

	function calificar(voto, id, itemid){
		divResultado = document.getElementById('califica');
		valores = "&id="+id+"&voto="+voto+"&itemid="+itemid;
		var d = new Date();
		nocache = d.getTime();
		ajax=objetoAjax();
		ajax.open("POST", "templates/trailers/ajax/calificar.php", true);
		ajax.onreadystatechange=function(){
			if (ajax.readyState==1){
            	divResultado.innerHTML = "<center><img src='templates/trailers/images/loading.gif'><\/center>";
	        }
			if(ajax.readyState==4){
			   divResultado.innerHTML = unescape(ajax.responseText);
				if(voto<0)				
					publicar_puntaje(78796838727);
				else
					publicar_puntaje(78797698727)
			}
		}
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		ajax.send("nocahe="+nocache+""+valores);
		
	}
	function votar(puntos, id){
		divResultado = document.getElementById('ratingblock');
		valores = "&id="+id+"&puntos="+puntos;
		var d = new Date();
		nocache = d.getTime();
		ajax=objetoAjax();
		ajax.open("POST", "templates/trailers/ajax/votar.php", true);
		ajax.onreadystatechange=function(){
			if (ajax.readyState==1){
            	divResultado.innerHTML = "<center><img src='templates/trailers/images/loading.gif'><\/center>";
	        }
			if(ajax.readyState==4){
			   divResultado.innerHTML = unescape(ajax.responseText);
			   publicar_votacion(78795418727, puntos);
			}
		}
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		ajax.send("nocahe="+nocache+""+valores);
		
	}
	
	function mostrar_comentarios(uid, pagina){
		divResultado = document.getElementById('comments');
		valores = "&uid="+uid+"&pagina="+pagina;
		var d = new Date();
		nocache = d.getTime();
		ajax=objetoAjax();
		ajax.open("POST", "templates/trailers/ajax/mostrar_comentarios.php", true);
		ajax.onreadystatechange=function(){
			if (ajax.readyState==1){
            	divResultado.innerHTML = divResultado.innerHTML+"<center><img src='templates/trailers/images/cargando.gif'></center>";
	        }
			if (ajax.readyState==4){
			   divResultado.innerHTML = unescape(ajax.responseText);
			}
		}
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		ajax.send("nocahe="+nocache+""+valores);
		
	}
	
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document;
if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++)
x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++)
x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_jumpMenuGo(selName,targ,restore){ //v3.0
  var selObj = MM_findObj(selName); if (selObj)
MM_jumpMenu(targ,selObj,restore);
}



function update_user_box(){
	FB.XFBML.Host.parseDomTree();
	var user_box = document.getElementById("login_facebook"); // add in some XFBML. note that we set useyou=false so it doesn't display "you" 
	uid = FB.Connect.get_loggedInUser();
	user_box.innerHTML = "<div class=\"cont_rec\">"
							+"<p>Hola, <fb:name uid=loggedinuser useyou=false></fb:name>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a href=\"javascript:void(0);\" class=\"logout_facebook\" onclick=\"FB.Connect.logoutAndRedirect('http://www.trailers.cl/home/peliculas/home')\">Salir</a></p><div class=\"imagen\"><fb:profile-pic uid=\"loggedinuser\" facebook-logo=\"true\" size=\"square\" linked=\"false\"></fb:profile-pic></div> "
							+" <a class=\"logout_facebook\" href=\"javascript:void();\">Mi perfil</a><br />"
							+" <a class=\"logout_facebook\" href=\"peliculas/invita\">Invita a tus amigos</a><br />"
							+" <fb:prompt-permission class=\"logout_facebook\" perms=\"email\">Acepto recibir correos</fb:prompt-permission>"
							+"</div>";

	FB.XFBML.Host.parseDomTree(); 
}

function login_otro(){
FB.login(function(response) {
  if (response.session) {
    if (response.perms) {
      // user is logged in and granted some permissions.
      // perms is a comma separated list of granted permissions
    } else {
      // user is logged in, but did not grant any permissions
    }
  } else {
    // user is not logged in
  }
}, {perms:'email,publish_stream,user_birthday,user_events'});
	
	
	}

function callback(){
	url_trailer	= document.location.href ;
	partes 		= url_trailer.split('/');
	final		= partes[2]; 
	uid 		= FB.Connect.get_loggedInUser();
	update_user_box();
	window.location.reload(true);
	//window.location="http://"+final+"/home/peliculas/miperfil/"+uid;
}

function no_conected(m){
	if(m=='pelicula'){
		showDialog("Informaci&oacute;n","Para agregar esta pel&iacute;cula a tus favoritos debes ingresa con tu cuenta de Facebook","success",1);
	}else if(m=='cine'){
		showDialog("Informaci&oacute;n","Para agregar este cine a tus favoritos debes ingresa con tu cuenta de Facebook","success",1);
	}else if(m=='invitar'){
		showDialog("Informaci&oacute;n","Para agregar este cine a tus favoritos debes ingresa con tu cuenta de Facebook","success",1);
	}else if(m=='video_facebook'){
		showDialog("Informaci&oacute;n","Para publicar este trailer en tu muro debes ingresa con tu cuenta de Facebook","success",1);
	}
}

function codigo_qr(url){
		mensaje = "<table><tr><td><img src='http://chart.apis.google.com/chart?cht=qr&chs=100x100&chld=l|1&chl="+url+"'></td><td>Descarga el trailers a tu celular para eso necesitas un lector de codigo QR</td></tr></table>";
	
		showDialog("Informaci&oacute;n",mensaje,"success",0);
}

function publicar_puntaje(codigo_feed){
	var nombre 		= document.getElementById('pelicula').value;
	var url 		= document.getElementById('url').value;
	var descripcion = document.getElementById('descripcion').value;
	var imagen 		= document.getElementById('imagen').value;
	
	
var share = {
   method: 'stream.share',
   u: url
 };

 FB.ui(share, function(response) { console.log(response); });

/*
 
	
	
	var plantilla = {
	method: 'stream.share',	
	pelicula:nombre,
	url:url,
	descripcion:descripcion,
	imagen:[{"src":"http://www.trailers.cl/plataforma/upload/mini/mini_"+imagen, "href":url}]};

	FB.ui(share, function(response) { console.log(response); });
	//FB.Connect.showFeedDialog(codigo_feed, plantilla); */
}

function publicar_votacion(codigo_feed, puntos){
	var nombre 		= document.getElementById('pelicula').value;
	var url 		= document.getElementById('url').value;
	var descripcion = document.getElementById('descripcion').value;
	var imagen 		= document.getElementById('imagen').value;
	
/*var share = {
   method: 'stream.share',
   u: url
 };*/
FB.api('/me', function(response) {
	var publicar = {
		 method: 'stream.publish',
		 message: '',
		 attachment: {
		   name: 'Trailers.cl',
		   caption: response.name+' le a dado '+puntos+" punto(s) a la película "+nombre,
		   description: (
			 descripcion
		   ),
		   href: imagen,
		   image:imagen
		 },
		 action_links: [
		   { text: 'Code', href: url } 
		 ],
		 user_prompt_message: 'Publica tu mensaje aqui'
	   } 
	
	 FB.ui(publicar, function(response) { console.log(response); });				   

}); 
 
	
	
/*	var plantilla = {"pelicula":nombre,
	"url":url,
        "nota":puntos,
	"descripcion":descripcion,
	"images":[{"src":"http://www.trailers.cl/plataforma/upload/mini/mini_"+imagen, "href":url}]};

	FB.Connect.showFeedDialog(codigo_feed, plantilla); */
}

function publicar_video(video, imagen){
	codigo_feed = 98803848727;
	var nombre 		= document.getElementById('pelicula').value;
	var url 		= document.getElementById('url').value;
	var descripcion = document.getElementById('descripcion').value;
	var plantilla = {
					"pelicula":nombre,
					"url":url,
					"descripcion":descripcion,
					"video":{ 
							"video_src":"http://www.trailers.cl/home/templates/trailers/swf/player_350x250.swf?t="+video, 
							"preview_img":"http://www.trailers.cl/plataforma/upload/web/"+imagen 
							}
					}
	FB.Connect.showFeedDialog(codigo_feed, plantilla);
}

function menu_sl(total){
valor = document.getElementById('estado_menu').value;
		$('sm_1').setStyle({
			opacity: 0,
			border: 1
		});
		
	if(valor==0){
		new Effect.Parallel([
			new Effect.Morph('sm_1', { style: 'height:'+(total*30)+'px;'}),
			new Effect.Morph('sm_1', { style: 'border-color:#3B5998'}),
			new Effect.Opacity('sm_1', { sync: true, from: 0, to: 1 })
		], { 
		  duration: 0.7,
		  delay: 0.1
		});
		document.getElementById('estado_menu').value=1;
	}else{
		new Effect.Parallel([
			new Effect.Morph('sm_1', { style: 'height:0px;'}),
			new Effect.Morph('sm_1', { style: 'border-color:#EBEBEB'}),
			new Effect.Opacity('sm_1', { sync: true, from: 1, to: 0 })
		], { 
		  duration: 0.7,
		  delay: 0.1
		});
		document.getElementById('estado_menu').value=0;
	}
}


