/**********************************
NOTA: Para usar este script necesitas tener referencia al script 
	  global_functions.js.
***********************************/

/**
ChrExcp1 = ","; ChrExcp2 = "."; ChrExcp3 = ":"
**/
var ErrorInProgress = false;
var ObjectError = false;

var vMark = 0; vError = false;


/**************************************************************************************/
function entryOnlyNumbers(e, ChrExcp1, ChrExcp2, ChrExcp3){//LISTO
	tecla = getKeyCode(e)
	if (tecla==8 || tecla==37 || tecla==38 || tecla==39 || tecla==40) return true;
	if (tecla==35 || tecla==36) return true;
	if (tecla == 13) return true;
	if ((ChrExcp1) && (tecla == 44)) return true; //Verificar si se puede ingresar comas.
	if ((ChrExcp2) && (tecla == 46)) return true; //Verificar si se puede ingresar puntos.
	if ((ChrExcp3) && (tecla == 58)) return true; //Verificar si se puede ingresar dos puntos.
	if (tecla == 9) return true; //Verificar si se puede ingresar dos puntos.

	patron =/\d/;

	te = String.fromCharCode(tecla);
  if (!patron.test(te)){
		stopEvent(e)
  }
  
  
}
/**************************************************************************************/


/*** Functions for numbers validation ***/
function formatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas){ //LISTO
    if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number

	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	if (isNaN(parseInt(tmpNum))) return "NaN";

	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}
	if (decimalNum > 0){
		var pos = tmpNumStr.indexOf(".");
		var zeros = ".";
		var decimalpart = "";

		if (pos > 0){
			decimalpart = tmpNumStr.substr(pos + 1,tmpNumStr.length); 
			zeros = "";
		}
		for (var i=decimalpart.length; i<decimalNum;i++) zeros += "0"; 

		tmpNumStr += zeros; 
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}

