function ErrorMSJ(titulo, code)
{
    oCortina.showError(Array(arrErrores["MICARRITO"][code]), titulo);
}
function InfoMSJ(titulo, code, pagina, showbutton)
{
        oCortina.showInfo(Array(arrErrores["MICARRITO"][code]), titulo, pagina, showbutton);
}
function ValidarForm(frm)
{
    try
    {
        if(frm["frmDir[txtDomicilio]"].value.length == 0 || frm["frmDir[txtNumero]"].value.length == 0 || frm["frmDir[txtCiudad]"].value.length == 0 || frm["frmDir[cbxProvincia]"].value == 0 || frm["frmDir[cbxPais]"].value == 0 || frm["frmDir[txtCP]"].value.length == 0)
        {
            ErrorMSJ("Dirección de envio incorrecta.", "DIRECCION_ENVIO");
            return false;
        }
        frm.submit();
    }
    catch(e)
    {
        throw e;
    }
}

function mostrarDireccion() {
	block = document.createElement('div');
	block.id = 'blockLayer';
	document.body.appendChild(block);
	document.getElementById('direccionEdit').style.display = 'block';
}

function actualizarDatos() {
	document.getElementById('calle').innerHTML = document.getElementById('frmDir[txtDomicilio]').value;
	document.getElementById('no').innerHTML = document.getElementById('frmDir[txtNumero]').value;
	document.getElementById('piso').innerHTML = document.getElementById('frmDir[txtPiso]').value;
	document.getElementById('depto').innerHTML = document.getElementById('frmDir[txtPuerta]').value;
	document.getElementById('ciudad').innerHTML = document.getElementById('frmDir[txtCiudad]').value;
	document.getElementById('prov').innerHTML = document.getElementById('frmDir[cbxProvincia]').options[document.getElementById('frmDir[cbxProvincia]').selectedIndex].innerHTML;

	document.getElementById('direccionEdit').style.display = 'none'
	document.body.removeChild(document.getElementById('blockLayer'));
}

function actualizarTotal() {
	
	var bono = parseInt(document.getElementById('txtBonoUtilizado').value);
	var envioF = document.getElementById('txtGastosEnvio');
	
	var totalF = document.getElementById('txtTotal');
	
	Total = -bono;
	
	var precios = document.getElementsByTagName('input');
	var cantidades = new Array();
	for(i = 0; i < precios.length; i++) {
		
		if(precios[i].className == 'importes') {
			Total += parseInt(precios[i].value);
			
			id = precios[i].id.substr(precios[i].id.indexOf('txtImporte')+10);
			id = id.substr(0, id.indexOf('Total'))
			cantidades[id] = (document.getElementById('frmA[cbxCantidad]['+id+']').selectedIndex + 1);
			
		}
		
	}
	
	cantidades = serialize(cantidades);
	//Obtener costo de envio
	var provincia = document.getElementById('frmDir[cbxProvincia]').options[document.getElementById('frmDir[cbxProvincia]').selectedIndex].value;
	envio = obtenerCostoEnvio(cantidades, provincia);

	document.getElementById('envioGasto').innerHTML = Moneda(envio, MONEDA_DECIMALES, MONEDA_FORMATO);
	envioF.value = envio;
	
	Total += envio;
	
	totalF.value = Total;
	
	document.getElementById('verTotalCompra').innerHTML = Moneda(Total, MONEDA_DECIMALES, MONEDA_FORMATO)
}

function obtenerCostoEnvio(c, p) {

	var costo = 0;
	
	if(p != null)
		p = '&p='+p;
	else
		p = '';
	
	$.ajax({
		type: "GET",
		url: "getCostoEnvio.php",
		data: "c="+c+p,
		async: false,
		success: function(msg){
			costo = msg;
		}
	});
	
	return parseInt(costo);

}

function ValidarCreditos()
{
    try
    {
        var Anterior = "0";
        if(document.getElementById("txtActualizarCreditos").value.length > 0 && parseInt(document.getElementById("txtActualizarCreditos").value) == document.getElementById("txtActualizarCreditos").value)
        {
            if(MaxCreditos < document.getElementById("txtActualizarCreditos").value)
            {
                ErrorMSJ("Creditos", "CREDITOS_MAYOR");
                document.getElementById("txtActualizarCreditos").value = Anterior;
                document.getElementById("CreditoUtilizado").innerHTML=Moneda(Anterior, MONEDA_DECIMALES, MONEDA_FORMATO);;
            }
            else if(document.getElementById("txtActualizarCreditos").value > Ganancia)
            {
                ErrorMSJ("Creditos", "CREDITOS_MAYOR_GANANCIA");
                document.getElementById("txtActualizarCreditos").value = Anterior;
                document.getElementById("CreditoUtilizado").innerHTML=Moneda(Anterior, MONEDA_DECIMALES, MONEDA_FORMATO);;
            }
            else
            {                   
                var BonoAUsar = document.getElementById("txtActualizarCreditos").value;
                var Importe = Total - BonoAUsar;
                document.getElementById("verTotalCompra").innerHTML = Moneda(Importe, MONEDA_DECIMALES, MONEDA_FORMATO);
                document.getElementById("txtTotal").value = Importe;
                document.getElementById("txtBonoUtilizado").value = BonoAUsar;
                document.getElementById("CreditoUtilizado").innerHTML=Moneda(BonoAUsar, MONEDA_DECIMALES, MONEDA_FORMATO);
            }
        }
        else
        {
            ErrorMSJ("Creditos", "CREDITOS_INCORRECTOS");
        }
    }
    catch(e)
    {
        throw e;
    }
}
function FinalizarCompra()
{
    try
    {
        /*var Pago = "";
        for(i=0; i<document.forms[0].optPago.length; i++)
        {
            if(document.forms[0].optPago[i].checked == true)
                Pago = document.forms[0].optPago[i].value;
        }
        if(Pago == "")
        {
            ErrorMSJ("Formas de pago", "PAGOS_SELECCIONE")
        }
        else
        {*/
        
        if(!document.getElementById('dineromail').checked &&
        !document.getElementById('pvisa').checked &&
        !document.getElementById('pmaster').checked &&
        !document.getElementById('pamerican').checked) {
        
        	ErrorMSJ("Atención", "PAGOS_SELECCIONE")
        
        } else if (!document.getElementById('dineromail').checked && document.getElementById('npsBank').selectedIndex == 0){
        	
        	ErrorMSJ("Atención", "BANCO_SELECCIONE")
        	
       	} else {
       	                
	    	if(document.getElementById('dineromail').checked)    
				msjInfoJs("Mi carrito",arrErrores["MICARRITO"]["AVISOS"][1]+"<a href='javascript:document.forms[0].submit();'><img src='"+DIRECTORIO_URL_JS+"front/images/boton-aceptar.gif' /></a>", null,"document.forms[0].submit();", "<img src='"+DIRECTORIO_URL_JS+"front/images/icon-seguridad.gif' />");
			else
				document.forms[0].submit()
				
		}
		    
    }
    catch(e)
    {
        throw e;
    }
}

