/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
function XHConn()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
      if (sMethod == "GET")
      {
		if(typeof(sVars) == 'object') {
			var finalvars = 'json='+encodeURIComponent($.toJSON(sVars));
		} else {
			var variables = sVars.split('&');
			var finalvars = new Array();
			for(var i=0;i<variables.length;i++) {
				var row = variables[i].split('=');
				finalvars.push(encodeURIComponent(row[0])+'='+encodeURIComponent(row[1]));
			}
			finalvars = finalvars.join('&');
		}
        xmlhttp.open(sMethod, sURL+"?"+finalvars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");

      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete)
        {
          bComplete = true;
		  if(typeof(fnDone) == 'object') {
			  fnDone.run(xmlhttp);
		  } else {
	          fnDone(xmlhttp);
		  }
        }};
		var finalvars = '';
		if(typeof(sVars) == 'object') {
			finalvars = 'json='+encodeURIComponent($.toJSON(sVars));
		} else {
			finalvars = sVars;
		}
				
      xmlhttp.send(finalvars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}

function page(targetId,url,params,handler,method) {
	if(method == null) {
		method = "GET";
	}
target= document.getElementById(targetId);
target.innerHTML = '<img class="cargando" src="/css/img/cargando.gif" alt="Cargando..." />';
var myConn = new XHConn();
    if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
	if(!handler) {
	    var query = function (oXML) {  target.innerHTML = oXML.responseText; };
	} else {
		var query = handler;
	}
    myConn.connect(url, method, params, query);
}

var oldform = '';

function loginForm(elem,redir) {
	if(elem.username.value == '' || elem.password.value == '') {
		alert('Error: No puede haber campos vacíos');
		return false;
	}
	
	oldform = elem.innerHTML;
	
	var hndl = function(oXML) {
		if(oXML.responseText == 'true') {
			// Mejor no window.reaload (por si se ha enviado POST)
			if(redir != null) {
				window.location.href = redir;
			} else {
				window.location.href = window.location.href;
			}
		} else {
			elem = document.getElementById('login'); // Más abajo hay una solución, hay que reescribir este handler
			elem.innerHTML = '<p class="info">Usuario y/o contraseña incorrectos <a href="#" onclick="document.getElementById(\'login\').innerHTML = oldform; return false;">Volver a intentar</a></p>';
		}
	}
	
	page(elem.id,'/ajax/login.php','username='+elem.username.value+'&password='+elem.password.value,hndl);
	
	return false;
	
}

function voteFilm(vote,id,from,cambio) {
	var from = from || '';
	
	if(cambio == null) {
		cambio = false;
	}
	
	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				var response = oXML.responseText.substr(4);
				this.destination.innerHTML = response.split('#')[1];
				this.destination.parentNode.getElementsByTagName('li')[0].style.width = response.split('#')[0]+'%';
				window.location.href=window.location.href;
			} else {
				var response = oXML.responseText.substr(5);
				if(response == 'unlogged') {
					this.destination.parentNode.innerHTML = 'Debes estar identificado para poder votar';
				} else {
					this.destination.innerHTML = this.restore;
				}
			}
		}
	}	
	
	var hndl = new requestHandler();
	if(cambio) {
		hndl.destination = document.getElementById('voteContainer2');
	} else {
		hndl.destination = document.getElementById('voteContainer');
	}
	hndl.restore = hndl.destination.innerHTML;
	
	var params = 'vote='+vote.toString()+'&id='+id;
	if(from != '') {
		params += '&from='+from;
	}
	if(cambio) {
		params += '&cambio=true';
	}
	page(cambio ? 'voteContainer2' : 'voteContainer','/ajax/pelicula-votar.php',params,hndl);
	
}

function voteCritic(vote,id,from) {
	var from = from || '';
	
	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				this.destination.innerHTML = oXML.responseText.substr(4);
			} else {
				this.destination.innerHTML = this.restore;
			}
		}
	}	
	
	var hndl = new requestHandler();
	hndl.destination = document.getElementById('voteContainer'+id);
	hndl.restore = hndl.destination.innerHTML;
	
	var params = 'vote='+vote.toString()+'&id='+id;
	if(from != '') {
		params += '&from='+from;
	}
	page('voteContainer'+id,'/ajax/pelicula-votar-critica.php',params,hndl);
	
}

function voteDiscussion(vote,id,from) {
	var from = from || '';
	
	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				this.destination.innerHTML = oXML.responseText.substr(4);
			} else {
				this.destination.innerHTML = this.restore;
			}
		}
	}	
	
	var hndl = new requestHandler();
	hndl.destination = document.getElementById('voteContainer'+id);
	hndl.restore = hndl.destination.innerHTML;
	
	var params = 'vote='+vote.toString()+'&id='+id;
	if(from != '') {
		params += '&from='+from;
	}
	page('voteContainer'+id,'/ajax/pelicula-votar-discusion.php',params,hndl);
	
}

