﻿function ValidateLoad(){

}

function disableSelection(target){
  
    if (typeof target.onselectstart!="undefined") //IE route
	    target.onselectstart=function(){return false}
    else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
	    target.style.MozUserSelect="none"
    else //All other route (ie: Opera)
	    target.onmousedown=function(){return false}
    target.style.cursor = "default"
}

    

// JScript File
function Volver(){
  window.history.back();
}

 function navegar(myURL){
    window.location.href= myURL;
 }
 
function Abrir_Ventana(URL){
    var sFEATURES= 'toolbar=0,scrollbars=yes,location=0,status=1,menubar=no,left=0,top=0,resizable=1, width=830px, height=630px';

    try{
        window.open(URL,"winVentana","",true)
        }
    catch(err)
    {
      alert('Imposible abrir la ventana'); 
    }

}

function Abrir_Ventana_Legal(URL){
    var sFEATURES= 'toolbar=0,scrollbars=yes,location=0,status=1,menubar=no,left=0,top=0,resizable=1, width=600px, height=350px';

    try{
        window.open(URL,"winVentana",sFEATURES,true)
        }
    catch(err)
    {
      alert('Imposible abrir la ventana'); 
    }

}

function Abrir_Ventana_Coments(URL){
    var sFEATURES= 'toolbar=0,scrollbars=yes,location=0,status=1,menubar=no,left=0,top=0,resizable=1, width=450px, height=350px';

    try{
        window.open(URL,"winVentana",sFEATURES,true)
        }
    catch(err)
    {
      alert('Imposible abrir la ventana'); 
    }

}

function Codificar_HTML(sENTRADA){
    //sENTRADA=  sENTRADA.replace(/<br>/g, 'xXEnterXx');
    //sENTRADA=  sENTRADA.replace(/<BR>/g, 'xXEnterXx'); 
    sENTRADA=  sENTRADA.replace(/>/g, 'xXMAYXx'); 
    sENTRADA=  sENTRADA.replace(/</g, 'xXMENXx'); 
    
    return sENTRADA;
}

function Decodificar_HTML(sENTRADA){
    sENTRADA=  sENTRADA.replace(/xXMAYXx/g, '>'); 
    sENTRADA=  sENTRADA.replace(/xXMENXx/g, '<'); 
    
     return sENTRADA;
}



function Abrir_Flyer(sFLYER){
var sFEATURES= 'toolbar=0,scrollbars=yes,location=0,status=1,menubar=no,left=0,top=0,resizable=1, width=400px, height=400px';

try{
    navegar('r_Enviar_Flyer.aspx?FLYER=' + sFLYER)
    }
catch(err)
{
  alert('Imposible abrir la ventana'); 
}

}


//FUNCIÓN QUE AJUSTA EL CONTENIDO DEL CONTROL DE TEXTO, DE MODO 
//QUE RESPETA LA LONGITUD MÁXIMA PERMITIDA
 function AjustarTexto(control, iLongitud)
     {
     var texto=  control.value;
     
     if(texto.length>iLongitud){
        texto= texto.substring(0,iLongitud);
        control.value= texto;
      }
     
     }
     
     
				
function replaceSubstring(inputString, fromString, toString) {
			// Goes through the inputString and replaces every occurrence of fromString with toString
			var temp = inputString;
			if (fromString == "") {
				return inputString;
			}
			if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
				while (temp.indexOf(fromString) != -1) {
					var toTheLeft = temp.substring(0, temp.indexOf(fromString));
					var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
					temp = toTheLeft + toString + toTheRight;
				}
			} else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
				var midStrings = new Array("~", "`", "_", "^", "#");
				var midStringLen = 1;
				var midString = "";
				// Find a string that doesn't exist in the inputString to be used
				// as an "inbetween" string
				while (midString == "") {
					for (var i=0; i < midStrings.length; i++) {
						var tempMidString = "";
						for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
						if (fromString.indexOf(tempMidString) == -1) {
						midString = tempMidString;
						i = midStrings.length + 1;
						}
					}
				} // Keep on going until we build an "inbetween" string that doesn't exist
				// Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
				while (temp.indexOf(fromString) != -1) {
					var toTheLeft = temp.substring(0, temp.indexOf(fromString));
					var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
					temp = toTheLeft + midString + toTheRight;
				}
				// Next, replace the "inbetween" string with the "toString"
				while (temp.indexOf(midString) != -1) {
					var toTheLeft = temp.substring(0, temp.indexOf(midString));
					var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
					temp = toTheLeft + toString + toTheRight;
				}
			} // Ends the check to see if the string being replaced is part of the replacement string or not
			return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function	
     
