dojo.require("dojo.io.*");
dojo.require("dojo.event.*");

/**************************************/
function datosServidor() {
};
datosServidor.prototype.iniciar = function() {
	try {
		// Mozilla / Safari
		this._xh = new XMLHttpRequest();
	} catch (e) {
		// Explorer
		var _ieModelos = new Array(
		'MSXML2.XMLHTTP.5.0',
		'MSXML2.XMLHTTP.4.0',
		'MSXML2.XMLHTTP.3.0',
		'MSXML2.XMLHTTP',
		'Microsoft.XMLHTTP'
		);
		var success = false;
		for (var i=0;i < _ieModelos.length && !success; i++) {
			try {
				this._xh = new ActiveXObject(_ieModelos[i]);
				success = true;
			} catch (e) {
				// Implementar manejo de excepciones
			}
		}
		if ( !success ) {
			return false;
		}
		return true;
	}
}

datosServidor.prototype.ocupado = function() {
	estadoActual = this._xh.readyState;
	return (estadoActual && (estadoActual < 4));
}

datosServidor.prototype.procesa = function() {
	if (this._xh.readyState == 4 && this._xh.status == 200) {
		this.procesado = true;
	}
}

datosServidor.prototype.enviar = function(urlget,id, zona) {
	if (!this._xh) {
		this.iniciar();
	}
	if (!this.ocupado()) {
		this._xh.open("GET",urlget,false);
		this._xh.send(id);

		if (this._xh.readyState == 1) {
			divMensajes=document.getElementById(zona);
			divMensajes.innerHTML = "<img src='http://es.shoomo.com/imgs/loader.gif' alt='Enviando' />";
		}

		if (this._xh.readyState == 4 && this._xh.status == 200) {
			divMensajes=document.getElementById(zona);
			divMensajes.innerHTML = this._xh.responseText;
		}

	}
	return false;
}

function _gr(reqseccion,divcont) {
	remotos = new datosServidor;
	nt = remotos.enviar(reqseccion,"");
	document.getElementById(divcont).innerHTML = nt;
}

function seleccionarProdComparador(zona,tipo) {
	if (tipo == "ON")
		document.getElementById(zona).className = "unidadoff";
    else
		document.getElementById(zona).className = "unidad";
}
function utopiasExtraCallback(type, data, evt)
{
	if (type == 'error')
	  alert("Hay un problema para añadir su utopía.\n Intentelo más adelante.");
	else {
        temp =  document.getElementById('layer_utopias_barra').innerHTML;
        temp1 =  temp.indexOf('(') + 1;
        temp2 = temp.indexOf(')');
        temp = parseInt(temp.substring(temp1,temp2)) + 1;
        document.getElementById('layer_utopias_barra').innerHTML = '<a href="/utopias.php">Utopías(' + temp + ')</a>'
		tempData = data.split('|||');
		document.getElementById(tempData[0]).innerHTML = 'Utopía agregada';
    	dojo.fx.html.highlight(document.getElementById(tempData[0]), 1000, "#ffe761");
    	dojo.fx.html.highlight(document.getElementById('layer_utopias_barra'), 1000, "#ffe761");
        setTimeout('parpadeoUtopias("layer_utopias_barra")',1100);
        setTimeout('parpadeoUtopias("layer_utopias_barra")',2200);
    }
}
function votacionExtraCallback(type, data, evt)
{
	if (type == 'error')
	  alert("Hay un problema para añadir su voto.\n Intentelo más adelante.");
	else {
        /* temp =  document.getElementById('layer_utopias_barra').innerHTML;
        temp1 =  temp.indexOf('(') + 1;
        temp2 = temp.indexOf(')');
        temp = parseInt(temp.substring(temp1,temp2)) + 1;
        document.getElementById('layer_utopias_barra').innerHTML = '<a href="/utopias.php">Utopías(' + temp + ')</a>'
		tempData = data.split('|||');
		document.getElementById(tempData[0]).innerHTML = 'Utopía agregada';
    	dojo.fx.html.highlight(document.getElementById(tempData[0]), 1000, "#ffe761");
    	dojo.fx.html.highlight(document.getElementById('layer_utopias_barra'), 1000, "#ffe761");
        setTimeout('parpadeoUtopias("layer_utopias_barra")',1100);
        setTimeout('parpadeoUtopias("layer_utopias_barra")',2200); */
        window.location.reload();
    }
}