//Busca los intereses correspondientes para la combinación seleccionada
//Incluye promociones
function setCuotas(idBank, select) {

	if(isNaN(idBank) || idBank == -1) return false;

	document.getElementById('cuotasContainer').style.display = 'block';

	while(select.firstChild)
		select.removeChild(select.firstChild)

	if(inter[idBank]) {
			
		for(i = 0; i < inter[idBank].length; i++) {
			
			var opt = document.createElement('option');
			opt.value = i;
			opt.appendChild(document.createTextNode(inter[idBank][i][0]+' cuotas'))
			select.appendChild(opt);
			
		}
		
		select.onchange = function() {
			promo = inter[idBank][this.options[this.selectedIndex].value][3];
			document.getElementById('promo').style.display = 'none';
			
			interes = null;
			
			if(promo != false) {
				idBancoSeleccionado = document.getElementById('npsBank').options[document.getElementById('npsBank').selectedIndex].value;
				for(i = 0; i < promo.length; i++) {
					if(promo[i][0] == idBancoSeleccionado) {
						document.getElementById('promoName').innerHTML = promo[i][2];
						//document.getElementById('promo').style.display = 'block';
						interes = promo[i][1];				
						break;
					}		
				}
			}
			
			if(interes == null) {
				interes = inter[idBank][this.options[this.selectedIndex].value][1];
			}
			
			cuotas = this.options[this.selectedIndex].text;
			cuotas = parseInt(cuotas.substr(0, cuotas.indexOf('cuotas')));
			document.getElementById('total').innerHTML = (total + (total/100 * interes)).toFixed(2);
			document.getElementById('cuota').innerHTML = ((total + (total/100 * interes)) / cuotas).toFixed(2);
			document.getElementById('cuotaId').value = inter[idBank][this.options[this.selectedIndex].value][2];
			
		}
		
		var promo = inter[idBank][select.options[select.selectedIndex].value][3];
		document.getElementById('promo').style.display = 'none';
		
		interes = null;
		
		if(promo != false) {
			idBancoSeleccionado = document.getElementById('npsBank').options[document.getElementById('npsBank').selectedIndex].value;
			for(i = 0; i < promo.length; i++) {
				if(promo[i][0] == idBancoSeleccionado) {		
					document.getElementById('promoName').innerHTML = promo[i][2];
					//document.getElementById('promo').style.display = 'block';
					interes = promo[i][1];
					break;
				}		
			}
		}
		
		if(interes == null) {
			interes = inter[idBank][select.options[select.selectedIndex].value][1];
		}
		
		cuotas = select.options[select.selectedIndex].text;
		cuotas = parseInt(cuotas.substr(0, cuotas.indexOf('cuotas')))
			
		document.getElementById('total').innerHTML = (total + (total/100 * interes)).toFixed(2);
		document.getElementById('cuota').innerHTML = ((total + (total/100 * interes)) / cuotas).toFixed(2);
		document.getElementById('cuotaId').value = inter[idBank][select.options[select.selectedIndex].value][2];
		
	}

}

function setOpacity(testObj, value) {
	testObj.style.opacity = value/10;
	testObj.style.filter = 'alpha(opacity=' + value*10 + ')';
}

function highlight(n) {
	for(i = 1; i <= 4; i++)
		setOpacity(document.getElementById('bot'+i), 5);
		
	setOpacity(document.getElementById(n), 10);
}

/* SERIALIZE */
function serialize (mixed_value) {
    // Returns a string representation of variable (which can later be unserialized)  
    // 
    // version: 910.813
    // discuss at: http://phpjs.org/functions/serialize
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
    // +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
    // +   bugfixed by: Jamie Beck (http://www.terabit.ca/)
    // +      input by: Martin (http://www.erlenwiese.de/)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
    var _getType = function (inp) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            mixed_value = this.utf8_encode(mixed_value);
            val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = this.serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += this.serialize(okey) +
                        this.serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
        case "undefined": // Fall-through
        default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
            val = "N";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";
    }
    return val;
}

function utf8_encode ( argString ) {
    // Encodes an ISO-8859-1 string to UTF-8  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/utf8_encode
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}
