// JavaScript Document
//------------------------------------------------------------------
var AppDebug= false;

//------------------------------------------------------------------
// forms validators
//------------------------------------------------------------------

//menu Popups

function queryGuia(){

    var nguia = prompt("Digite el número de guia:");
    if (!nguia) {return;}

    if(!isNaN(nguia)){
    innerWindowWH('reportpage_guia.aspx?format=html&nguia=' + nguia, 'winQueryGuia', 'Guia ' + nguia, 800, 600);
    }else
    alert("NGUIA no valido.");
}

//procesa el comando del formulario cliente.
function cmdBuscarCLie() {
    //si presiono enter procesa.
    if (!checkEnter()) {
        return;
    }
    //validar comando
    var cmd= document.FormCmd.Comando.value;
    var msgdiv = document.getElementById("msgdiv");
    msgdiv.innerHTML = "Procesando...";

    if (cmd.substr(0,1)=="d" || cmd.substr(0,1)=="D") {//buscar por dir
        parent.parent.parent.openBrWindow('menu/inbound/clientesDir_Find.aspx','win_findDir','width=880,height=540,scrollbars=yes');
        return;
    }

    if (cmd.length<2) {
        msgdiv.innerHTML = "Escriba un comando";
        return;
    }
    if (!xmlhttpwitherrormsg("command_check.asp?cmd=" + escape(cmd),false)) {
        msgdiv.innerHTML = "Comando NO VALIDO.";
        return;
    }

    if (cmd=="nc" || cmd=="NC") {
        document.location.href="inbound_clie.asp?cmd=nc";    //new client
        return;
    }

    //envia el comando para determinar la cantidad de registros afectados. >0 codigo del clie, -1 mas de uno.
    var result= xmlhttpreturnresponse("../../net/AjaxApi.aspx?cmd=cmdSeekClientCount&command="+escape(cmd),false);
    //si hay mas de un registro pagina resultados.
    //alert(result);
    if (result=="0") { //no regs.
        msgdiv.innerHTML = "NO SE ENCUENTRA: " + escape(cmd);
        return;
    } else if (result=="-1") { //varios regs.
        document.location.href="inbound_seekclient.asp?Comando=" +  escape(cmd);
        return;
    } else if (result=="-99") {
        msgdiv.innerHTML = "CODIGO DE CLIENTE NO NUMERICO.";
        return;
    } else if (isNaN(result)) {//un solo reg., recarga pagina.
        alert("Respuesta Inesperada: " + result.substr(0, 500));
    } else {
        document.location.href="inbound_clie.asp?Comando=Cliente+Seleccionado&setcodclie=" + result;
        return;
    }
}

function validarClie(codcliente) {
    var smode= document.FormData.mode.value;
    var nombres= document.FormData.Nombre.value;
    var apellidos= document.FormData.Apellido.value;
    var codzona= document.FormData.CodZona.value;
    var direccion= document.FormData.FullDir.value;
    var telefono= document.FormData.Telefono.value;
    var celular= document.FormData.celular.value;
    var identificacion= document.FormData.Identificacion.value;

    //obligatorios
    if (!nombres) {
        alert("Campo nombres Obligatorio.");
        return false;
    }
    if (!apellidos) {
        alert("Campo apellidos Obligatorio.");
        return false;
    }
    if (!direccion) {
        alert("Campo direccion Obligatorio.");
        return false;
    }
    if (!codzona) {
        alert("Campo codzona Obligatorio.");
        return false;
    }
    if (!telefono && !celular && !identificacion ) {
        alert("Campo Telefono o Celular o Identificacion Obligatorio.");
        return false;
    }
    if (isNaN(telefono)) {
        alert("Campo Telefono NO numérico.");
        return false;
    }
    if (isNaN(celular)) {
        alert("Campo Celular NO numérico.");
        return false;
    }
    if (isNaN(identificacion)) {
        alert("Campo Identificacion NO numérico.");
        return false;
    }


    var xmlresul="null";
    //combinacion (telefono o celular) y direccion ya existen con otro cliente?
    if (!xmlhttpwitherrormsg("../../net/AjaxApi.aspx?cmd=validarClieInbound&o="+smode+"&c="+codcliente+"&t="+escape(telefono)+"&ce="+escape(celular)+"&d="+escape(direccion),false)) {
        alert("El (teléfono o celular) y dirección ya existen con otro cliente.");
        return false;
    }

    //insert
    if (smode=='i') {
        //si solo existe el tel, celular o la dir genera alerta
        var result= xmlhttpreturnresponse("../../net/AjaxApi.aspx?cmd=validarClieInboundInsert&o="+smode+"&t="+escape(telefono)+"&ce="+escape(celular)+"&d="+escape(direccion),false);
        if (result!="") {
            if (!confirm("SUCESO AUDITADO PARA EVITAR DUPLICACION CLIENTES:\n" + result + "\n\n ¿ DESEA CONTINUAR ?")) {
                return false;
            }
        }
    }
}