/***********************************************************/
function elementNumberOnBlur(e, DecimalNum,LeadingZero,Parens,Commas,DefaultValue, PreserveValue){

	vError = false;
	if (vMark==1) return false;
	if (e.keyCode == 13) vMark = 1;
	
	var typExplorer = detectBrowser();
	var element = null
	if (typExplorer=="IE"){
		element = event.srcElement;
	}else{
		element = e.target;
	}


	
	var tmpValue = element.value;

	if (ErrorInProgress && element.id != ObjectError.id) {
	   ErrorInProgress = false
	   return true;
	}

	ErrorInProgress = false;

	if (tmpValue == "" && DefaultValue) tmpValue = "0";
    if (tmpValue == "") return true;

	tmpValue = tmpValue.toString().replace(/\$|\,/g,'');
	tmpValue = formatNumber(tmpValue,DecimalNum,LeadingZero,Parens,Commas);

	if (tmpValue == "NaN"){
		ErrorInProgress = true;
		ObjectError = element;
		alert("The value you entered isn't valid for this field. This field only accepts numeric values.");
		if (e.keyCode == 13) vError = true;
		
		window.setTimeout(function(){element.focus();}, 1)
		return false;
	}else{
		if (typeof(PreserveValue) != "undefined" || PreserveValue == false) element.value = tmpValue;
		return true;
	}
}
/***         End         ***/
/*** Functions for e-mails validation ***/
function echeck(str){
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);

	if (str.indexOf(at)==-1) return false;
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) return false;
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) return false;
	if (str.indexOf(at,(lat+1))!=-1) return false;
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) return false;
	if (str.indexOf(dot,(lat+2))==-1) return false;
	if (str.indexOf(" ")!=-1) return false;

 	return true;
}
function validateCharactersMail(argvalue){	
	var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890.;@_- ";
			
	var checkStr = argvalue.value;
	var allValid = true;
		
	for(i=0;i<checkStr.length;i++)
	{
		ch=checkStr.charAt(i);
		
		for(j=0;j<checkOK.length;j++)
			if (ch == checkOK.charAt(j))
				break;
		
		if (j == checkOK.length)
		{
			allValid=false;
			break;
		}
	}

	if (!allValid){
		alert("The e-mail address may consist of a-z, 0-9 and underscores.")
		return false;
	}
	
	return true; 
}
function elementEmailOnBlur(e){
	var typExplorer = detectBrowser();
	var element = null
	if (typExplorer=="IE"){
		element = event.srcElement;
	}else{
		element = e.target;
	}
	
	var tmpValue = element.value;

	if (ErrorInProgress && element.id != ObjectError.id) {
	   ErrorInProgress = false
	   return true;
	}

	ErrorInProgress = false;

    if (Trim(tmpValue) == ""){
		element.value = "";
		return true;
    }

	var valid = echeck(tmpValue);

	if (! valid){
		ErrorInProgress = true;
		ObjectError = element;
		alert("The value you entered isn't valid for this field. This field only accepts valid e-mails (test@test.com).");
		window.setTimeout(function(){element.focus();}, 1)
		return false;
	}

	return true;
}
/***         End         ***/
/*** Functions for dates validation ***/
function IsValidDate(PossibleDate,lgActual){	
	var PDate = new String(PossibleDate);
	var regex = /(^\d{1,2})\/(\d{1,2})\/(\d{4,4})|(^\d{1,2})\/(\d{1,2})\/(\d{2,2})/;

	if( regex.test(PDate)){
		var month = new String(RegExp.$1);
		var day = new String(RegExp.$2);
		var year = new String(RegExp.$3);
		if( month.length == 0 ){
			month = new String(RegExp.$4);
			day = new String(RegExp.$5);
			year = new String(RegExp.$6);
			
			
		}
		if(lgActual == 1){
		    var tempMonth = month
		    month = day
		    day = tempMonth
		}
				
		var today = new Date();
		var thisYear = new String(today.getFullYear());
		if( year.length == 2 ){
			if( year > 50 ){year = String(Number(thisYear.substring(0,2))-1) + year;}
			else{year = thisYear.substring(0,2) + year;}
		}
		if( month < 1 || month > 12 ) return false;
		if( day < 1 || day > 31 ) return false;
		if ((month==4 || month==6 || month==9 || month==11) && day>30) return false;

		if (month == 2) // check for february 29th
		{
			var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
			if (day>29 || (day==29 && !isleap)) return false;
		}
		if((Number(year) < Number(thisYear) - 250) || (Number(year) > Number(thisYear) + 250)) return false;

		return PossibleDate;
	}

	return false;
}
function formatDate(date,lgActual){

	var tmpValue = date.toString().replace(/\/|\./g,'');
    var tmpDate = "";

	if (isNaN(tmpValue)) return false;
	if (tmpValue.length < 6) return false;

	if (tmpValue.length == 6){
		var DateTmp = new Date();
		var sYear = new String(DateTmp.getFullYear());

		tmpDate = tmpValue.substr(0,2) + "/" + tmpValue.substr(2,2) + "/" + sYear.substr(0,2) + tmpValue.substr(4,2);
	}else{
		var n=0;
		var tmpYear="";
		var tmpMonth="";
		var tmpDay="";

		for (var i = tmpValue.length-1; i>=0; i--){
			if (n < 4) tmpYear = tmpValue.substr(i,1) + tmpYear;
			if ((n > 3) && (n < 6)) tmpDay = tmpValue.substr(i,1) + tmpDay;
			if (n > 5) tmpMonth = tmpValue.substr(i,1) + tmpMonth;
			n+=1;
		}
        
        
		tmpDate = (tmpMonth <= 9 ? "0" : "") + Math.abs(tmpMonth) + "/" + (tmpDay <= 9 ? "0" : "") + Math.abs(tmpDay) + "/" + tmpYear;
	}

    
	return IsValidDate(tmpDate,lgActual);
}
function elementDateOnBlur(e, lenguageID){
    var lgActual = 0;
    
    if (document.getElementById("_lActual") !== null){
		lenguageID = document.getElementById("_lActual").value
    }

    if (typeof(lenguageID) == "undefined")
        lgActual = 0    
    else        
        lgActual = lenguageID 
        
    vError = false;
	if (vMark==1) return false;
	if (e.keyCode == 13) vMark = 1;
	
	var typExplorer = detectBrowser();
	var element = null
	if (typExplorer=="IE"){
		element = event.srcElement;
	}else{
		element = e.target;
	}
	
	var tmpValue = element.value;

	if (ErrorInProgress && element.id != ObjectError.id) {
	   ErrorInProgress = false
	   return true;
	}

	ErrorInProgress = false;

    if (Trim(tmpValue) == ""){
		element.value = "";
		return true;
    }

	var valid = formatDate(tmpValue,lgActual);

	if (valid == false){
		    ErrorInProgress = true;
		    ObjectError = element;
		    if(lgActual == 1)
	    	    //alert("El Formato de Fecha aceptado es: (Mes/ D" + String.fromCharCode(237) + "a / A" + String.fromCharCode(241) + "o).");
	    	    alert("El Formato de Fecha aceptado es: (D" + String.fromCharCode(237) + "a / Mes / A" + String.fromCharCode(241) + "o).")
		    else
		        alert("Please check the Date Format (Month / Day / Year).");
		if (e.keyCode == 13) vError = true;
		    element.value = "";
		    window.setTimeout(function(){element.focus();}, 1)
		    return false;
	}else{
		element.value = valid;
		return true;
	}
}