function voteChat(vote,id,from) {
	var from = from || '';
	
	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				this.destination.innerHTML = oXML.responseText.substr(4);
			} else {
				this.destination.innerHTML = this.restore;
			}
		}
	}	
	
	var hndl = new requestHandler();
	hndl.destination = document.getElementById('voteContainer'+id);
	hndl.restore = hndl.destination.innerHTML;
	
	var params = 'vote='+vote.toString()+'&id='+id;
	if(from != '') {
		params += '&from='+from;
	}
	page('voteContainer'+id,'/ajax/pelicula-votar-chat.php',params,hndl);
	
}


function voteTag(vote,id) {
	
	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				this.destination.innerHTML = oXML.responseText.substr(4);
			} else {
				this.destination.innerHTML = this.restore;
			}
		}
	}	
	
	var hndl = new requestHandler();
	hndl.destination = document.getElementById('voteContainer'+id);
	hndl.restore = hndl.destination.innerHTML;
	
	page('voteContainer'+id,'/ajax/pelicula-votar-tag.php','vote='+vote.toString()+'&id='+id,hndl);
	
}

function voteList(vote,id) {
	
	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				this.destination.innerHTML = oXML.responseText.substr(4);
			} else {
				this.destination.innerHTML = this.restore;
			}
		}
	}	
	
	var hndl = new requestHandler();
	hndl.destination = document.getElementById('voteContainer'+id);
	hndl.restore = hndl.destination.innerHTML;
	
	page('voteContainer'+id,'/ajax/votar-lista.php','vote='+vote.toString()+'&id='+id,hndl);
	
}

function voteImage(vote,id) {
	
	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				this.destination.innerHTML = oXML.responseText.substr(4);
			} else {
				this.destination.innerHTML = this.restore;
			}
		}
	}	
	
	var hndl = new requestHandler();
	hndl.destination = document.getElementById('voteContainer');
	hndl.restore = hndl.destination.innerHTML;
	
	page('voteContainer','/ajax/votar-imagen.php','vote='+vote.toString()+'&id='+id,hndl);
	
}


function friendConfirm(id,status) {
	
	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				this.destination.innerHTML = oXML.responseText.substr(4);
			} else {
				this.destination.innerHTML = '¡Error!';
			}
		}
	}	
	
	var hndl = new requestHandler();
	hndl.destination = document.getElementById('petition-'+id);
	
	page('petition-'+id,'/ajax/aceptar-amigo.php','id='+id+'&status='+status,hndl);
	
}

function aliasAdd(elem) {
		if(elem.alias.value == '') {
				alert('Por favor, introduce un alias.');
				return false;
		}
		
		var container = document.getElementById('agregar');
		
		oldform = container.innerHTML;
		
		function requestHandler() {
			this.destination = null;
			this.elementAdd = null;
			
			this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
					this.destination.innerHTML = '<p>El alias se ha agregado correctamente. <a href="#" onclick="document.getElementById(\''+this.destination.id+'\').innerHTML = oldform; return false;">Insertar otro alias</a>.</p>';
					this.elementAdd.innerHTML += oXML.responseText.substr(4);
				} else {
					this.destination.innerHTML = '<p>Ha habido un problema al insertar el alias</p>';
				}			
			}
		}
		
		var hndl = new requestHandler();
		hndl.destination = container;
		hndl.elementAdd = document.getElementById('aliases');
				
		page(container.id,'/ajax/pelicula-agregar-alias.php',{'id': elem.filmid.value, 'alias': elem.alias.value},hndl);
		return false;		
}

function voteAlias(vote,id) {
	
	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				this.destination.innerHTML = oXML.responseText.substr(4);
			} else {
				this.destination.innerHTML = this.restore;
			}
		}
	}	
	
	var hndl = new requestHandler();
	hndl.destination = document.getElementById('voteContainer'+id);
	hndl.restore = hndl.destination.innerHTML;
	
	page('voteContainer'+id,'/ajax/pelicula-votar-alias.php','vote='+vote.toString()+'&id='+id,hndl);
	
}

function voteDescription(vote,id) {
	
	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				this.destination.innerHTML = oXML.responseText.substr(4);
			} else {
				this.destination.innerHTML = this.restore;
			}
		}
	}	
	
	var hndl = new requestHandler();
	hndl.destination = document.getElementById('voteContainer'+id);
	hndl.restore = hndl.destination.innerHTML;
	
	page('voteContainer'+id,'/ajax/pelicula-votar-descripcion.php','vote='+vote.toString()+'&id='+id,hndl);
	
}

