﻿// Archivo JScript

var tiempo= 1000;

//mensajes
function msgSave() {
    document.getElementById("lblGuardo").style.visibility = "hidden";
}

function errorPages() {
    images(11);
    cadPage="";
    if (typeof this.req != "undefined" ) {
        alert(this.req.responseText);
    }
}

function SetCombo (nombre, valor) {
    var mm = elemento(nombre).options;
    var j=0;
    if (mm.length>0) {
         elemento(nombre).selectedIndex=0;
    }
    for (var i=0; i<mm.length; i++) {
        //j=elemento(nombre).options[elemento(nombre).selectedIndex].value;
        j=elemento(nombre).options[i].value;
        if (j==valor) {
            elemento(nombre).selectedIndex=i;
            i=mm.length;
        }
//        j=aElemPage[i].nom.trim();
//        q=aElemPage[i].id.trim();
//        m[i] = new Option (j,q,'','');
    }
}


function ddldes(elem, estado) {
    elemento(elem).disabled=!estado;
}

function txtdes(elem, estado) {
    elemento(elem).readOnly=!estado;
}

//inicializar un combo.
function ddlini(elem) {
	var m = elemento(elem).options;
    m.length = null;
	m[0] = new Option ('[Seleccione]','0','','');
}


function limpiarFormulario() {
    var tod = datForm;
    var s = "";
    var i=0;
    for (i=0; i<tod.length; i++) {
        s = tod[i].substring(0,3);
        if (s=="txt") {
            elemento(tod[i]).value="";
        } else if (s=="ddl") {
            elemento(tod[i]).selectedIndex=0;
        }
    }
}


//------------------------------------------------------
// ABREVIADO DE GETELEMENTBYID
//------------------------------------------------------

function elemento(elem) {
    return document.getElementById(elem);
}

function ver(elem,tipo) {
    var op = elemento(elem).style.visibility;
    if (tipo==true) {
        elemento(elem).style.visibility="visible";
    } else {
        elemento(elem).style.visibility="hidden";
    }
}

function habil(elem,tipo) {
    var op = elemento(elem).enabled;
    if (tipo==true) {
        elemento(elem).enabled=true;
    } else {
        elemento(elem).enabled=false;
    }
}

function desHabil(elem,tipo) {
    var op = elemento(elem).enabled;
    if (tipo==true) {
        elemento(elem).disabled=true;
    } else {
        elemento(elem).disabled=false;
    }
}

function ddlValor(elem) {
    return elemento(elem).options[elemento(elem).selectedIndex].value; 
}
function ddlTexto(elem) {
    return elemento(elem).options[elemento(elem).selectedIndex].text.trim(); 
}
//elemento("txtdesemp").="disabled";

//APROBADO V 3.5 DANIEL G.
//function dep(opwd) {
//    var ent ="";
//    if (opwd==1) { //cargue departamentos
//        ent="ddlpaiemp";
//        mun="ddldepemp";
//        var m = elemento("ddlmunemp").options;
//        m.length = null;
//        m[0] = new Option ("","",'','');
//    } else if (opwd==2) {
//        ent="ddldepemp";
//        mun="ddlmunemp";
//    } else {
//        return ;
//    }
//    var d=elemento(ent).options;
//    var m=elemento(mun).options;
//    var indice = elemento(ent).selectedIndex;
//    var escogido = d[indice].text.trim();
//    
//    var d22=elemento("ddlpaiemp").options;
//    var indice22 = elemento("ddlpaiemp").selectedIndex;
//    var escogido22 = d22[indice22].text.trim();

