/** 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/                           **/
 
 // Loading preload
 
 var img = new Image();
 img.src = '/img/common/loader.gif';
 
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")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, 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);
		  }
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}

function page(targetId,url,params,handler) {
	if(typeof(targetId) == 'object') {
		img = document.createElement('img');
		img.src = '/img/common/loader.gif';
		img.alt = 'Cargando...';	
		targetId.parentNode.replaceChild(img,targetId);
	} else if(targetId != '') {
		target= document.getElementById(targetId);
		target.innerHTML = '<img src="/img/common/loader.gif" alt="Cargando..." class="loading" />';
	}
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, "GET", params, query);
}

var oldform = '';

function getProvincias(destination,id,cualquiera) {
	
	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				eval(oXML.responseText.substr(4));
				arrayToSelect(provincias,'provincia');
				getLocalidades('localidad',provincias[0][0]);
				this.destination.innerHTML = '';
			} else {
				//this.destination.innerHTML = this.restore;
			}
		}
		
		this.destination = document.getElementById('provincia_loading');
	}	
	
	var hndl = new requestHandler();
	
	var params = 'pais='+id.toString();
	if(cualquiera) {
		params += '&cualquiera=1';
	}
	page('provincia_loading','/ajax/listado-provincias.php',params,hndl);	
}

function getLocalidades(destination,id,cualquiera) {
	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				eval(oXML.responseText.substr(4));
				if(document.getElementById('poblacion')) {
					arrayToSelect(localidades,'poblacion');
			   } else if(document.getElementById('ciudad')) {
				   arrayToSelect(localidades,'ciudad');
			   } else {
				   arrayToSelect(localidades,'localidad');
			   }
				this.destination.innerHTML = '';
			} else {
				//this.destination.innerHTML = this.restore;
			}
		}
		
		this.destination = document.getElementById('localidad_loading');
	}	
	
	var hndl = new requestHandler();
	
	var params = 'provincia='+id.toString();
	if(cualquiera) {
		params += '&cualquiera=1';
	}	
	page('localidad_loading','/ajax/listado-localidades.php',params,hndl);		
}

function getComments(destination,id,table) {
	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;
			}
		}
		
		this.destination = destination;
	}	
	
	var hndl = new requestHandler();
	
	var params = 'table='+table+'&id='+id;
	page(destination.id,'/ajax/comment-load.php',params,hndl);		
}

function voteImage(destination,id,votacion,seccion,tabla) {
	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				eval(oXML.responseText.substr(4));
				this.destination.innerHTML = result[0];
				votos[currentid][0] = result[1];
				votos[currentid][1] = result[2];
				votesShow();
				
				if(document.getElementById('fotoContainer-'+currentid) != null) {
					
					document.getElementById('starsComment').style.display = 'none';
					
					checkvotes[currentid] = votacion;
					var hijos = document.getElementById('fotoContainer-'+currentid).getElementsByTagName('div');
					hijos[0].className = 'votado';
					var output = '<span style="color:#999;">Le has dado <b>'+votacion+'</b> puntos</span><br />';
					for(var i=0;i<5;i++) {
						output += '<img src="/img/foro/estrella-';
						if(i<checkvotes[currentid]) { output += 'on'; } else { output += 'off'; }
						output += '.gif" alt="Puntuación"/>';
					}
					hijos[0].innerHTML = output;
				}
				
			} else {
				if(oXML.responseText.length > 5) {
						eval(oXML.responseText.substr(5));
						alert(result[0]);
						this.destination.innerHTML = 'Ya has votado';
				} else {
						alert('Debes estar identificado para votar');
						window.location.href='/login.php';
				}
			}
		}
		
		this.destination = destination;
		oldvotes = this.destination.innerHTML;		
	}	
	
	var hndl = new requestHandler();
	
	var params = 'id='+id+'&votos='+votacion;
	
	if(seccion == null) {
		seccion = 'albumes';
	}
	if(tabla == null) {
		tabla = 'galdocs';
	}
	
	params += '&tabla='+tabla+'&seccion='+seccion;
	
	page(destination.id,'/ajax/vote.php',params,hndl);		
}