function valoracionExtraCallback(type, data, evt) {
	if (type == 'error')
	  alert("Hay un problema para añadir su valoracion.\n Intentelo más adelante.");
	else {
        temp =  document.getElementById('valoracion').innerHTML;
        window.location.reload();
		//window.location.replace();
		//document.getElementById('valoracion').innerHTML = temp;
		//tempData = data.split('|||');
		//document.getElementById(tempData[0]).innerHTML = 'valorado';
    	//dojo.fx.html.highlight(document.getElementById(tempData[0]), 1000, "#ffe761");
    	//dojo.fx.html.highlight(document.getElementById('valoracion'), 1000, "#ffe761");
        //setTimeout('parpadeoUtopias("valoracion")',1100);
        //setTimeout('parpadeoUtopias("valoracion")',2200);
    }

}

/*
function valoracionExtraCallback(type, data, evt) {
	if (type == 'error')
	  alert("Hay un problema para añadir su valoracion.\n Intentelo más adelante.");
	else {
		dojo.io.bind ({
		url: 'process_avatar.php',
		handler: avatarCallback,
		mimetype: "text/plain",
		formNode: dojo.byId('valoracion')
		});
	}
}
*/

function agregarUtopiasExtra(prod_id,cookie_usuario,tienda,zona) {
	dojo.io.bind({
    		url: '/php-include/utopias_agregar_dojo.php',
            handler: utopiasExtraCallback,
            content: {prod_id: prod_id, cookie_usuario: cookie_usuario, tienda: tienda, zona: zona}
    })
}

function verificarEnvioEmailFichaCallback(type, data, evt)
{
	if (type == 'error')
		document.getElementById(tempData[0]+"_div_errores").innerHTML = "<br />Por razones técnicas, no es posible guardar su opinion. <br />Por favor, inténtelo más adelante.<br />El Equipo de Shoomo.com";
	else {
	    error = 'FALSE';
        newdata = new String(data);
		tempData = newdata.split("***");
        prod_titulo = tempData[1];
        prod_pros = tempData[2];
        prod_contras = tempData[3];
        prod_opinion = tempData[4];
        prod_tags = tempData[5];

        if (prod_titulo == "SI") {
			document.getElementById("titulo_opinion").style.background = "#FFFF66";
            error = 'TRUE';
        } else
			document.getElementById("titulo_opinion").style.background = "#FFFFFF";
        if (prod_pros == "SI") {
			document.getElementById("pros").style.background = "#FFFF66";
            error = 'TRUE';
        } else
			document.getElementById("pros").style.background = "#FFFFFF";
        if (prod_contras == "SI") {
			document.getElementById("contras").style.background = "#FFFF66";
            error = 'TRUE';
        } else
			document.getElementById("contras").style.background = "#FFFFFF";
        if (prod_opinion == "SI") {
			document.getElementById("cuerpo_opinion").style.background = "#FFFF66";
            error = 'TRUE';
        } else
			document.getElementById("cuerpo_opinion").style.background = "#FFFFFF";
        if (prod_tags == "SI") {
			document.getElementById("opinion_tags").style.background = "#FFFF66";
            error = 'TRUE';
        } else
			document.getElementById("opinion_tags").style.background = "#FFFFFF";

        if (tempData[6] == 'TRUE' && error == 'TRUE') {
			document.getElementById(tempData[0]+"_div_errores").innerHTML = tempData[7] + "<br />Asegurate de rellenar todos los campos requeridos<br />";
        } else if (tempData[6] != 'TRUE' && error == 'TRUE') {
			document.getElementById(tempData[0]+"_div_errores").innerHTML = "Asegurate de rellenar todos los campos requeridos<br />";
        } else if (tempData[6] == 'TRUE' && error != 'TRUE') {
			document.getElementById(tempData[0]+"_div_errores").innerHTML = tempData[7] + "<br />";
        } else {
	        document.getElementById(tempData[0]).submit();
        }
    }
}
function checkForm(id) {
	dojo.io.bind({
	    url: "/ficha-producto/php-include/procesar_envio_email.php",
	    handler: verificarEnvioEmailFichaCallback,
	    formNode: document.getElementById(id)
	});
}