function MM_findObj(n, d) { //v4.01
    var p,i,x;

    if(!d) {
        d=document;
    }

    if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
    }

    if(!(x=d[n]) && d.all) {
        x=d.all[n];
    }

    for (i=0; !x && i<d.forms.length; i++) {
        x = d.forms[i][n];
    }

    for(i=0;!x&&d.layers&&i<d.layers.length;i++) {
        x = MM_findObj(n,d.layers[i].document);
    }

    if(!x && d.getElementById) {
        x=d.getElementById(n);
    }

    return x;
}

function MM_validateForm() { //v4.1rbf
    var i,p,q,nm,test,msg,num,min,max,errors='',args=MM_validateForm.arguments,error=false;
	var mikExp = /[$\\@\\\#%\^\&\*\(\)\[\]\+\_\{\}\`\~\=\|\<\>]/;
	//characters\n\r\n\r@ $ % ^ & * # ( ) [ ] \\ { + } ` ~ =  | \n\r\n\rare not allowed!\n");

    for (i=0; i<(args.length-1); i+=3) {

        test=args[i+1];
        val=MM_findObj(args[i]);
		if (!error)
			val2=MM_findObj(args[i]);
		nm=args[i+2]; //El nombre del CAMPO manda el ALERT
		

        if (val) {
            //nm=val.name;
            //si es combo
            if (test.indexOf('isCombo')!=-1) {
		if (val.options[val.selectedIndex].value == 0) {
			errors+='- \"'+nm+'\" es obligatorio.\n';
			error = true;
		}
            } else
            if ((val=val.value)!="") {
                if (test.indexOf('isText')!=-1) {
					if(val.search(mikExp) > -1) {
						errors+='- \"'+nm+'\" contiene caracteres invalidos: ' + val + '.\n';
						error = true;
					}
                } else if (test.indexOf('isPath')!=-1) {
					if (!(/^(\w+|\.\.|\.)?(\/(\w+|\.\.|\.))*(\?\w+=\w+(&\w+=\w+)*)?$/.test(val))) {
						errors+='- \"'+nm+'\" debe contener una ruta valida.\n';
						error = true;
					}
                } else if (test.indexOf('isFile')!=-1) {
					if (!(/^(\w+|\.\.|\.)?(\/(\w+|\.\.|\.))*\/([\w+\.])*\w+$/.test(val))) {
						errors+='- \"'+nm+'\" debe contener una ruta valida a un archivo.\n';
						error = true;
					}
                } else if (test.indexOf('isEmail')!=-1) {
                    p=val.indexOf('@');
                    if (p<1 || p==(val.length-1)) {
                        errors+='- \"'+nm+'\" debe contener una direccion de correo electronico.\n';
						error = true;
                    //} else if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(val))) {
                    } else if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)+$/.test(val))) {
						errors+='- \"'+nm+'\" contiene una direccion de correo invalida: ' + val + '.\n';
						error = true;
					}
                } else if (test.indexOf('isDate')!=-1) {

                    dia = val.substring(0,2);
                    s1  = val.substring(2,3);
                    mes = val.substring(3,5);
                    s2  = val.substring(5,6);
                    ano = val.substring(6,10);

                    if ( (val.length!=10) || // el formato de fecha es de 10 caracteres
                         (isNaN(dia)) || // verificar el dia
                         (isNaN(mes)) || // verificar el mes
                         (isNaN(ano)) || // verificar el anio
                         (s1!="/") || (s2!="/") ) { // verificar los separadores
                        errors+='- \"'+nm+'\" debe contener una fecha (dd/mm/yyyy).\n';
						error = true;
		    } else if ((ano < 1900) || (ano > 2079)) {
						errors+='- \"'+nm+'\" contiene una fecha invalida: ' + val + '.\n';
						error = true;
                    } else if (!validaFecha(dia,mes,ano)) {
						errors+='- \"'+nm+'\" contiene una fecha invalida: ' + val + '.\n';
						error = true;
					}

                } else if (test!='R') {
                    num = parseFloat(val);

                    if (test.indexOf('isSignedNum') != -1 || test.indexOf('isNum') != -1) {
						if (!(/^[-+]?\d+$/.test(val))) {
							errors+='- \"'+nm+'\" debe contener un numero entero.\n';
							error = true;
							break;
						}
                     }

                    if (test.indexOf('isUnsignedNum') != -1 || test.indexOf('isInteger') != -1) {
						if (!(/^\d+$/.test(val))) {
							errors+='- \"'+nm+'\" debe contener un numero entero sin signo.\n';
							error = true;
							break;
						}
                    }

                    if (test.indexOf('isCurrency') != -1) {
                        if (!(/^[-+]?\d*\.\d\d$/.test(val))) {
                            errors+='- \"'+nm+'\" debe contener un numero con 2 decimales.\n';
							error = true;
                        }
                    }

                    if (test.indexOf('isFloat') != -1) {
                        if (!(/^[-+]?\d*\.?\d+$/.test(val))) {
                            errors+='- \"'+nm+'\" debe contener un numero.\n';
							error = true;
                        }
                    }

                    if (test.indexOf('inRange') != -1) {
                        p=test.indexOf(':');
                        min=test.substring(8,p); max=test.substring(p+1);

                        if (num<min || max<num) {
                            errors+='- \"'+nm+'\" debe contener un numero entre '+min+' y '+max+'.\n';
							error = true;
                        }
                    }
                }
            } else if (test.charAt(0) == 'R') {
                errors += '- \"'+nm+'\" es obligatorio.\n';
				error = true;
            }
        }
    }

    if (errors) {
        alert('Ocurrieron los siguientes errores:\n'+errors);
		val2.focus();
    }

    document.MM_returnValue = (error);
}