//    if (escogido22=="Colombia") {
//        if (opwd==1) {
//            ddldes("ddldepemp",true);
//            ddldes("ddlmunemp",false);
//            elemento("lbldepempO").innerHTML="*";
//            elemento("lblmunempO").innerHTML="*";
//        } else {
//            //alert("no");
//            ddldes("ddldepemp",true);
//            ddldes("ddlmunemp",true);
//            elemento("lbldepempO").innerHTML="*";
//            elemento("lblmunempO").innerHTML="*";
//        }
//    } else {
//        ddldes("ddldepemp",false);
//        ddldes("ddlmunemp",false);
//        elemento("lbldepempO").innerHTML=" ";
//        elemento("lblmunempO").innerHTML=" ";
//    }
//    m.length = null;
//    if (d[0].selected == true) {
//        m[0] = new Option("[Seleccione]","","","");
//        return;
//    }
//    paramPage = "dep48=si&opval="+opwd+"&opdep="+escogido;
//    //images(11);
//    //alert(paramPage);
//    var url = urlDef + "models/register/register_ajax.aspx";
//    var cargador = new net.ContentLoader(url, loadmun,errorPages ,'POST', paramPage, 'application/x-www-form-urlencoded'); 
//    
//}

//------------------------------------------------------
// VALIDACIONES DE LOS ELEMENTOS
//------------------------------------------------------

   
function valide(idError, elem, op, lista, listaError) {
    //1 esNumerico
    //2 esAlfaNumerico
    //3 listas
    //4 email
    //5 numero sin espacios
    //6 numero sin espacios CELULAR
    
    
    //51 obligatorio-num
    //52 obligatorio-AlphaNum
    //54 obligatorio-mail
    //55 obligatorio-nit sin espacios
    //56 obligatorio-nit sin espacios CELULAR
    //57 obligatorio modelo carro 4 digitos numerico y fecha valida
    //58 obligatorio-numero de 2 digitos
    
    if (op != 3) {
        elem = elem.trim();
    }

        if (op==1) {
            if (!(esNum(elem))) {
                msg = " Caracter no valido: [ " + err +" ]";
            } else {
                msg = " ";
            }  
        } else if (op==2) {   
            if (!(IsAlphaNum(elem.trim()) )) {
                msg = " Caracter no valido: [ " + err +" ]";
            } else {
                msg = " ";
            }
        } else if (op==3) {
            if (elem.options[0].selected) {
                msg =  "* Campo obligatorio";
            } else {
                msg =  "*";
            }
            
        } else if (op==4) {
            
            if (!(esMail(elem))) {
                msg = " Mail invalido.";
            } else {
                msg = " ";
            }
        } else if (op==5) {
            
            if (!(esNumNit(elem))) {
                msg = " Caracter no valido: [ " + err +" ]";
            } else {
                msg = " ";
            }
        } else if (op==6) {
            
            if (!(esNumCel(elem))) {
                msg = " Caracter no valido: [ " + err +" ]";
            } else {
                var cel = esCelular(elem);
                if (cel==1) {
                    msg = " Numero incorrecto";
                } else if (cel==2) {
                    msg = " El celular debe empezar por 3";
                } else {
                    msg = " ";
                }
            }
        } else if (op==51) {
            if (!(esNum(elem))) {
                msg = "* Caracter no valido: [ " + err +" ]";
            } else {
                msg = "*";
            }
        } else if (op==52) {        
            if (!(IsAlphaNum(elem.trim()) )) {
                msg =  "* Caracter no valido: [ " + err +" ]";
            } else {
                msg = "*";
            }
        } else if (op==54) {
            if (!(esMail(elem)))
                msg = "* Mail invalido !!!";
            else
                msg = "*";
        } else if (op==55) {
            if (!(esNumNit(elem))) {
                msg = "* Caracter no valido: [ " + err +" ]";
            } else {
                msg = "*";
            }
        } else if (op==57) {
            if (!(esModeloCarro(elem))) {
                msg = "* Año invalido";
            } else {
                msg = "*";
            }
        } else if (op==58) {
            if (!(esNum(elem))) {
                msg = "* Caracter no valido: [ " + err +" ]";
            } else {
                if (!(elem.length<=2)) {
                    msg = "* Maximo 2 digitos";
                } else {
                    msg = "*";
                }
            }
        }
        document.getElementById(idError).innerHTML = msg;
        images(12);

        setTimeout(errorPages,tiempo);

    } //end valide


