// JavaScript Document
var server = "http://www.xoppi.com/";

function strTrim(texto) {
	return texto.replace(/^\s+|\s+$/g,"");
}

function changeToStaticSearch(cadena, lang) {
	//return true;
	//cadena = cadena.toLowerCase();
	var keywords    = strTrim(cadena);
	keywords		= replaceRareChars(keywords);
	//if(cadena.indexOf(".")>-1) return true;
	//if(cadena.indexOf("/")>-1) return true;
	//if (/[^\w\-\s]/.test(keywords) || keywords.search(/\S/)==-1 ) return true;
	
    keywords        = keywords.replace(/-/g, '==');		// Cambiamos - por _-_
    keywords        = keywords.replace(/\./g, "_o_");		// Cambiamos . por __-__
	//keywords        = keywords.replace(/\./g, "-");		// Cambiamos . por __-__
    keywords        = keywords.replace(/\s+/g, "-");		// Cambiamos espacios por -
    keywords        = keywords.replace(/\//g, "_oo_");		// Cambiamos / por --- ## No hacemos el cambio todavia, porque crea conflico en buscar.php
	keywords        = keywords.replace(/\%/g, "_p_");		// Cambiamos . por __-__
	keywords        = keywords.replace(/\&/g, "_pp_");		// Cambiamos . por __-__
	keywords        = keywords.replace(/\*/g, "_ooo_");		// Cambiamos . por __-__
	
	var url         = server + keywords;
	//alert(url);
	if(lang=="es") url += "--zzzLang=es";
	//location.href = "00/"+url;
	location.href = url;
	return false;
}

function replaceRareChars(keywords) {

	/*keywords        = keywords.replace(/Á/g, 'A');
    keywords        = keywords.replace(/É/g, 'E');
    keywords        = keywords.replace(/Í/g, 'I');
    keywords        = keywords.replace(/Ó/g, 'O');
    keywords        = keywords.replace(/Ú/g, 'U');
	
	keywords        = keywords.replace(/ç/g, 'c');
    keywords        = keywords.replace(/ã/g, 'a');
    keywords        = keywords.replace(/â/g, 'a');
    keywords        = keywords.replace(/à/g, 'a');
    keywords        = keywords.replace(/ê/g, 'e');
    keywords        = keywords.replace(/ô/g, 'o');

	keywords        = keywords.replace(/Ç/g, 'C');
    keywords        = keywords.replace(/Ã/g, 'A');
    keywords        = keywords.replace(/Â/g, 'A');
    keywords        = keywords.replace(/À/g, 'A');
    keywords        = keywords.replace(/Õ/g, 'O');
    keywords        = keywords.replace(/Ô/g, 'O');*/
	
	keywords = stripVowelAccent(keywords);
	
	//alert(keywords);
	return keywords;
}


function stripVowelAccent(str)
{
	var s=str;
	
	var rExps=[ /[\xC0-\xC2]/g, /[\xE0-\xE3]/g,
	/[\xC8-\xCA]/g, /[\xE8-\xEB]/g,
	/[\xCC-\xCE]/g, /[\xEC-\xEE]/g,
	/[\xD2-\xD4]/g, /[\xF2-\xF5]/g,
	/[\xD9-\xDB]/g, /[\xF9-\xFB]/g, /[\xE7]/]; 
	
	var repChar=['A','a','E','e','I','i','O','o','U','u', 'c'];
	
	for(var i=0; i<rExps.length; i++)
	s=s.replace(rExps[i],repChar[i]);
	
	return s;
}

function setVariable(url, name, value) {
	var test = "--zzz"+name+"=";
	if((pos = url.indexOf(test))>0) {
		var tokens = url.split(test);
		ladoDerecho = tokens[1];
		if(ladoDerecho.indexOf("--zzz")) {
			// Hay mas variables en el lado derecho.
			var tokens2 = ladoDerecho.split("--zzz");
			valor = tokens2[0];
		}
		buscado = test + valor;
		tokens3 = url.split(buscado);
		if(tokens3.length>1) {
			url = tokens3[0]+tokens3[1];
		}
		if(value!= "")
			url += "--zzz"+name+"="+value;
	}
	else if (value!= "") {
		url += "--zzz"+name+"="+value;
	}
	return url;
}

function jsPriceRange(lang) {
	precioMin = document.getElementById('precioMin').value;
	precioMax = document.getElementById('precioMax').value;
	url = location.href;
	url = setVariable(url, "PrecoMin", precioMin);
	url = setVariable(url, "PrecoMax", precioMax);


	/*var test = "--zzzPrecoMin=";
	if((pos = url.indexOf(test))>0) {
		var tokens = url.split(test);
		ladoDerecho = tokens[1];
		if(ladoDerecho.indexOf("--zzz")) {
			// Hay mas variables en el lado derecho.
			var tokens2 = ladoDerecho.split("--zzz");
			valor = tokens2[0];
		}
		buscado = test + valor;
		tokens3 = url.split(buscado);
		if(tokens3.length>1) {
			url = tokens3[0]+tokens3[1];
		}
		if(precioMin!= "")
			url += "--zzzPrecoMin="+precioMin;
	}
	else if (precioMin!= "") {
		url += "--zzzPrecoMin="+precioMin;
	}*/
	/*var test = "--zzzPrecoMax=";
	if((pos = url.indexOf(test))>0) {
		var tokens = url.split(test);
		ladoDerecho = tokens[1];
		if(ladoDerecho.indexOf("--zzz")) {
			// Hay mas variables en el lado derecho.
			var tokens2 = ladoDerecho.split("--zzz");
			valor = tokens2[0];
		}
		buscado = test + valor;
		tokens3 = url.split(buscado);
		if(tokens3.length>1) {
			url = tokens3[0]+tokens3[1];
		}
		if(precioMax!= "")
			url += "--zzzPrecoMax="+precioMax;		
	}
	else if (precioMax!= "") {
		url += "--zzzPrecoMax="+precioMax;		
	}*/
	
	//alert(url);
	location.href = url;
	return false;
}


function sort(id) {
	//precioMin = document.getElementById('precioMin').value;
	//precioMax = document.getElementById('precioMax').value;
	//alert(id[id.selectedIndex].value);
	//return false;
	val = id[id.selectedIndex].value;
	url = location.href;

	if(val==4) {
		url = setVariable(url, "Clase", "ranking");
		url = setVariable(url, "Sort", "ASC");	
	}
	else if(val==3) {
		url = setVariable(url, "Clase", "ranking");
		url = setVariable(url, "Sort", "DESC");	
	}
	else if(val==2) {
		url = setVariable(url, "Clase", "preco");
		url = setVariable(url, "Sort", "ASC");	
	}
	else if(val==1) {
		url = setVariable(url, "Clase", "preco");
		url = setVariable(url, "Sort", "DESC");	
	}		
	else {
		url = setVariable(url, "Clase", "");
		url = setVariable(url, "Sort", "");	
	}
	
	location.href = url;
	return false;
}


function comparar(msg) {
	j = 0;
	for (i = 0; i<document.getElementById('formResultados').pid.length; i++) {
		if (document.getElementById('formResultados').pid[i].checked == true)
			j++;
	}
	if(j<2) {
		alert(msg);
	}
	else {
		document.getElementById('formResultados').action = server+"comparar.php";
		document.getElementById('formResultados').submit();
	}
}

function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
   { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
      {
         IsNumber = false;
      }
   }
   return IsNumber;
}