function Trim(cadena)
{
	for(i=0; i<cadena.length; )
	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(i+1, cadena.length);
		else
			break;
	}

	for(i=cadena.length-1; i>=0; i=cadena.length-1)
	{
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(0,i);
		else
			break;
	}
  return cadena	
}
/**********************/



/*** Functions for times validation ***/
function validateTime(value){
	var iToday = new Date();
	var iDay = iToday.getDate();
	var iMonth = iToday.getMonth();
	var iYear = iToday.getFullYear();
	var divisionPos = value.search(/:/i);
	var iHours = new String(value.substr(0, divisionPos));
	var iMinutes = new String(value.substr(divisionPos + 1));
		
	if ((iHours < 0 ||  iHours > 23) || (iMinutes < 0 || iMinutes > 59)) {
		return false;
	}

	var iDate = new Date(iYear, iMonth, iDay, iHours, iMinutes);
	if (isNaN(iDate)) return false;

	return value;
}
function formatTime(date){
	var tmpValue = date.toString().replace(/\:|\./g,'');
    var tmpTime = "";

	if (isNaN(tmpValue)) return false;

	var n=0;
	var tmpMinutes="";
	var tmpHours="";

	for (var i = 0; i<tmpValue.length; i++){
		if (n < 2) tmpHours += tmpValue.substr(i,1);
		if (n > 1) tmpMinutes += tmpValue.substr(i,1);
		n+=1;
	}

	tmpDate = (tmpHours <= 9 ? "0" : "") + Math.abs(tmpHours) + ":" + (tmpMinutes <= 9 ? "0" : "") + Math.abs(tmpMinutes);

	return validateTime(tmpDate);
}
function elementTimeOnBlur(e){
	var typExplorer = detectBrowser();
	var element = null
	if (typExplorer=="IE"){
		element = event.srcElement;
	}else{
		element = e.target;
	}
	
	var tmpValue = element.value;

	if (ErrorInProgress && element.id != ObjectError.id) {
	   ErrorInProgress = false
	   return true;
	}

	ErrorInProgress = false;

    if (Trim(tmpValue) == ""){
		element.value = "";
		return true;
    }

	var valid = formatTime(tmpValue);

	if (valid == false){
		ErrorInProgress = true;
		ObjectError = element;
		alert("The value you entered isn't valid for this field. Use 24 Hours Format. eg. 17:00 = 05:00 pm.");
		window.setTimeout(function(){element.focus();}, 1)
		return false;
	}else{
		element.value = valid;
		return true;
	}
}

/**************************************************************************************/
function entryOnlyNumbersTab(e, ChrExcp1, ChrExcp2, ChrExcp3,element){//LISTO
	tecla = getKeyCode(e)

     if (tecla == 9){
            alert("dsadsa")
            element.setFocus()
		    stopEvent(e)
        }

	if (tecla==8 || tecla==37 || tecla==38 || tecla==39 || tecla==40) return true;
	if (tecla==35 || tecla==36) return true;
	if (tecla == 13) return true;
   
	if ((ChrExcp1) && (tecla == 44)) return true; //Verificar si se puede ingresar comas.
	if ((ChrExcp2) && (tecla == 46)) return true; //Verificar si se puede ingresar puntos.
	if ((ChrExcp3) && (tecla == 58)) return true; //Verificar si se puede ingresar dos puntos.
	
	patron =/\d/;

	te = String.fromCharCode(tecla);
  if (!patron.test(te)){
		stopEvent(e)
  }
  
  
}
/**************************************************************************************/


/***         End         ***/