//------------------------------------------------------
// VALIDAR/GUARDAR UN FORMULARIO
//------------------------------------------------------
//tod concatena campos
function guardar(form) {
    //verificar que no hay errores.
    var lblError = true;
    var tod = sol;
    var s = "";
    var i=0;
    
    //valide si hay comentarios de errores.
    for (i=0; i<tod.length && lblError; i++) {
        s = "lbl" + tod[i].substring(3,(tod[i].length)) + "O";
        lblError = !(document.getElementById(s).innerHTML.length>=2); 
    }
  
    if (lblError) {
        form.submit();
        return 2;
    } else {
        alert ("El formulario contiene errores o campos incompletos.");
        return 1;
    }
}

//------------------------------------------------------
// CARGADOR DE IMAGENES
//------------------------------------------------------

function images(op) {
    if (op==11) {
        //document.getElementById("iBull").src="../images/space.gif";
    } else if (op==12) {
        //document.getElementById("iBull").src="../images/photo_loading.gif";
    } else if (op==33) {
        //document.getElementById("iBull").src="../images/photo_loading.gif";
    } else if (op==34) {
        //document.getElementById("iBull").src="../images/space.gif";
    }
}



//------------------------------------------------------
//CLASE EXTEND STRING
//------------------------------------------------------

String.prototype.rtrim = function() {
return this.replace(/\s*$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s*/g,"");
}
String.prototype.trim = function() {
return this.ltrim().rtrim();
}

//elimina cualquier etiqueta HTML
String.prototype.stripTags = function() {
return this.replace(/<\/?[^>]+>/gi, '');
}

//------------------------------------------------------
//ELIMINAR NODOS HIJOS DE UN DIV
//------------------------------------------------------

function DelChilds(divi) {
    var oldChild = null;
    var valor = divi.hasChildNodes();
    while (valor) {
        oldChild = divi.firstChild;
        divi.removeChild(oldChild);
        valor = divi.hasChildNodes();
    }
}

//mailAntiSpam
function mailAntiSpam()
{
	var usuario = "danielgaravitog"
	var dominio = "yahoo.com.ar"
	document.write("<a href=\"mailto:" + usuario + "@" + dominio + "\"> Ing. Daniel Garavito </a>")
}

//alfanumerico.
//pos: true|false; err: indica caracter no valido
function IsAlphaNum( str ) {
	//if (str+"" == "undefined" || str+"" == "null" || str+"" == "") { return false; }	
	if (str+"" == "undefined" || str+"" == "null") { return false; }	
	var isValid = true; str += "";	
	//alert("Si");
   	for (i = 0; i < str.length; i++) {
	//alert(escape(str.charAt(i)));
	// Alphanumeric must be between "0"-"9", "A"-"Z","a"-"z" OR ". , &"
      	if (!(((str.charAt(i) >= "0") && (str.charAt(i) <= "9")) || (str.charAt(i) == "(") || (str.charAt(i) == ")") || (str.charAt(i) == "#") || (str.charAt(i) == "-") || (str.charAt(i) == "_") ||  (str.charAt(i) == " ") ||
      			((str.charAt(i) >= "a") && (str.charAt(i) <= "z")) ||
      			((str.charAt(i) >= "A") && (str.charAt(i) <= "Z")) || ((str.charAt(i) == " ")) || ((str.charAt(i) == ",")) ||
			((escape(str.charAt(i)) == "%F1")) || ((escape(str.charAt(i)) == "%D1")) ||
			((escape(str.charAt(i)) == "%E9")) || ((escape(str.charAt(i)) == "%E1")) ||
			((escape(str.charAt(i)) == "%ED")) || ((escape(str.charAt(i)) == "%F3")) || ((escape(str.charAt(i)) == "%0D")) || ((escape(str.charAt(i)) == "%0A")) || ((escape(str.charAt(i)) == "%24")) ||
			((escape(str.charAt(i)) == "%C1")) || ((escape(str.charAt(i)) == "%C9")) ||
			((escape(str.charAt(i)) == "%CD")) || ((escape(str.charAt(i)) == "%D3")) ||
			((escape(str.charAt(i)) == "%DA")) || ((escape(str.charAt(i)) == "%3A")) ||
			((escape(str.charAt(i)) == "%FA")) || ((str.charAt(i) == "."))))
			{isValid = false; err=str.charAt(i); break; }	
			
			
   	} // END for

   	return isValid;
}// end IsAlphaNum