function verificarComentarioCallback(type, data, evt)
{
	if (type == 'error')
		document.getElementById(tempData[0]+"_div_errores").innerHTML = "<br />Por razones técnicas, no es posible guardar su comentario. <br />Por favor, inténtelo más adelante.<br />El Equipo de Shoomo.com";
	else {
	    var error = 'FALSE';
		tempData = data.split('***');
        comentario = tempData[1];
        if (comentario == "") {
			document.getElementById("error_comentario").style.background = "#FFFF66";
            error = 'TRUE';
        }

        if (tempData[2] == 'TRUE' && error == 'TRUE') {
			document.getElementById(tempData[0]+"_div_errores").innerHTML = tempData[3] + "<br />Asegurate de rellenar todos los campos requeridos<br />";
        } else if (tempData[2] != 'TRUE' && error == 'TRUE') {
			document.getElementById(tempData[0]+"_div_errores").innerHTML = "Asegurate de rellenar todos los campos requeridos<br />";
        } else if (tempData[2] == 'TRUE' && error != 'TRUE') {
			document.getElementById(tempData[0]+"_div_errores").innerHTML = tempData[3] + "<br />";
        } else {
	        document.getElementById(tempData[0]).submit();
        }
    }
}
function ValidateComment(id) {
	dojo.io.bind({
	    url: "/ficha-producto/php-include/procesar_verificar_comentario.php",
	    handler: verificarComentarioCallback,
	    formNode: document.getElementById(id)
	});
}

function textCounter(field, countfield, maxlimit) {
    if (field.value.length > maxlimit)
        field.value = field.value.substring(0, maxlimit);
    else
        countfield.value = field.value.length + " de " + maxlimit;
}

function cuenta_caracteres(field, countfield, maxlimit){
    if (field.value.length > maxlimit)
        field.value = field.value.substring(0, maxlimit);
    else
        countfield.value = field.value.length;

}
/*
function votar_opinion(voto,id)  {
	dojo.io.bind({
    		url: '/ficha-producto/votar_opinion.php',
            handler: votacionExtraCallback,
            content: {voto: voto, id: id, zona: 'opinion'+id}
    })
}
function valorar_opinion(voto,id,shop,pnf,pnf_clase)  {
	dojo.io.bind({
    		url: '/ficha-producto/votar_opinion.php',
			handler: valoracionExtraCallback,
            content: {voto: voto, id: id, shop: shop, pnf: pnf, pnf_clase: pnf_clase, zona: 'valoracion'}
    })
}*/
function valorar_opinion_live(voto,id)  {
	dojo.io.bind({
    		url: '/ficha-producto/votar_opinion.php',
			handler: valoracionExtraCallback,
            content: {voto: voto, id: id, zona: 'valoracion_live'}
    })
}

function set_valor(mensaje) {
	document.getElementById("texto-valoracion").innerHTML = mensaje ;
}
function set_valor2(mensaje, zona) {
	document.getElementById(zona).innerHTML = mensaje ;
}

/*  */

var urlBase = "/ficha-producto/votar_opinion.php?";