/* Registro */
function validarRegistro(f, lang) {
	return true; // SOLO PARA PROBAR LA VALIDACION POR PHP.
	var showM = false;
	var m = "";

	if(f.email.value == "") {
		showM = true;
		if(lang=="po") 	m += "Falta email(po)\n";
		else 			m += "Falta email\n";
	}
	else {
		if(echeck(f.email.value)==false) {
			showM = true;
			if(lang=="po") 	m += "O endecao da email e imvalido ;-)(po)\n";
			else 			m += "Dirección de hólá mail inválida\n";			
		}
	}
	
	if(f.usuario.value ==  "") {
		showM = true;
		m += "Debe elejir un nombre de usuario\n";
	}
	
	if(f.password.value != "" && f.confirmar.value != "") {
		if(f.password.value != f.confirmar.value) {
			showM = true;
			m += "Las contrasenhas no coinciden\n";
		}
	}
	else {
		showM = true;
		m += "Debe elejir una contrasenha para la cuenta\n";
	}
	
	if(f.security_code.value ==  "") {
		showM = true;
		m += "Falta el codigo de seguridad\n";
	}
	m += "Lenguaje="+lang;
	if(showM) {
		alert(m);
		return false
	}
	else {
		xajax_verificarCodigo(document.getElementById('security_code').value); 
		return false
	}
}