//esNumeroEntero
//pos: true|false; err: error
function esNum (numstr) {
    err="";
	if (numstr+"" == "undefined" || numstr+"" == "null" || numstr+"" == "") {return false;}
	numstr += "";
	var cadena1;
	for (i = 0; i < numstr.length; i++) {
	    if (numstr.charAt(i) == " ") {
	    } else if (!((numstr.charAt(i) >= "0") && (numstr.charAt(i) <= "9"))) {
		    err = numstr.charAt(i);
		    return false;
		}
	} // endFor
	return true;
} // END esNum

//pos: true|false; err: error
function esNumCel (numstr) {
    err="";
	if (numstr+"" == "undefined" || numstr+"" == "null") {return false;}
	numstr += "";
	var cadena1;
	for (i = 0; i < numstr.length; i++) {
	    if (numstr.charAt(i) == " ") {
	    } else if (!((numstr.charAt(i) >= "0") && (numstr.charAt(i) <= "9"))) {
		    err = numstr.charAt(i);
		    return false;
		}
	} // endFor
	return true;
} // END esNum

//esNumeroEnteroNIT
//pos: true|false; err: error
function esNumNit (numstr) {
    err="";
	if (numstr+"" == "undefined" || numstr+"" == "null" || numstr+"" == "") {return false;}
	numstr += "";
	var cadena1;
	for (i = 0; i < numstr.length; i++) {
	    if (numstr.charAt(i) == " ") {
	         //err = numstr.charAt(i);
	         err = "espacio";
		    return false;
	    } else if (!((numstr.charAt(i) >= "0") && (numstr.charAt(i) <= "9"))) {
		    err = numstr.charAt(i);
		    return false;
		}
	} // endFor
	return true;
} // END esNum

//valida si tiene los 4 digitos
//si es un modelo de carro valido
function esModeloCarro (numstr) {
    err="";
	if (numstr+"" == "undefined" || numstr+"" == "null" || numstr+"" == "") {return false;}
	numstr += "";
	var cadena1;
	if (!(esNum(numstr))) {
	    return false;
	}
	if (!(numstr.length==4)) {
	    return false;
	}
	var f = new Date();
    f = f.getFullYear();
    //validar el anio.
    if ((numstr>f) || (numstr<=1900)) { //anio default
        return false;
    }
    return true;
} // END esNum

function esCelular (numstr) {
    err="";
	//if (numstr+"" == "undefined" || numstr+"" == "null" || numstr+"" == "") {return false;}
	numstr += "";
	var cadena1;
    if (numstr.length==0) {
		    return 0;
	}
	if (!(numstr.length==10)) {
	    return 1; //tamano no sirve
	}
	if (!(numstr.charAt(0) == "3")) {
	    return 2; //no empieza por 3
	}
	return 0;
} // END esCelular

//esMail
function esMail(elem) {
	var filter=/^[A-Za-z][A-Za-z0-9_.\-]*@[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-.]+[A-za-z]$/;
	if (elem.length == 0 ) return true;
	if (filter.test(elem))
	    return true;
    return false;
}



//es cadena vacia
function esVacio(q) {
    if (q.trim().length != 0)
        return false;
    return true;
}

//limpiar casilla nit de letras.
function clearNit(elem) {
    if (elem.value.indexOf("puntos") != -1) {
        elem.value="";
    }
}