function deletePhoto(id,tipo) {
	var element = document.getElementById('photo-list-'+id);
	
	var boton = element.getElementsByTagName('input');
	for(var i=0;i<boton.length;i++) {
		if(boton[i].type == 'button') {
			boton = boton[i];
			break;
		}
	}

	function requestHandler() {
		this.destination = null;
		this.restore = null;
		
		this.run = function(oXML) {
			if(oXML.responseText.substr(0,4) == 'true') {
				this.destination.style.display = 'none';
				
				var marco = document.getElementById('concurso-upload');
				if(marco) {
					marco.contentDocument.getElementById('uploadfield').onclick = function() { };
					document.getElementById("mensaje").style.display="";
				}
				
			} else {
				alert('Error al intentar borrar la imagen');
				img = this.destination.getElementsByTagName('img');
				img = img[1];
				img.parentNode.replaceChild(this.restore,img);
			}
		}
	}	
	var hndl = new requestHandler();
	
	hndl.destination = element;
	hndl.restore = boton.cloneNode(true);
	
	var params = 'id='+id+'&tipo='+tipo;
	page(boton,'/ajax/borrar-foto.php',params,hndl);	

}
function imagenPrincipal(perro, id){ 
	fotosContainer = document.getElementById('fotos-container');
	fotos = fotosContainer.getElementsByTagName('div');
	for(var i=0;i<fotos.length;i++) {
		if(fotos[i].id.indexOf('photo-list') != -1) {
			if(fotos[i].id == 'photo-list-'+id) {
				fotos[i].getElementsByTagName('div')[0].className = 'gestion-galeria fotoactiva';						
			} else {
				fotos[i].getElementsByTagName('div')[0].className = 'gestion-galeria';
			} 
		}
	}	
	var xmlHttp = new XHConn();
	
	xmlHttp.connect('/ajax/cambiar-foto.php', 'GET', 'perro='+perro+'&imagen='+id );
	//xmlHttp.connect = function(sURL, sMethod, sVars, fnDone)
		
}

function cargar_paises(id){
	var pais=document.getElementById('pais');
	if(pais.options.length < 5){
		/*
		page('provincia_loading','/ajax/listado-paises.php','pais='+pais.value,
				function(e){
					pais.innerHTML=e.responseText;
				    document.getElementById('provincia_loading').innerHTML='';
				});	
		*/
		var xmlHttp = new XHConn();
		
		if(xmlHttp){
			xmlHttp.connect('/ajax/listado-paises.php', 'GET','id='+id, function(e){ pais.innerHTML=e.responseText;	});
		}
	} 
}

function cargar_razas(){
	var raza=document.getElementById('raza');
	if(raza.options.length < 10){
		/*
		page('razas_loading','/ajax/listado-razas.php','', 
				function(e){
					raza.innerHTML=e.responseText;
					document.getElementById('razas_loading').innerHTML='';
				});	
		*/
		var xmlHttp = new XHConn();
		if(xmlHttp){
			xmlHttp.connect('/ajax/listado-razas.php', 'GET','', function(e){ raza.innerHTML=e.responseText; });
		}
	}
}

function cargar_provincias(pais){
	var provincias = document.getElementById('provincia');
	if(provincias.options.length == 1 && pais!=0){
		//getProvincias('pais',pais,'1');
		var xmlHttp = new XHConn();
		if(xmlHttp){ 
			xmlHttp.connect('/ajax/listado-provincias.php', 'GET','pais='+pais,  
					function(e){   
						//provincias.innerHTML=e.responseText;
						if(e.responseText.substr(0,4) == 'true') {
							eval(e.responseText.substr(4));
							arrayToSelect(provincias,'provincia');
						} 
					});
		}
	}
	/*if(pais.selectedIndex && pais.options){
		get
	}*/
}
function guardarDescripcionFoto(id){
	var descr = document.getElementById('titulo['+id+']');
	 
	if(descr.value!='Introduzca una breve descripción de la foto'){
		var xmlHttp = new XHConn();
		xmlHttp.connect('/ajax/guardar-descripcion-foto.php', 'POST', 'descripcion='+descr.value+'&foto='+id, 
						function(e){
							alert(e.responseText);
						});
	} 
	 
}

function arrayToSelect(data,dest) {
	dest = document.getElementById(dest);
	dest.options.length = 0;	
	for(var i=0;i<data.length;i++) {
		if(data[i][1] == '') { continue; }
		dest.options[dest.options.length] = new Option(data[i][1],data[i][0]);
	}
}
