var mozilla=false;
if (navigator.appName.indexOf("Microsoft")!=-1)	mozilla=false;
else mozilla=true;

var RutaInfo = "/web/";

function nuevoAjax()
{
	var xmlhttp=false; 
	try { 
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
	} 
	catch (e) { 
		try { 
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		catch (E) { 
			xmlhttp = false; 
		} 
	}
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') { 
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

function ajaxOk(ajax, funcion) 
{
	eval(funcion+"(ajax)");
}

function loadAjax(url, method, vars, funcion, async)
{
	var ajax = nuevoAjax();	
	
	ajax.onreadystatechange = function() {
		if (ajax.readyState==4) 
			if (ajax.status == 200) {
				ajaxOk(ajax, funcion);
			}
	}
	ajax.open(method, url, async);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	ajax.send(vars);
	if (!async && mozilla)
		ajaxOk(ajax, funcion);
}

function number_format(a, b, c, d) {
 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
 e = a + '';
 f = e.split('.');
 if (!f[0]) {
  f[0] = '0';
 }
 if (!f[1]) {
  f[1] = '';
 }
 if (f[1].length < b) {
  g = f[1];
  for (i=f[1].length + 1; i <= b; i++) {
   g += '0';
  }
  f[1] = g;
 }
 if(d != '' && f[0].length > 3) {
  h = f[0];
  f[0] = '';
  for(j = 3; j < h.length; j+=3) {
   i = h.slice(h.length - j, h.length - j + 3);
   f[0] = d + i +  f[0] + '';
  }
  j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
  f[0] = j + f[0];
 }
 c = (b <= 0) ? '' : c;
 return f[0] + c + f[1];
}

function EnviarFormulario()
{
	var nombre = document.getElementById("nombre").value;
	var fono = document.getElementById("fono").value;
	var email = document.getElementById("email2").value;
	var comentarios = document.getElementById("comentarios").value;
	var ruta = document.getElementById("Ruta").value;
	var alerta = "";
	
	if(nombre == "")
	alerta += "Debe ingresar el nombre\n";
	if(fono == "")
	alerta += "Debe ingresar el fono\n";
	if(email == "")
	alerta += "Debe ingresar el email\n";
	if(comentarios == "")
	alerta += "Debe ingresar los comentarios\n";
	
	if(alerta == "")
	{
		var url = RutaInfo + "EnviarCorreo/Nombre=" + nombre;
		url += "&Fono=" + fono;
		url += "&Email=" + email;
		url += "&Comentarios=" + comentarios;
		url += "&Ruta=" + ruta;
		loadAjax(url, "GET", "null", "respuestaEnviarFormulario", true);
		//alert(url);
	}
	else
	{
		alert(alerta);
	}
}

function respuestaEnviarFormulario(ajax)
{
	var resp = ajax.responseText;
	if(resp != "El email es incorrecto.")
	{
		document.getElementById("nombre").value = "";
		document.getElementById("email2").value = "";
		document.getElementById("fono").value = "";
		document.getElementById("comentarios").value = "";
		alert(resp);
	}
	else
	{
		alert(resp);
	}
}

function Paso2()
{
	var email = document.getElementById("email_registro").value;
	var rut = document.getElementById("rut_registro").value;
	var alerta = "";
	
	if(email == "")
	alerta += "Debe ingresar el Email\n";
	if(rut == "")
	alerta += "Debe ingrear el Rut";
	
	if(alerta == "")
	{
		var url = RutaInfo + "Registro/Paso2/";
		var Vars = "Email=" + email;
		Vars += "&Rut=" + rut;
		loadAjax(url, "POST", Vars, "respuestaPaso2", true);
	}
	else
	{
		alert(alerta);
	}
}

function respuestaPaso2(ajax)
{
	var capa = document.getElementById("registro2");
	var email = document.getElementById("email_registro");
	var rut = document.getElementById("rut_registro");
	
	html = ajax.responseText;
	var ok = true;
	if(html == "err-rut")
	{
		if(confirm("El Rut Ingresado ya existe en nuestra base de datos.\nSi desea conocer los usuarios Registrados y solicitar su clave, presiones Aceptar.\n\nDe lo contrario Cancele y envienos un Contacto Rapido solicitando agregar su correo a la lista de usuarios permitidos.\n\nNos pondremos en contacto con usted lo antes posible."))
		{
			location.href = RutaInfo + "SolicitarClave/";
			return true;
		}
		else
		{
			return true;
		}
		
	}
	if(html == "err-email")
	{
		if(confirm("El Email ingresado ya existe en nuestra base de datos.\nDesea que le enviemos la contraseña por correo?."))
		{
			SolicitarClave();
			return true;
		}
		else
		{
			return true;
		}
	}
	if(html == "err-sess")
	{
		alert("Existe un problema de sesion, por favor vuelva a realizar el proceso de registro.");
		return true;
	}
	
	if(ok)
	{
		capa.innerHTML = ajax.responseText;
		email.disabled = true;
		rut.disabled = true;
	}
}

function respuestaEnviarClave(ajax)
{
	alert(ajax.responseText);
}

function SolicitarClave()
{
	var email = document.getElementById("email_registro").value;
	var url = RutaInfo + "EnviarPass/";
	var Vars = "Email=" + email;
	loadAjax(url, "POST", Vars, "respuestaSolicitarClave", true);
}

function SolicitarClave2(id, temp)
{
	var url = RutaInfo + "EnviarPass/";
	var Vars = "IDContacto=" + id;
	Vars += "&Temporal=" + temp;
	loadAjax(url, "POST", Vars, "respuestaSolicitarClave", true);
}


function respuestaSolicitarClave(ajax)
{
	alert(ajax.responseText);
}

function SolicitarEmails()
{
	var rut = document.getElementById("rut_registro").value;
	var url = RutaInfo + "SolicitarCorreos/";
	var Vars = "Rut=" + rut;
	loadAjax(url, "POST", Vars, "respuestaSolicitarEmails", true);	
}

function respuestaSolicitarEmails(ajax)
{
	var capa = document.getElementById("correos");
	capa.innerHTML = ajax.responseText;
}

function ValidaRUT(form, campo)
{
        var valor = ValidarRUT(campo.value.toUpperCase());
        if(!valor)
        {
                alert("El RUT ingresado no es valido");
                campo.value="";
                campo.focus();
        }
        else
        {
                campo.value=Trim(valor);
        }
}

function ValidarRUT(RUT)
{
        if (Trim(RUT) != "")
        {
                RUT=Trim(RUT);
                RUT=replaceSubstring(RUT, ".", "");
                RUT=replaceSubstring(RUT, "-", "");
                RUT=Trim(RUT);
                DV=RUT.substring(RUT.length-1, RUT.length);
                RUT=RUT.substring(0, RUT.length-1);
                var suma=0;
                var digit=2;
                var aux=0;
                for (r=RUT.length-1; r>=0; r=r-1)
                {
                        valor=parseInt(RUT.substring(r, r+1));
                        aux=digit*valor;
                        suma=suma+aux;
                        digit++;
                        if (digit>7)
                        {
                                digit=2;
                        }
                }
                test=11-(suma%11);
                if (test==10)
                {
                        test="K";
                }
                if (test==11)
                {
                        test=0;
                }
                if (DV==test)
                {
                        valido=addCommas(RUT)+"-"+DV;
                }
                else
                {
                        valido=false;
                }
        }
        else
        {
                valido=" ";
        }
        return valido;
}

function ValidaEmail(campo)
{
     var valor=ValidarEmail(campo);
     if (!valor)
     {
             alert("El Email ingresado no es valido");
             campo.value="";
             campo.focus();
     }
     else
     {
             //campo.value=Trim(valor);
     }
}

function ValidarEmail(campo)
{
        var s = campo.value;
        var filter=/^[A-Za-z][A-Za-z0-9_.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
        if (s.length==0)
        {
                return true;
        }
        if (filter.test(s))
        {
                return true;
        }
        else
        {
                return false;
        }
}

function Trim(TRIM_VALUE)
{
        if(TRIM_VALUE.length < 1)
        {
                return "";
        }
        TRIM_VALUE = RTrim(TRIM_VALUE);
        TRIM_VALUE = LTrim(TRIM_VALUE);
        if(TRIM_VALUE=="")
        {
                return "";
        }
        else
        {
                return TRIM_VALUE;
        }
}

function RTrim(VALUE)
{
        var w_space = String.fromCharCode(32);
        var v_length = VALUE.length;
        var strTemp = "";
        if(v_length < 0)
        {
                return "";
        }
        var iTemp = v_length -1;
        while(iTemp > -1)
        {
                if(VALUE.charAt(iTemp) == w_space)
                {
                }
                else
                {
                        strTemp = VALUE.substring(0,iTemp +1);
                        break;
                }
                iTemp = iTemp-1;
        }
        return strTemp;
}

function LTrim(VALUE)
{
        var w_space = String.fromCharCode(32);
        if(v_length < 1)
        {
                return "";
        }
        var v_length = VALUE.length;
        var strTemp = "";
        var iTemp = 0;
        while(iTemp < v_length)
        {
                if(VALUE.charAt(iTemp) == w_space)
                {
                }
                else
                {
                        strTemp = VALUE.substring(iTemp,v_length);
                        break;
                }
                iTemp = iTemp + 1;
        }
        return strTemp;
}

function replaceSubstring (inputString, badString, goodString, caseSensitive )
{
        fixedReplace = " ";
        UI = inputString;
        UB = badString;
        if ((caseSensitive !=1) && (caseSensitive != true))
        {
                UI = inputString.toUpperCase();
                UB = badString.toUpperCase();
        }
        badEnd = -1;
        badLoc = UI.indexOf(UB);
        if (badLoc != -1)
        {
                for (x=1; (badLoc != -1); x++)
                {
                        fixedReplace = fixedReplace + inputString.substring((badEnd + 1), badLoc) + goodString
                        badEnd = badLoc + UB.length - 1;
                        badLoc = UI.indexOf(UB, (badLoc + 1));
                }
                fixedReplace = fixedReplace + inputString.substring((badEnd + 1), inputString.length);
        }
        else
        {
                fixedReplace = inputString;
        }
        return fixedReplace;
}

function addCommas(nStr)
{
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + '.' + '$2');
        }
        return x1 + x2;
}

function BuscarComunas(id)
{
	var url = RutaInfo + "BuscarComunas/";
	var Vars = "IDCiudad=" + id;
	loadAjax(url, "POST", Vars, "respuestaBuscarComunas", true); 
}

function respuestaBuscarComunas(ajax)
{
	var capa = document.getElementById("comunas");
	var html = ajax.responseText;
	capa.innerHTML = html;
}

function FinalizarRegistro()
{
	var razonsocial = document.getElementById("razonsocial_registro").value;
	var giro = document.getElementById("giro_registro").value;
	var direccion = document.getElementById("direccion_registro").value;
	var ciudad = document.getElementById("ciudad_registro").value;
	var comuna = document.getElementById("comuna_registro").value;
	var fono = document.getElementById("fono_registro").value;
	var contacto = document.getElementById("contacto_registro").value;
	var password = document.getElementById("password_registro").value;
	var alerta = "";
	
	if(razonsocial == "")
	alerta += "Debe ingresar la Razon Social\n";
	if(giro == "")
	alerta += "Debe ingresar el Giro. En caso de no tener, debe poner Particular\n";
	if(direccion == "")
	alerta += "Debe ingresar la Direccion\n";
	if(ciudad == 0)
	alerta += "Debe seleccionar la ciudad\n";
	if(comuna == 0)
	alerta += "Debe seleccionar la comuna\n";
	if(fono == "")
	{
		alerta += "Debe seleccionar la comuna\n";
	}
	else
	{
			if(fono.length > 15)
			{
				alerta += "El Fono debe ser de menos de 15 caracteres\n";
			}
	}
	if(contacto == "")
	alerta += "Debe ingresar el nombre del contacto\n";
	if(password == "")
	{
		alerta += "Debe ingresar la contraseña\n";
	}
	else
	{
		if(password.length < 6)
		{
			alerta += "La contraseña debe tener entre 6 y 20 caracteres\n";
		}
	}
	
	if(alerta != "")
	{
		alert(alerta);
	}	
	else
	{
		var url = RutaInfo + "Registro/FinalizarRegistro/";
		var Vars = "RazonSocial=" + razonsocial;
		Vars += "&Giro=" + giro;
		Vars += "&Direccion=" + direccion;
		Vars += "&Ciudad=" + ciudad;
		Vars += "&Comuna=" + comuna;
		Vars += "&Fono=" + fono;
		Vars += "&Contacto=" + contacto;
		Vars += "&Password=" + password;
		loadAjax(url, "POST", Vars, "respuestaFinalizarRegistro", true);
	}
}

function respuestaFinalizarRegistro(ajax)
{
	if(ajax.responseText.length > 10)
	{
		alert(ajax.responseText);
	}
	else
	{
		IraHome();
	}
}

function IraHome()
{
	location.href = RutaInfo;
}

function Ingresar()
{
	var usuario = document.getElementById("usuario").value;
	var password = document.getElementById("password").value;
	var alerta = "";
	
	if(usuario == "")
	alerta += "Debe ingresar el Email\n";
	if(password == "")
	alerta += "Debe ingresar la Contraseña\n";
	
	if(alerta != "")
	{
		alert(alerta);
	}
	else
	{
		var url = RutaInfo + "IngresoUsuario/";
		//alert(url);
		var Vars = "Email=" + usuario;
		Vars += "&Password=" + password;
		loadAjax(url, "POST", Vars, "respuestaIngresar", true);
	}
}

function respuestaIngresar(ajax)
{
	var respuesta = ajax.responseText;
	if(respuesta.length > 2)
	{
		alert(respuesta);
	}
	else
	{
		IraHome();
	}
}

function AgregaraCotizacion(idproducto)
{
	var idcontacto = document.getElementById("idcontacto").value;
	if(idcontacto == "")
	{
		location.href= RutaInfo + "Registro/Paso1/";
	}
	else
	{
		AgregarProductoaCarro(idproducto);
	}
}

function AgregarProductoaCarro(id)
{
		var url = RutaInfo + "AgregarProductoaCarro/";
		var Vars = "IDProducto=" + id;
		loadAjax(url, "POST", Vars, "respuestaAgregarProductoaCarro", true);
}

function respuestaAgregarProductoaCarro(ajax)
{
	alert(ajax.responseText);
	location.reload();
}

function CambiarPassword()
{
	var passantigua = document.getElementById("pass_antigua").value;
	var passnueva = document.getElementById("pass_nueva").value;
	var alerta = "";
	if(passantigua == "")
	alerta += "Debe ingresar la Contraseña Antigua\n";
	if(passnueva == "")
	alerta += "Debe ingresar la Contraseña Nueva\n";
	
	if(alerta == "")
	{
		var url = RutaInfo + "Procesos/CambiarContrasena/";
		var Vars = "PassAntigua=" + passantigua;
		Vars += "&PassNueva=" + passnueva;
		loadAjax(url, "POST", Vars, "respuestaCambiarPassword", true);
	}
	else
	{
		alert(alerta);
	}
}

function respuestaCambiarPassword(ajax)
{
	alert(ajax.responseText);
	location.reload();
}

function ActualizarDatos()
{
	var giro = document.getElementById("giro").value;
	var direccion = document.getElementById("direccion").value;
	var ciudad = document.getElementById("ciudad").value;
	var comuna = document.getElementById("comuna_registro").value;
	var fono = document.getElementById("fono").value;
	var email = document.getElementById("email").value;
	var nombrecontacto = document.getElementById("nombrecontacto").value;
	var fonocontacto = document.getElementById("fonocontacto").value;
	var emailcontacto = document.getElementById("emailcontacto").value;
	var idempresa = document.getElementById("idempresa").value;
	var alerta = "";
	
	if(giro == "")
	alerta += "Debe ingresar el giro\n";
	if(direccion == "")
	alerta += "Debe ingresar la Direccion\n";
	if(ciudad == "")
	alerta += "Debe ingresar la Ciudad\n";
	if(comuna == "")
	alerta += "Debe ingresar la Comuna\n";
	if(fono == "")
	alerta += "Debe ingresar el Fono\n";
	if(email == "")
	alerta += "Debe ingresar el Email\n";
	if(nombrecontacto == "")
	alerta += "Debe ingresar el Nombre del Contacto\n";
	if(fonocontacto == "")
	alerta += "Debe ingresar el Fono del Contacto\n";
	if(emailcontacto == "")
	alerta += "Debe ingresar el Email del Contacto\n";
	
	if(alerta == "")
	{
		var url = RutaInfo + "Procesos/ActualizarDatos/";
		var Vars = "Giro=" + giro;
		Vars += "&Direccion=" + direccion;
		Vars += "&IDCiudad=" + ciudad;
		Vars += "&IDComuna=" + comuna;
		Vars += "&Fono=" + fono;
		Vars += "&Email=" + email;
		Vars += "&NombreContacto=" + nombrecontacto;
		Vars += "&FonoContacto=" + fonocontacto;
		Vars += "&EmailContacto=" + emailcontacto;
		Vars += "&IDEmpresa=" + idempresa;
		loadAjax(url, "POST", Vars, "respuestaActualizarDatos", true);
	}
	else
	{
		alert(alerta);
	}
}

function respuestaActualizarDatos(ajax)
{
	alert(ajax.responseText);
}

function EliminarProductodeCotizacion(idproducto)
{
	if(confirm("Realmente desea eliminar este producto del Carro de Cotizacion?"))
	{
		var idsolicituddecotizacion = document.getElementById("idsolicituddecotizacion").value;
		var url = RutaInfo + "Procesos/EliminarProductodeCotizacion/";
		var Vars = "IDProducto=" + idproducto;
		Vars += "&IDSolicitud=" + idsolicituddecotizacion;
		loadAjax(url, "POST", Vars, "respuestaEliminarProductodeCotizacion", true);
	}
}

function respuestaEliminarProductodeCotizacion(ajax)
{
	location.reload();
	//alert(ajax.responseText);
}

function EliminarCotizacion(idsolicitud)
{
	if(confirm("Realmente desea eliminar la Solicitud de Cotizacion?"))
	{
		var url = RutaInfo + "Procesos/EliminarCotizacion/";
		var Vars = "IDSolicitud=" + idsolicitud;
		loadAjax(url, "POST", Vars, "respuestaEliminarCotizacion", true);
	}
}

function respuestaEliminarCotizacion(ajax)
{
	location.reload();
	//alert(ajax.responseText);
}

function GrabarCotizacion(idsolicitud, verif)
{
	if(!verif)
	resp = "respuestaGrabarCotizacion2";
	else
	resp = "respuestaGrabarCotizacion";
	var elementos = document.getElementsByTagName("input");
	var ids = "";
	var valores = "";
	var comentarios = document.getElementById("comentarios").value;
   for(var i=0; i < elementos.length; i++)
   {
   	if(elementos[i].getAttribute("name") == "cantidad")
		{
			if(ids != "")
			{
				ids += ",;,";
				valores += ",;,";
			}
			ids += elementos[i].getAttribute("id");
			valores += document.getElementById(elementos[i].getAttribute("id")).value;
		}
	}
	var url = RutaInfo + "Procesos/GrabarCotizacion/";
	var Vars = "IDs=" + ids;
	Vars += "&Valores=" + valores;
	Vars += "&IDSolicitud=" + idsolicitud;
	Vars += "&Comentarios=" + comentarios;
	loadAjax(url, "POST", Vars, resp, true);
}

function respuestaGrabarCotizacion(ajax, verif)
{
	//location.reload();
	//alert(ajax.responseText);
	alert("Los cambios fueron actualizados.");
}

//function respuestaGrabarCotizacion2()
//{
//
//}

function CerrarCotizacion(idsolicitud)
{
	if(confirm("Realmente desea cerrar la cotizacion?. Esta será enviada a nuestra area de ventas y no podrá ser modificada."))
	{
		GrabarCotizacion(idsolicitud, false);
		var url = RutaInfo + "Procesos/CerrarCotizacion/";
		var Vars = "IDSolicitud=" + idsolicitud;
		loadAjax(url, "POST", Vars, "respuestaCerrarCotizacion", true);
	}
}

function respuestaCerrarCotizacion(ajax)
{
	//alert(ajax.responseText);
	location.href="/UsuarioAutenticado/CotizacionesPendientes/";
}

function ObtenerFactura(folio)
{
        var url = RutaInfo + "Procesos/ObtenerFactura/";
        var Vars = "Folio=" + folio;
        Vars += "&TipoDTE=" + 33;
        Vars += "&C=False";
        loadAjax(url, "POST", Vars, "respuestaObtenerFactura", true);
}

function respuestaObtenerFactura(ajax)
{
        //alert(ajax.responseText);
        window.open(ajax.responseText);
}

function CambiarFoto(idfoto)
{
        var url = RutaInfo + "Procesos/ObtenerFoto/";
        var Vars = "IDFoto=" + idfoto;
        loadAjax(url, "POST", Vars, "respuestaCambiarFoto", true);
}

function respuestaCambiarFoto(ajax)
{
        var capa = document.getElementById("fotoproducto");
        capa.innerHTML = ajax.responseText;
}