//Es Anio bisiesto
function anioBisiesto(anio) {
    if (((anio % 4 == 0) && (anio % 100 != 0)) || (anio % 400 == 0)) {
        return true;
    } else {
        return false;
    }
}


//Es Fecha valida
function esFecha(fecha){

    var dia=fecha.split("/")[0];
    var mes=fecha.split("/")[1];
    var ani=fecha.split("/")[2];
    
    if( (isNaN(dia)==true) || (isNaN(mes)==true) || (isNaN(ani)==true) ) {
        return ("La fecha introducida debe estar formada sólo por números");
    }

    var febrero=28;
    if(anioBisiesto(ani)) {
        febrero=29;
    }

    if ((mes<1) || (mes>12)) {
        return ("El mes introducido no es valido. Por favor, introduzca un mes correcto");
    }

    //verificando febrero
    if ((mes==2) && ((dia<1) || (dia>febrero))) {
        return ("El dia de Febrero no es valido. Por favor, introduzca un dia correcto");
    }

    // si el mes introducido es de 31 dias y el dia introducido es mayor de 31 > alertamos y detenemos ejecucion
    if (((mes==1) || (mes==3) || (mes==5) || (mes==7) || (mes==8) || (mes==10) || (mes==12)) && ((dia<1) || (dia>31))) {
        return ("El dia introducido no es valido. Por favor, introduzca un dia correcto");
    }

    // si el mes introducido es de 30 dias y el dia introducido es mayor de 301 > alertamos y detenemos ejecucion
    if (((mes==4) || (mes==6) || (mes==9) || (mes==11)) && ((dia<1) || (dia>30))) {
        return ("El dia introducido no es valido. Por favor, introduzca un dia correcto");
    }
    return "true";
} 

//FechaMayor Actual < F2
function compFechaActual(fecha1) {
    var f = new Date();
    f = f.getDate()+"/"+(f.getMonth()+1)+"/"+f.getFullYear();
    if (getTimestamp(fecha1) < getTimestamp(f)){
        return false;
    } else {
        return true;
    }
}

//FechaMayor F1 => F2
//yyy/mm/dd
function compFechas(fecha1, fecha2) {
    var f = new Date(fecha2);
    var f2 = new Date(fecha1);
    var tmp1=f.getDate()+"";
    var tmp2=f2.getDate()+"";
    f = f.getDate()+"/"+(f.getMonth()+1)+"/"+f.getFullYear();
    f2 = f2.getDate()+"/"+(f2.getMonth()+1)+"/"+f2.getFullYear();

    if (tmp1.length<=1) {
        f= "0"+f;
    }
    if (tmp2.length<=1) {
        f2= "0"+f2;
    }
//alert(tmp1.length+"----"+tmp2);
//alert(getTimestamp(f2) +"---"+ getTimestamp(f));
    if (getTimestamp(f2) <= getTimestamp(f)){
        return false;
    } else {
        return true;
    }
}

//compara una fecha con la fecha actual del sistema.
function fechaMayoraLaActual(fecha1) {

    var fechaActual = new Date();
    var timestamp2 = parseInt(fechaActual.getTime(),10);
    var timestamp = parseInt(fecha1.getTime(),10);
    
    return (timestamp>timestamp2);

//var fecha2 = new Date();
//alert(fecha1);
//    var f = new Date(fecha2);//10/6/92009
//    var f2 = new Date(fecha1);
//    alert(f2);
//    f = f.getDate()+"/"+(f.getMonth()+1)+"/"+f.getFullYear();
//    f2 = f2.getDate()+"/"+(f2.getMonth()+1)+"/"+f2.getFullYear();
//    alert(f+"..."+f2);
//    if (getTimestamp(f2) <= getTimestamp(f)){
//        return false;
//    } else {
//        return true;
//    }
}