function validarPerfil(f, lang) {
	return true; // SOLO PARA PROBAR LA VALIDACION POR PHP.
	var showM = false;
	var m = "";
	if(f.password.value != "") {
		if(f.password.value != f.confirmar.value) {
			showM = true;
			m += "Las contraseñas no coinciden";
		}
	}
	if(f.email.value!= "" && echeck(f.email.value)==false) {
		showM = true;
		if(lang=="po") 	m += "O endecao da email e imvalido ;-)(po)\n";
		else 			m += "Dirección de hólá mail inválida\n";			
	}	
	if(showM) {
		alert(m);
		return false;
	}
}

function validarContactoProducto(f, lang) {
	var showM = false;
	var m = "";
	
	if(lang == 'es')
		var msg = [ 'Falta su nombre', 'Falta su pais', 'Falta su ciudad', 'Su direccion de email es incorrecta', 'Falta el mensaje de contacto'];
	else
		var msg = [ 'Falta o seu nome', 'Falta o seu pais', 'Falta a sua cidade', 'Seu email é incorreto', 'Falta a mensagem de contato'];
	
	if(f.conNombres.value == "") {
		showM = true;
		m += msg[0]+"\n";
	}
	
	if(f.conPais.selectedIndex == 0) {
		showM = true;
		m += msg[1]+"\n";
	}
	
	if(f.conCiudad.value == "") {
		showM = true;
		m += msg[2]+"\n";
	}	
	
	if(!echeck(f.conEmail.value)) {
		showM = true;
		m += msg[3]+"\n";
	}	

	if(f.conMensaje.value == "") {
		showM = true;
		m += msg[4]+"\n";
	}
	
	if(showM) {
		alert(m);
		return false;
	}	
	
	return true;
}



function echeck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		return false
	 }
	
	 if (str.indexOf(" ")!=-1){
		return false
	 }

	 return true					
}

function resenaOrden(value, idExistencia) {
	location.href = server + "resenas.php?id="+idExistencia+"&o="+value+"#resenas";
}

function cuadraditoCambiarEstado(id, id2, estado, idC) {
	var color = "";
	if(estado == 1) {
		color = "white";
		document.getElementById(id2).style.backgroundColor  = "#0066cb";
	}
	else {
		color = "";
		document.getElementById(id2).style.backgroundColor  = "";
	}

	document.getElementById(id).style.backgroundColor  = color;
	mostrar_vis_prod(idC);
}

function cuadraditoCambiarEstado2(id, id2, estado, idC) {
	var color = "";
	if(estado == 1) {
		color = "white";
		document.getElementById(id2).style.backgroundColor  = "#d6ff34";
	}
	else {
		color = "";
		document.getElementById(id2).style.backgroundColor  = "";
	}

	document.getElementById(id).style.backgroundColor  = color;
	//alert(idC);
	mostrar_vis_prod2(idC);
}

function cuadraditoCambiarEstado3(id, id2, estado, idC) {
	var color = "";
	if(estado == 1) { 
		color = "white";
		document.getElementById(id2).style.backgroundColor  = "#f9a46e";
		//alert("premium_vis_"+id2);
		document.getElementById("premium_vis_"+id2).style.backgroundColor  = "#faa36e";
	}
	else {
		color = "";
		document.getElementById(id2).style.backgroundColor  = "";
		document.getElementById("premium_vis_"+id2).style.backgroundColor  = "";
	}
}
 