function setFindDir() {
    var p1= document.form1.P1.options[document.form1.P1.selectedIndex].value;
    var p2= trim(document.form1.P2.value);
    var p3= document.form1.P3.options[document.form1.P3.selectedIndex].value;
    var p4= trim(document.form1.P4.value);
    var p5= document.form1.P5.options[document.form1.P5.selectedIndex].value;
    var p6= trim(document.form1.P6.value);
    var p7= trim(document.form1.P7.value);
    var p8= document.form1.P8.options[document.form1.P8.selectedIndex].value;
    var p9= trim(document.form1.P9.value);
    var p10= document.form1.P10.options[document.form1.P10.selectedIndex].value;
    var p11= document.form1.P11.options[document.form1.P11.selectedIndex].value;
    var p12= trim(document.form1.P12.value);
    var p13= document.form1.P13.options[document.form1.P13.selectedIndex].value;
    var p14= trim(document.form1.P14.value);
    var p15= trim(document.form1.P15.value);

//validar solo letras o numeros:
    var result;
    if (isNaN(p6)) {
        document.form1.P6.value="";
        p6="";
    }
    if (isNaN(p9)) {
        document.form1.P9.value="";
        p9="";
    }
    document.form1.P4.value= p4.replace(/[^\D]/g, "");
    document.form1.P7.value= p7.replace(/[^\D]/g, "");

    if (p9) {
        result= p1 + p2 + p3 + p4 + p5 + " # " + p6 + p7 + p8 +  " - " + p9 + p10 + p11 + p12 + p13 + p14;    // si hay nomenclatura, agrega el #
    } else {
        result= p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 +  " " + p9 + p10 + p11 + p12 + p13 + p14;
    }

    if (p15) {
        result+= ", " + p15;
    }

    document.form1.fulldir.value= result.replace(/\s+/g," "); //quita dobles espacios

}

function findDirSetClie(codclie) {
    parent.mainIframe.MainFrame.TopFrame.document.location.href="inbound_clie.asp?Comando=Cliente+Seleccionado&setcodclie=" + codclie
            top.Windows.close(top.Windows.focusedWindow.getId());
}

function showEditDir() {
    var dir= document.FormData.FullDir.value;
    parent.parent.parent.openBrWindow('menu/inbound/clientesDir_Edit.aspx?dir='+escape(dir),'win_EditDir','width=880,height=200,scrollbars=yes');
    return;
}

function setFieldClieDir() {
    parent.mainIframe.MainFrame.TopFrame.document.FormData.FullDir.value= document.form1.fulldir.value;
    top.Windows.close(top.Windows.focusedWindow.getId());
}

//------------------------------------------------------------------
// Utility Functions
//------------------------------------------------------------------

function checkEnter(e) { //e is event object passed from function invocation
    var characterCode;
    if (e && e.which) { //if which property of event object is supported (NN4)
        e = e;
        characterCode = e.which; //character code is contained in NN4's which property
    } else {
        e = event;
        characterCode = e.keyCode; //character code is contained in IE's keyCode property
    }

    if (characterCode == 13) {
        return true;
    } else {
        return false;
    }
}

//-- string functions
function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
    return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
    return stringToTrim.replace(/\s+$/,"");
}
//---

//-- cookies functions
function setCookie(c_name,value,expiredays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name) {
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) {
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return "";
}
//---

function setUserPrefStyle(estilo) {
    if (xmlhttpwitherrormsg("../AjaxApi.aspx?cmd=setUserPrefStyle&estilo=" + (estilo), false)) {
        alert('Selección guardada. Servirá mientras no elimine las cookies de su ordenador.');
    } else {
        alert('Atención:\nSu selección No pudo ser guardada!.');
    }
}