//fechas iguales
function compFechasIguales(fecha1, fecha2) {
    var f = new Date(fecha2);
    var f2 = new Date(fecha1);
    f = f.getDate()+"/"+(f.getMonth()+1)+"/"+f.getFullYear();
    f2 = f2.getDate()+"/"+(f2.getMonth()+1)+"/"+f2.getFullYear();
    if (getTimestamp(f2) == getTimestamp(f)){
        return true;
    } else {
        return false;
    }
}
    



function getTimestamp(fecha_dd_mm_yyyy) {
    var dia_aux = parseInt(fecha_dd_mm_yyyy.substring(0, 2),10);
    var mes_aux = parseInt(fecha_dd_mm_yyyy.substring(3, 5),10);
    var ano_aux = parseInt(fecha_dd_mm_yyyy.substring(6, 10),10);
    var fecha = new Date();
    fecha.setFullYear(ano_aux);
    fecha.setMonth(mes_aux-1);
    fecha.setDate(dia_aux);
    fecha.setHours(0);
    fecha.setMinutes(0);
    fecha.setSeconds(0);
    fecha.setMilliseconds(0);
    var timestamp = parseInt(fecha.getTime(),10);
    return timestamp;
}

function pause(milisec){
    var d = new Date();
    var begin = d.getTime();
    begin = begin + milisec;
    while ((d.getTime() < begin )){
        // nothing...
        d = new Date(); 
    } 
}


function getAbsoluteDivs()   
{   
    var arr = new Array();   
    var all_divs = document.body.getElementsByTagName("DIV");   
    var j = 0;   
  
    for (i = 0; i < all_divs.length; i++)   
        if (all_divs.item(i).style.position=='absolute')   
        {   
            arr[j] = all_divs.item(i);   
            j++;   
        }   
  
    return arr;   
}   
  
function bringToFront(id)   
{   
    if (!document.getElementById ||   
        !document.getElementsByTagName)   
        return;   
  
    var obj = document.getElementById(id);   
    var divs = getAbsoluteDivs();   
    var max_index = 0;   
    var cur_index;   
  
    // Compute the maximal z-index of   
    // other absolute-positioned divs   
    for (i = 0; i < divs.length; i++)   
    {   
        var item = divs[i];   
        if (item == obj ||   
            item.style.zIndex == '')   
            continue;   
  
        cur_index = parseInt(item.style.zIndex);   
        if (max_index < cur_index)   
        {   
            max_index = cur_index;   
        }   
    }   
  
    obj.style.zIndex = max_index + 1;   
}   
  
function sendToBack(id)   
{   
    if (!document.getElementById ||   
        !document.getElementsByTagName)   
        return;   
  
    var obj = document.getElementById(id);   
    var divs = getAbsoluteDivs();   
    var min_index = 999999;   
    var cur_index;   
  
    if (divs.length < 2)   
        return;   
  
    // Compute the minimal z-index of   
    // other absolute-positioned divs   
    for (i = 0; i < divs.length; i++)   
    {   
        var item = divs[i];   
        if (item == obj)   
            continue;   
  
        if (item.style.zIndex == '')   
        {   
            min_index = 0;   
            break;   
        }   
  
        cur_index = parseInt(item.style.zIndex);   
        if (min_index > cur_index)   
        {   
            min_index = cur_index;   
        }   
  
    }   
  
    if (min_index > parseInt(obj.style.zIndex))   
    {   
        return;   
    }   
  
    obj.style.zIndex = 1;   
  
    if (min_index > 1)   
        return;   
  
    var add = min_index == 0 ? 2 : 1;   
  
    for (i = 0; i < divs.length; i++)   
    {   
        var item = divs[i];   
        if (item == obj)   
            continue;   
  
        item.style.zIndex += add;   
    }   
} 

function MM_openBrWindow(theURL,winName,features) { 
  window.open(theURL,winName,features);
}

//---

//var urlDef = ";
var urlDef = "http://" + location.host + "/Correspon_2010/";
urlDef = "http://" + location.host + "/portal/corr/";

