/**********************************
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(ChrExcp1, ChrExcp2, ChrExcp3){
	var kc = window.event.keyCode;

	if (kc == 13) return;

	if ((ChrExcp1) && (kc == 44)) return; //Verificar si se puede ingresar comas.
	if ((ChrExcp2) && (kc == 46)) return; //Verificar si se puede ingresar puntos.
	if ((ChrExcp3) && (kc == 58)) return; //Verificar si se puede ingresar dos puntos.

	if ((kc < 48) || (kc > 57)) window.event.keyCode = 0;
}
/*** Functions for numbers validation ***/
function formatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas){ 
    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(DecimalNum,LeadingZero,Parens,Commas,DefaultValue, PreserveValue){
	var element = event.srcElement;
	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.");
		element.focus();
		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 elementEmailOnBlur(){
	var element = event.srcElement;
	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).");
		element.focus();
		return false;
	}

	return true;
}
/***         End         ***/
/*** Functions for dates validation ***/
function IsValidDate(PossibleDate){	
	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);
		}
		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){
	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);
}
function elementDateOnBlur(){
	var element = event.srcElement;
	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);

	if (valid == false){
		ErrorInProgress = true;
		ObjectError = element;
		alert("The value you entered isn't valid for this field. This field only accepts valid dates (01/01/05).");
		element.focus();
		return false;
	}else{
		element.value = valid;
		return true;
	}
}
/***         End         ***/
/*** 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(){
	var element = event.srcElement;
	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. This field only accepts valid times (12:30).");
		element.focus();
		return false;
	}else{
		element.value = valid;
		return true;
	}
}
function elementValidateMaxLen(vMaxLen){
	var element = event.srcElement;
	var tmpValue = element.value;

	if (ErrorInProgress && element.id != ObjectError.id) {
	   ErrorInProgress = false
	   return true;
	}

	ErrorInProgress = false;

    if (Trim(tmpValue) == ""){
		element.value = "";
		return true;
    }

	var mReturnValue
	
	mReturnValue = Number(tmpValue.length) <= Number(vMaxLen)
	  
	 var valid
	 if(!mReturnValue){
		valid = false
	 }else{
		valid =  tmpValue
	 }
   
	if (valid == false){
		ErrorInProgress = true;
		ObjectError = element;
		
		alert("Notes can note exceed " + vMaxLen.toString() + " characters. Current notes size " + tmpValue.length.toString() + " characters.");
		
		element.focus();
		return false;
	}else{
		element.value = valid;
		return true;
	}
}
function InStr(n, s1, s2){
	// Devuelve la posición de la primera ocurrencia de s2 en s1
	// Si se especifica n, se empezará a comprobar desde esa posición
	// Sino se especifica, los dos parámetros serán las cadenas
	var numargs=InStr.arguments.length;
	
	if(numargs<3)
		return n.indexOf(s1)+1;
	else
		return s1.indexOf(s2, n)+1;
}
function Left(s, n){
	// Devuelve los n primeros caracteres de la cadena
	if(n>s.length)
		n=s.length;
		
	return s.substring(0, n);
}
function Right(s, n){
	// Devuelve los n últimos caracteres de la cadena
	var t=s.length;
	if(n>t)
		n=t;
		
	return s.substring(t-n, t);
}
/***         End         ***/