//------------------------------------------------------------------
// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
    if (!radioObj)
        return "";
    var radioLength = radioObj.length;
    if (radioLength == undefined)
        if (radioObj.checked)
            return radioObj.value;
        else
            return "";
    for (var i = 0; i < radioLength; i++) {
        if (radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
    if (!radioObj)
        return;
    var radioLength = radioObj.length;
    if (radioLength == undefined) {
        radioObj.checked = (radioObj.value == newValue.toString());
        return;
    }
    for (var i = 0; i < radioLength; i++) {
        radioObj[i].checked = false;
        if (radioObj[i].value == newValue.toString()) {
            radioObj[i].checked = true;
        }
    }
}

function validarnavegador() {
//If script is executed width , then document.body is not available yet.

    if (window.XMLHttpRequest) {
        if (document.all) {
            //document.write(”IE 7?);
            //IE7
        } else {
            //document.write(”Mozilla”);
            //mozilla, safari, opera 9â€¦etc
        }
    } else {
        //document.write(”IE 6?);
        // IE6, older browsers
        alert("Usted esta usando un navegador NO soportado por esta aplicación.\nPor favor revise los requisitos mínimos.\nNingun error en el sistema tendrá soporte o garantía de funcionamiento.");
    }
}

function num2money(n_value) {
	// validate input
	if (isNaN(Number(n_value)))
	return 'ERROR';
	
	// save the sign
	var b_negative = Boolean(n_value < 0);
	n_value = Math.abs(n_value);
	
	// round to 1/100 precision, add ending zeroes if needed
	var s_result = String(Math.round(n_value * 1e2) % 1e2 + '00').substring(0, 2);
	
	// separate all orders
	var b_first = true;
	var s_subresult;
	while (n_value >= 1) {
	s_subresult = (n_value >= 1e3 ? '00' : '') + Math.floor(n_value % 1e3);
	s_result = s_subresult.slice(-3) + (b_first ? '.' : ',') + s_result;
	b_first = false;
	n_value = n_value / 1e3;
	}
	// add at least one integer digit
	if (b_first)
		s_result = '0.' + s_result;
	
	// apply formatting and return
	return b_negative	? '($' + s_result + ')'	: '$' + s_result;
}


//------------------------------------------------------------------
// validators
//------------------------------------------------------------------
function valActivDates(date1,hora1,min1,date2,hora2,min2) {
    if (xmlhttpexecute("../AjaxApi.aspx?cmd=validateDates&fecha1="+date1+"&hora1=" + hora1 +"&min1=" + min1 + "&fecha2=" + date2 + "&hora2=" + hora2 +"&min2=" + min2 ,false)) {
        return true;
    } else {
        return false;
    }
}

//------------------------------------------------------------------
// AJAX DB table functions
//------------------------------------------------------------------
function tablasCheckRecordExist(db,stable,sfield,svalue,svaluetype) {
    if (xmlhttpwitherrormsg("../AjaxApi.aspx?cmd=tablasCheckRecordExist&db="+db+"&table=" + stable +"&field=" + sfield + "&valuetype=" + svaluetype + "&value="+escape(svalue) ,false)) {
        return true;
    } else {
        return false;
    }
}

function tablasGetStringRecord(db,stable,sfield,svalue,svaluetype,sfieldreturn) {
    var result= xmlhttpreturnresponse("/net/AjaxApi.aspx?cmd=tablasGetStringRecord&db="+db+"&table=" + stable +"&field=" + sfield + "&valuetype=" + svaluetype + "&value="+escape(svalue) + "&fieldreturn="+sfieldreturn ,false);
    if (AppDebug) {
        alert(result);
    }
    return result;
}

function tablasDeleteRecord(db,stable,sfield,svalue,svaluetype) {

    var answer = confirm("¿Esta seguro de ELIMINAR este registro? :" + svalue );
    if (answer) {
        if (xmlhttpwitherrormsg("../AjaxApi.aspx?cmd=tablasDeleteRecord&db="+db+"&table=" + stable +"&field=" + sfield + "&valuetype=" + svaluetype + "&value="+escape(svalue) ,false)) {
            alert('El registro ha sido eliminado.');
            return true;
        } else {
            alert('Atención:\nEl registro NO pudo ser eliminado, NO posee permisos suficientes.');
            return false;
        }
    }

}

function tablasUpdateRecord(db,stable,sfield,svalue,svaluetype,sfupdate,sfupdateval,sfupdatetype) {
    if (xmlhttpwitherrormsg("../AjaxApi.aspx?cmd=tablasUpdateRecord&db="+db+"&table=" + stable +"&field=" + sfield + "&valuetype=" + svaluetype + "&value="+escape(svalue) +"&fieldupd=" + sfupdate + "&valuetypeupd=" + sfupdatetype + "&valueupd="+escape(sfupdateval) ,false)) {
        return true;
    } else {
        return false;
    }

}

function openpopupselectid(openerfield, db, table, campoid, campodes, campoidtype) {
    openBrWindowPopup("popup_select_id.aspx?db=" + db + "&table=" + table + "&campoid=" + campoid + "&campodes=" + campodes + "&campoidtype=" + campoidtype + "&destfield=" + openerfield, 'win_popupselectid', 'width=480,height=400,scrollbars=yes');
}

function openpopupselectidfiltered(openerfield, db, table, campoid, campodes, campoidtype, campofiltro, campofiltroval, campofiltrovaltype) {
    openBrWindowPopup("popup_select_id.aspx?db=" + db + "&table=" + table + "&campoid=" + campoid + "&campodes=" + campodes + "&campoidtype=" + campoidtype + "&destfield=" + openerfield + "&campofiltro=" + campofiltro + "&campofiltroval=" + campofiltroval + "&campofiltrovaltype=" + campofiltrovaltype, 'win_popupselectid', 'width=480,height=400,scrollbars=yes');
}

//------------------------------------------------------------------
// pop and inner windows
//------------------------------------------------------------------
function openBrWindow(theURL,winName,features) { //v2.0
    //newWindow= window.open(theURL,winName,features+',toolbar=yes,resizable=yes');
    //newWindow.focus();
    innerWindow(theURL,winName,features);

}
function openBrWindowPopup(theURL,winName,features) { //v2.0
    newWindow= window.open(theURL,winName,features+',toolbar=yes,resizable=yes');
    newWindow.focus();

}
function openPopupWindowMax( aURL, aWinName ) {
    var wOpen;
    var sOptions;

    sOptions = 'status=yes,menubar=yes,scrollbars=yes,resizable=yes,toolbar=yes';
    sOptions = sOptions + ',width=' + (screen.availWidth - 10).toString();
    sOptions = sOptions + ',height=' + (screen.availHeight - 122).toString();
    sOptions = sOptions + ',screenX=0,screenY=0,left=0,top=0';

    wOpen = window.open( aURL, aWinName, sOptions );
    wOpen.location = aURL;
    wOpen.focus();
    wOpen.moveTo( 0, 0 );
    wOpen.resizeTo( screen.availWidth, screen.availHeight );
    //return wOpen; //solamente por si se necesita retornar para administrar algo via variables.
}
function innerWindow(theURL, winName, theTitle, features) {

    var win = new Window({ className: "alphacube", title: theTitle, top: 70, left: 100, width: 650, height: 450, minimizable: false, url: theURL, showEffectOptions: {
duration:
        1.5
    }});
    win.setDestroyOnClose();
    win.showCenter(true);
    //win.show();
}
function innerWindowWH(theURL, winName, theTitle, iwidth, iheight) {

    var win = new Window({ className: "alphacube", title: theTitle, top: 50, left: 50, width: iwidth, height: iheight, minimizable: false, url: theURL, showEffectOptions: {
duration:
        1.5
    }});
    win.setDestroyOnClose();
    win.showCenter(true);
    //win.show();
}

// dialogo con cuenta regresiva
var timeoutDialog;
function openInfoTimeoutDialog(stext, iseconds) {
Dialog.info(stext, {className: "alert_lite", width:250, height:200, showProgress: false});
    timeoutDialog=iseconds;
    setTimeout("infoTimeoutDialog('"+stext+"')", 1000);
}

function infoTimeoutDialog(stext) {
    timeoutDialog--;
    if (timeoutDialog >0) {
        Dialog.setInfoMessage(stext + "<br> " + timeoutDialog + " ...");
        setTimeout("infoTimeoutDialog('"+stext+"')", 1000);
    } else
        Dialog.closeInfo()
    }

//dialogo con contador de carga
var timeProcessDialog=0;
function openInfoProcesingDialog(stext, iseconds) {
Dialog.info(stext, {className: "alert_lite", width:250, height:200, showProgress: true});
    setInterval("infoProcessDialog('"+stext+ "')", 1000);
}
function infoProcessDialog(stext) {
    timeProcessDialog++;
    Dialog.setInfoMessage(stext + "<br> Tiempo transcurrido: " + timeProcessDialog + " seg.");
}


//------------------------------------------------------------------
//------------------------------------------------------------------
// AJAX

function xmlhttpAsynchronous(url, retornaxml, customFunction) {
//ASynchronous AJAX
    var http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (retornaxml) {
            http_request.overrideMimeType('text/xml');
            // Ver nota sobre esta linea al final
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        alert('Error: No es posible crear una instancia XMLHTTP.\nSoluciones:\n1.Habilite Javascript en su Navegador.\n2.Actualice su navegador a una versión más reciente.');
        return false;
    }
    http_request.onreadystatechange = function(){xmlhttpAsynchronousUpdateState(http_request, customFunction)};
    http_request.open('GET', url, true);
    http_request.send(null);

}

function xmlhttpAsynchronousUpdateState(request, customFunction){
     if (request.readyState == 4){
       if (request.status == 200)
         eval(customFunction ); //alert(request.responseText);
       else if (request.status == 404)
         alert("Error AJAX, la URL solicitada No Existe!.");
       else{
	     var msg = request.responseText;
         alert("ERROR EN LA CONSULTA (AJAX).\n Estado: " + request.status + "\n" + msg.substr(0, 500) +"...");
		}
	 }
}


function xmlhttpexecute(url,retornaxml) {
//Synchronous AJAX
    var http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (retornaxml) {
            http_request.overrideMimeType('text/xml');
            // Ver nota sobre esta linea al final
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        alert('Error: No es posible crear una instancia XMLHTTP.\nSoluciones:\n1.Habilite Javascript en su Navegador.\n2.Actualice su navegador a una versión más reciente.');
        return false;
    }
    //http_request.onreadystatechange = processvdContents;
    http_request.open('GET', url, false);
    http_request.send(null);

    if (http_request.responseText=="true") {
        return true;
    } else {
        return false;
    }
}

function xmlhttpwitherrormsgDebug(url,retornaxml,errordocument) {
//Synchronous AJAX
    var http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (retornaxml) {
            http_request.overrideMimeType('text/xml');
            // Ver nota sobre esta linea al final
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        alert('Error: No es posible crear una instancia XMLHTTP.\nSoluciones:\n1.Habilite Javascript en su Navegador.\n2.Actualice su navegador a una versión más reciente.');
        return false;
    }
    //http_request.onreadystatechange = processvdContents;
    http_request.open('GET', url, false);
    http_request.send(null);

    if (http_request.responseText=="true") {
        return true;
    } else {
        if (AppDebug) {
            errordocument.writeln(http_request.responseText);
        } else {
            alert(http_request.responseText);
        }
        return false;
    }
}

function xmlhttpwitherrormsg(url,retornaxml) {
//Synchronous AJAX
    var http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (retornaxml) {
            http_request.overrideMimeType('text/xml');
            // Ver nota sobre esta linea al final
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        alert('Error: No es posible crear una instancia XMLHTTP.\nSoluciones:\n1.Habilite Javascript en su Navegador.\n2.Actualice su navegador a una versión más reciente.');
        return false;
    }
    //http_request.onreadystatechange = processvdContents;
    http_request.open('GET', url, false);
    http_request.send(null);

    if (http_request.responseText=="true") {
        return true;
    } else if (http_request.responseText=="false") {
        return false;
    } else {
        var msg = http_request.responseText;
        alert("ERROR EN LA CONSULTA (AJAX).\n" + url + "\n" + msg.substr(0, 500) +"...");
        return false;
    }
}

function xmlhttpreturnresponse(url,retornaxml) {
//Synchronous AJAX
    var http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (retornaxml) {
            http_request.overrideMimeType('text/xml');
            // Ver nota sobre esta linea al final
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!http_request) {
        alert('Error: No es posible crear una instancia XMLHTTP.\nSoluciones:\n1.Habilite Javascript en su Navegador.\n2.Actualice su navegador a una versión más reciente.');
        return "ERROR EN LA CONSULTA AJAX.";
    } else {
        //http_request.onreadystatechange = processvdContents;
        http_request.open('GET', url, false);
        http_request.send(null);

        return http_request.responseText;
    }
}
//------------------------------------- SPECIFIC AJAX: ------------------------------------------------