function betaJoin(elem) {
		if(elem.email.value == '') {
				alert('Por favor, introduce tu e-mail.');
				return false;
		}
		
		//var container = document.getElementById(elem);
		container = elem;
		
		oldform = container.innerHTML;
		
		function requestHandler() {
			this.destination = null;
			this.elementAdd = null;
			
			this.run = function(oXML) {
				if(oXML.responseText.substr(0,4) == 'true') {
					this.destination.innerHTML = '<div style="text-align: center;">Enhorabuena, tu solicitud para participar en la beta se ha realizado correctamente.</div>';
					if(this.elementAdd) {
						this.elementAdd.innerHTML += oXML.responseText.substr(4);
					}
				} else {
					this.destination.innerHTML = '<div style="text-align: center;">Ha habido un problema con tu solicitud, contacta con el equipo de 37pixels para solucionarlo.</div>';
				}			
			}
		}
		
		var hndl = new requestHandler();
		hndl.destination = container;
				
		page(container.id,'/ajax/beta-join.php','email='+elem.email.value,hndl);
		return false;		
}

function tagAdd(elem) {
		if(elem.tag.value == '') {
				alert('Por favor, introduce un tag.');
				return false;
		}
		
		var container = document.getElementById('agregar');
		
		oldform = container.innerHTML;
		
		function requestHandler() {
			this.destination = null;
			this.elementAdd = null;
			
			this.run = function(oXML) {
				//alert(oXML.responseText);
				var data = eval("("+oXML.responseText+")");
				this.elementAdd.innerHTML += data.html.join('');
				var output = '';
				if(data.errores.length > 0) {
					output += '<p>'+data.errores.join('<br />')+'</p>';
				}
				output += '<p>Temas agregados. <a href="#" onclick="document.getElementById(\''+this.destination.id+'\').innerHTML = oldform; initfunc(); return false;">¿Agregar otros temas?</a></p>';
				this.destination.innerHTML = output;
				/*if(oXML.responseText.substr(0,4) == 'true') {
					this.destination.innerHTML = '<p>El tema se ha agregado correctamente. <a href="#" onclick="document.getElementById(\''+this.destination.id+'\').innerHTML = oldform; initfunc(); return false;">¿Agregar otro tema?</a></p>';
					this.elementAdd.innerHTML += oXML.responseText.substr(4);
				} else {
					this.destination.innerHTML = '<p>'+oXML.responseText.substr(5)+' <a href="#" onclick="document.getElementById(\''+this.destination.id+'\').innerHTML = oldform; initfunc(); return false;">¿Agregar otro tema?</a></p>';
				}*/			
								
			}
		}
		
		var hndl = new requestHandler();
		hndl.destination = container;
		hndl.elementAdd = document.getElementById('temas');
				
		page(container.id,'/ajax/pelicula-agregar-tag.php','id='+elem.filmid.value+'&tag='+elem.tag.value,hndl);
		return false;		
}

function discussionAdd(elem) {
		if(elem.mensaje.value == '' || elem.subject.value == '') {
				alert('Por favor, introduce un título y mensaje.');
				return false;
		}
		
		var container = document.getElementById('agregar');
		
		oldform = container.innerHTML;
		
		function requestHandler() {
			this.destination = null;
			this.elementAdd = null;
			
			this.run = function(oXML) {
				if(oXML.responseText.substr(0,4) == 'true') {
					this.destination.innerHTML = '<p>El mensaje se ha agregado correctamente</p>';
					this.elementAdd.innerHTML += oXML.responseText.substr(4);
				} else {
					this.destination.innerHTML = '<p>Ha habido un problema al insertar el mensaje</p>';
				}			
			}
		}
		
		var hndl = new requestHandler();
		hndl.destination = container;
		hndl.elementAdd = document.getElementById('discusiones');
				
		page(container.id,'/ajax/pelicula-agregar-discusion.php',{'id': elem.filmid.value, 'subject': elem.subject.value,'mensaje': elem.mensaje.value,'spoiler': elem.spoiler.checked},hndl,'POST');
		return false;		
}

function discussionReply(elem) {
		if(elem.mensaje.value == '') {
				alert('Por favor, introduce un título y mensaje.');
				return false;
		}
		
		var container = document.getElementById('agregar');
		
		oldform = container.innerHTML;
		
		function requestHandler() {
			this.destination = null;
			this.elementAdd = null;
			
			this.run = function(oXML) {
				if(oXML.responseText.substr(0,4) == 'true') {
					this.destination.innerHTML = '<p>El mensaje se ha agregado correctamente</p>';
					this.elementAdd.innerHTML += oXML.responseText.substr(4);
				} else {
					this.destination.innerHTML = '<p>Ha habido un problema al insertar el mensaje</p>';
				}			
			}
		}
		
		var hndl = new requestHandler();
		hndl.destination = container;
		hndl.elementAdd = document.getElementById('discusiones');
				
		page(container.id,'/ajax/pelicula-agregar-discusion.php',{'id': elem.filmid.value, 'mensaje': elem.mensaje.value, 'discussionid': elem.discussionid.value},hndl,'POST');
		return false;		
}