function validaFecha(myDayStr, myMonthStr, myYearStr) {

	if ((myDayStr > 31) || (myMonthStr > 12)) {
		return false;
	}
 
	var myDate = new Date(myYearStr, myMonthStr-1, myDayStr);

	/* Cuando una fecha es invalida, al convertirla a Date()
	   el mes (getMonth()) se recorre automaticamente, resultando
	   diferente de myMonthStr-1 */	
	return (parseInt(myDate.getMonth())) == parseInt(myMonthStr-1);
}

	function TextoCorrecto(strCadena)
	{
		var nIndex = 0;
		
		if (strCadena.length > 0) {
			for (nIndex ; nIndex < strCadena.length; nIndex++)
			{
				if ((strCadena.charAt(nIndex) == "<") || (strCadena.charAt(nIndex) == ">")
					|| (strCadena.charAt(nIndex) == "&"))
					return false;
			}
		}
		return true;
	}

function formatCurrency( num ) {
        var isNegative = false;
        num = num.toString().replace(/\\$|\\,/g,'');
        if( isNaN( num ) ) {
          num = "0";
        }
        if ( num < 0 ) {
          num = Math.abs( num );
          isNegative = true;
        }
        cents = Math.floor( ( num * 100 + 0.5 ) % 100 );
        num = Math.floor( ( num * 100 + 0.5 ) / 100 ).toString();
        if ( cents < 10 ) {
          cents = "0" + cents;
        }
        for ( i = 0; i < Math.floor( ( num.length - ( 1 + i ) ) / 3 ); i++) {
          num = num.substring( 0 ,num.length - ( 4 * i + 3 ) ) + ',' + num.substring( num.length - ( 4 * i + 3 ) );
        }

        var result = num + '.' + cents;
        if ( isNegative ) {
          result = "-" + result;
        }
        return result;
      }