function votar_opinion(voto,id)  {
		remotos = new datosServidor;
		nt = remotos.enviar('/ficha-producto/votar_opinion.php?voto='+voto+'&id='+id, id, "opinion"+id);
}

function votar_opinion_tienda(voto,id)  {
		remotos = new datosServidor;
		nt = remotos.enviar('/shops2/votar_opinion_tienda.php?voto='+voto+'&id='+id, id, "opinion"+id);
}

function votar_conversacion(voto,id)  {
		remotos = new datosServidor;
		nt = remotos.enviar('/ficha-producto/votar_opinion.php?w=conversacion&voto='+voto+'&id='+id, id, "conversacion"+id);
}

function denunciar_spam(voto,id)  {
		remotos = new datosServidor;
		nt = remotos.enviar('/ficha-producto/votar_opinion.php?voto='+voto+'&id='+id, id, "denuncia-spam");
}

function valorar_opinion(voto,id, shop, pnf, pnf_clase)  {
		set_valor("Gracias");
		remotos = new datosServidor;
		nt = remotos.enviar('/ficha-producto/votar_opinion.php?voto='+voto+'&id='+id+'&shop='+shop+'&pnf='+pnf+'&pnf_clase='+pnf_clase, id, "valoracion");
}

function valorar_tienda(voto,tienda)  {
		set_valor("Gracias");
		var id=0;
		remotos = new datosServidor;
		nt = remotos.enviar('/ficha-producto/votar_opinion.php?voto='+voto+'&tipo=tienda&shop='+tienda, id, "valoracion");
}

function eliminar_opinion(id)  {
		remotos = new datosServidor;
		nt = remotos.enviar('/ficha-producto/xpress2shot.php?id='+id, id, "lista-comentarios");
}

function guardar_cambios(id) {
	remotos = new datosServidor;
	nt = remotos.enviar('/ficha-producto/xpress2shot.php?do=update&cuerpo_opinion='+document.getElementById('editar-opinion').value+'&id_opinion='+id, id, "cuerpo_opinion");
}

function editar_opinion(id) {
	divMensajes=document.getElementById('cuerpo_opinion');
	divMensajes.innerHTML = '<form action="/ficha-producto/xpress2shot.php" method="post"><textarea id="editar-opinion" name="cuerpo_opinion" cols="16" rows="15">' + divMensajes.innerHTML.replace(/<br>/gi,"\r").replace(/<br\/>/gi,"\r") +'</textarea><input type="hidden" name="id_opinion" value="' + id + '" /><input type="submit" value="Guardar" /><input type="submit" value="Cancelar" onclick="cancelar_edicion(\'cuerpo_opinion\',\'editar-opinion\');" /></form>';
	document.getElementById('enlace_editor').innerHTML = '<a href="#cuerpo_opinion" onclick="cancelar_edicion(\'cuerpo_opinion\', \'editar-opinion\');">(cancelar)</a>';
}

function cancelar_edicion(id_fuente, id_resultado) {
	divMensajes=document.getElementById(id_fuente);
	divMensajes.innerHTML = document.getElementById(id_resultado).value;
	document.getElementById('enlace_editor').innerHTML = '<a href="#cuerpo_opinion" onclick="editar_opinion(\'cuerpo_opinion\');">(editar)</a>';
}

function muestra_editor() {
	dojo.style.setOpacity(document.getElementById("edita_opinion"), 0);
	document.getElementById("edita_opinion").style.display = "block";
	dojo.fx.html.fadeHide (document.getElementById("cuerpo_opinion"),0);
	dojo.fx.html.fadeIn (document.getElementById("edita_opinion"),300);
}
								
function cierra_editor() {
	dojo.style.setOpacity(document.getElementById("cuerpo_opinion"), 0);
	document.getElementById("cuerpo_opinion").style.display = "block";

	dojo.fx.html.fadeHide (document.getElementById("edita_opinion"),0);
	dojo.fx.html.fadeIn (document.getElementById("cuerpo_opinion"),500);
}