/***************/
/* PriceAlert! */
function pAlert(idE) {
	div = "pAlert_"+idE;

	var html = 	'<div style="background-color:#c5d8e6; color:#000000; padding:3px">' +
					'<b>Alertar-me quando o preço do produto seja menor a:</b><Br />'+
					'U$S: <input type="text" id="precio_'+idE+'" size="4" /> Email: <input type="text" id="email_'+idE+'" size="18" /> <input type="button" value="Ok" onClick="guardarAlerta('+idE+')" />'+
				'</div>';

	document.getElementById(div).innerHTML = html;
}

function guardarAlerta(idE) {
	//alert("Guardaremos alerta de " + idE);
	precio = document.getElementById('precio_'+idE).value;
	email = document.getElementById('email_'+idE).value;
	//alert(precio + " " +email);
	div = "pAlert_"+idE;
	
	function pageCallback(response){
		response = "O brigado!";
		document.getElementById(div).innerHTML=response;
	}

	var ajax = new GLM.AJAX();
	var pagina = server + "/acciones/accion.php?accion=2321bac7aa8936e29603e7bcea537ae4&idE="+idE+"&email="+email+"&precio="+precio;
	ajax.callPage(pagina, pageCallback);	
	//document.getElementById(div).innerHTML=pagina;
	//document.getElementById(div).innerHTML = "Hemos guardado su alerta";
}

function agregarImagen(url) {
	var idExistencia = document.getElementById('id_existencia_img').value;
	function pageCallback(response){
		//response = "O brigado!";
		//document.getElementById(div).innerHTML=response;
		alert(response);
		document.getElementById('id_estado').value = "Foto agregada, busque y elija nuevamente...";
		document.getElementById('id_estado').focus();
	}

	document.getElementById('id_estado').value = "Cargando imagen, espere...";
	document.getElementById('id_estado').focus();

	var ajax = new GLM.AJAX();
	var pagina = server + "/acciones/admin.php?accion=6dd71f864fa8f713685eeb03f9981fdd&idE="+idExistencia+"&url="+url;
	ajax.callPage(pagina, pageCallback);	
}

/*var Utf8 = {

	// public method for url encoding
	encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// public method for url decoding
	decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}*/

function utf8(wide) {
	var c, s;
	var enc = "";
	var i = 0;
	while(i<wide.length) {
		c= wide.charCodeAt(i++);
		// handle UTF-16 surrogates
		if (c>=0xDC00 && c<0xE000) continue;
		if (c>=0xD800 && c<0xDC00) {
			if (i>=wide.length) continue;
			s= wide.charCodeAt(i++);
			if (s<0xDC00 || c>=0xDE00) continue;
			c= ((c-0xD800)<<10)+(s-0xDC00)+0x10000;
		}
		// output value
		if (c<0x80) enc += String.fromCharCode(c);
		else if (c<0x800) enc += String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F));
		else if (c<0x10000) enc += String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F));
		else enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F));
	}
	return enc;
}

function agregarGimg(url, idExistencia, idCde) {
	function pageCallback(response){
		//response = "O brigado!";
		//document.getElementById(div).innerHTML=response;
		//alert(response);
		//alert(idCde);
		if( response != "ERROR :-(" ) {
			//alert(response);
			document.getElementById('gi_'+idCde).src = response;
			document.getElementById('giConsole_'+idCde).innerHTML = "";
			//alert(idCde + " " + response);
			//alert(document.getElementById('gi_'+idCde).src);
		}
		else {
			alert("ERROR :-(");
		}
		//document.getElementById('id_estado').value = "Foto agregada, busque y elija nuevamente...";
		//document.getElementById('id_estado').focus();
	}

	//document.getElementById('id_estado').value = "Cargando imagen, espere...";
	//document.getElementById('id_estado').focus();

	var ajax = new GLM.AJAX();
	var pagina = server + "/acciones/admin.php?accion=5cd49b284bbb25c782e448df9cc70066&idE="+idExistencia+"&url="+url;
	ajax.callPage(pagina, pageCallback);	
}