function criticAdd(elem) {
		if(elem.title.value == '') {
			alert('Por favor, titula la crítica');
			return false;
		}
		if(elem.critic.value == '') {
				alert('Por favor, introduce una crítica.');
				return false;
		}
		
		var container = document.getElementById('agregar');
		
		oldform = container.innerHTML;
		
		function requestHandler() {
			this.destination = null;
			this.elementAdd = null;
			
			this.run = function(oXML) {
				if(oXML.responseText.substr(0,4) == 'true') {
					this.destination.innerHTML = '<p>La crítica se ha agregado correctamente</p>';
					this.elementAdd.innerHTML += oXML.responseText.substr(4);
				} else {
					this.destination.innerHTML = '<p>Ha habido un problema al insertar la crítica</p>';
				}			
			}
		}
		
		var hndl = new requestHandler();
		hndl.destination = container;
		hndl.elementAdd = document.getElementById('criticas');
				
		page(container.id,'/ajax/pelicula-agregar-critica.php',{'id': elem.filmid.value, 'title': elem.title.value,'critica': elem.critic.value},hndl,'post');
		return false;		
}

function descriptionAdd(elem) {
		if(elem.descripcion.value == '') {
				alert('Por favor, introduce una descripción.');
				return false;
		}
		
		var container = document.getElementById('agregar');
		
		oldform = container.innerHTML;
		
		function requestHandler() {
			this.destination = null;
			this.elementAdd = null;
			
			this.run = function(oXML) {
				if(oXML.responseText.substr(0,4) == 'true') {
					this.destination.innerHTML = '<p>La descripción se ha agregado correctamente</p>';
					this.elementAdd.innerHTML += oXML.responseText.substr(4);
				} else {
					this.destination.innerHTML = '<p>Ha habido un problema al insertar la descripción</p>';
				}			
			}
		}
		
		var hndl = new requestHandler();
		hndl.destination = container;
		hndl.elementAdd = document.getElementById('descripciones');
				
		page(container.id,'/ajax/pelicula-agregar-descripcion.php','id='+elem.filmid.value+'&descripcion='+elem.descripcion.value,hndl);
		return false;		
}

function autoCompletion(keyword) {
	
}

function enableCritic(elem) {
	elem.disabled = false;
	elem.onfocus = function() { }
	
	document.getElementById('title').disbled = false;
	document.getElementById('title').onfocus = function() {}
}

function filmCheckExistency(elem) {
	
	document.getElementById('filmtitlemsg').innerHTML = '';
			
		function requestHandler() {
			this.destination = null;
			this.elementAdd = null;
			this.elem = null;
			
			this.run = function(oXML) {
				if(oXML.responseText.substr(0,4) == 'true') {
					//this.elem.value = '';
					document.getElementById('filmtitlemsg').innerHTML = oXML.responseText.substr(4);
					document.getElementById('filmsloading').innerHTML = '<img src="/img/icon-error.png" alt="Error" />';
					document.getElementById('title').setAttribute("class", "error");
				} else {
					document.getElementById('filmsloading').innerHTML = '<img src="/img/icon-ok.png" alt="OK!" />';
					document.getElementById('title').setAttribute("class", "ok");
				}			
			}
		}
		
		var hndl = new requestHandler();
		
		hndl.elem = elem;
				
		page('filmsloading','/ajax/pelicula-comprobar-existencia.php','nombre='+elem.value,hndl);
		return false;	
}

/*************************************************************
	PORTANDO FUNCIONES A jQuery
**************************************************************/

/*function aliasAdd(elem) {
		if(elem.alias.value == '') {
				alert('Por favor, introduce un alias.');
				return false;
		}
		
		var container = document.getElementById('agregar');
		
		oldform = container.innerHTML;
			
		function requestHandler() {
			this.destination = null;
			this.elementAdd = null;
			
			this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
					this.destination.innerHTML = '<p>El alias se ha agregado correctamente</p>';
					this.elementAdd.innerHTML += oXML.responseText.substr(4);
				} else {
					this.destination.innerHTML = '<p>Ha habido un problema al insertar el alias</p>';
				}			
			}
		}
		
		var hndl = new requestHandler();
		hndl.destination = container;
		hndl.elementAdd = document.getElementById('aliases');
				
		page(container.id,'/ajax/pelicula-agregar-alias.php','id='+elem.filmid.value+'&alias='+elem.alias.value,hndl);
		
		$.getJSON('/ajax/pelicula-agregar-alias.php',{'id': elem.filmid.value, 'alias': elem.alias.value});
		
		return false;		
}*/
