/*
 * Generic Validation Functions
 */
var K_ISNOTNULL=0, K_ISNUMERIC=1, K_EMAIL=2, K_TELEPHONE=3, K_CELLPHONE=4,  
	K_TO_STRING=5, K_DATE=6, K_NOT_EMPTY=7, K_VALID_NAME=8, K_STRING_ALPHA=9,  
	K_STRING_ALPHA_SPACE=10, K_STRING_EXTENDED=11, K_URL=12, K_USERLOGIN=13, K_STRING_ALPHA_DOT=14, K_FILENAME=15; 
var ErrorFieldAlreadyFocused = false;

/**
 * Verifca se um determinado valor respeita as regras aplicaveis ao seu tipo.
 * cf - valor a validar
 * ti - tipo do valor
 * vmin - valor minimo, se aplicavel
 * vmax - valor maximo, se aplicavel
 * dc - numero de casas decimais, se aplicavel
 */
function checkField(cf , ti , vmin , vmax , dc)
{
	if (ti == K_ISNUMERIC || ti == K_ISTELEPHONE) 
		return checkNumeric(cf , vmin , vmax , dc);
		
	if (ti == K_ISCELLPHONE) 
		return checkCellPhone(cf);
		
	if (ti == K_ISEMAIL)
		return checkEmail(cf);
		
	if (ti == K_ISNOTNULL)
		return !(cf == null);
		
	if (ti == K_ISNOTEMPTY)
		return !isEmpty(cf);
		
	return true;
}

function checkNumeric(val , vmin , vmax , dc)
{
	val = ("" + val).replace(/\,/,".");
	var f = parseFloat(val), pv;
	
	if (typeof(vmin) != "number")
		vmin = Number.MIN_VALUE;
		
	if (typeof(vmax) != "number")
		vmax = Number.MAX_VALUE;
		
	if (typeof(dc) != "number")
		dc = 0;
		
	if (isNaN(f))
		return false;
		
	var p = val.indexOf(".");
	var v = val.indexOf(",");
	pv = (v < 0) ? p : v;

	if (dc == 0 && pv > -1 )
		return false;
		
	if (val.search(/^[0-9.,]+$/) < 0) 
		return false;
		
	if (f < vmin || f > vmax) 
		return false;
		
	if (pv  > -1 && (val.length - pv - 1) > dc)	
		return false;
		
	return true;
}

function checkCellPhone(val)
{
	return (val.search(/^9[136]\d{7}$/) != -1);
}

function checkEmail(val , vmin , vmax)
{
	if ((val == null || val == '' || val.length < 3 || val.indexOf('@') <= 0 || val.indexOf('.') <= 0 
	    || val.lastIndexOf('..')>0 || val.lastIndexOf('.@')>0 || val.lastIndexOf('@.')>0 
	        || val.lastIndexOf('.') < 3 || val.indexOf('@') != val.lastIndexOf('@')))
		return false;
	if ((vmin != null) && (vmax != null))
		return (val.length >= vmin) && (val.length <= vmax);
	else return true;
}

function IsNill(p){return (typeof(p)=="undefined")||p==null||String(p)=="";}	
 
function validateMonth(field) { 
	var input = stripZeros(field);
	if (isEmpty(input)) { 
		return false;
	} else { 
		if (!isNumber(input)) { 
			return false;
		} else { 
			if (!inRange(input,1,12)) { 
				return false;
			} 
		} 
	} 
	return true;
} 

function GetValidMonth(field) { 
	var input = stripZeros(field);
	if (isEmpty(input)) { 
		return 0;
	} else { 
		if (!isNumber(input)) { 
			return 0;
		} else { 
			if (!inRange(input,1,12)) { 
				return 0;
			} 
		} 
	} 
	return parseInt(input);
} 
function validateDate(field, monthField) { 
	var input = stripZeros(field);
	if (isEmpty(input)) { 
		return false;
	} else { 
		if (!isNumber(input)) { 
			return false;
		} else { 
			if (!validateMonth(monthField)) return false;
			var monthVal = GetValidMonth(monthField);
			var monthMax = new Array(0,31,29,31,30,31,30,31,31,30,31,30,31);
			var top = monthMax[monthVal];
			if (!inRange(input,1,top)) { 
				return false;
			} 
		} 
	} 
	return true;
} 
 
function validateYear(field) { 
	var input = stripZeros(field);
	if (isEmpty(input)) { 
		return false;
	} else { 
		if (!isNumber(input)) { 
			return false;
		} else { 
			if (!inRange(input,1900,3000)) { 
				return false;
			} 
		} 
	} 
	return true;
} 
 
function checkFullDate(year, month, day, hour, mins){ 
	if((!validateYear(year))||(!validateMonth(month))||(!validateDate(day, month))) 
		return false; 
	if((month==2)&&(day==29)) 
	{ 
		if(!isLeapYear(year)) // anos bisextos 
			return false; 
	} 
	if((isEmpty(hour))||(!isNumber(hour))||(hour>23)||(hour<0)) 
		return false; 
	if((isEmpty(mins))||(!isNumber(mins))||(mins>59)||(mins<0)) 
		return false; 
	return true; 
} 
 
function isLeapYear(y) {return (y % 4 == 0  &&  (y % 100 != 0  ||  y % 400 == 0));} 
 
function checkIntervalDate(dtini,dtfim)  
{ 
	if (dtini != "" && dtfim != "" && dtini >= dtfim) 
		return false; 
	return true;	 
}

function checkHour(hour)
{
	if( (isEmpty(hour)) || (!isNumber(hour)) || (hour > 23) || (hour < 0) )
		return false;
	return true;
}


function stripZeros(inputStr) { 
	var result = inputStr;
	while (result.substring(0,1) == "0") { 
		result = result.substring(1,result.length);
	} 
	return result;
} 
 
// general purpose function to see if an input value has been entered at all 
function isEmpty(inputStr) { 
	if (inputStr == "" || inputStr == null) { 
		return true 
	} 
	return false 
} 
 
// general purpose function to see if a suspected numeric input  
// is a positive integer 
function isNumber(inputStr) { 
	for (var i = 0; i < inputStr.length; i++) { 
		var oneChar = inputStr.substring(i, i + 1) 
		if (oneChar < "0" || oneChar > "9") { 
			return false 
		} 
	} 
	return true 
} 
 
// function to determine if value is in acceptable range for this application 
function inRange(inputStr, lo, hi) { 
	var num = parseInt(inputStr);
	if (num < lo || num > hi) { 
		return false;
	} 
	return true;
} 

function daysInFebruary (year)
{
	return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) 
{
	for (var i = 1; i <= n; i++) 
	{
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
	} 
	return this;
}

function stripCharsInBag(s, bag)
{
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++)
	{   
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function isInteger(s)
{
	var i;
	for (i = 0; i < s.length; i++)
	{   
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	return true;
}	
var minYear=1900;
var maxYear=2100;

function validateDateString(dateId, dtCh, validationType)
{
	if (validationType == 1)
		dtStr =	document.getElementById(dateId).value;
	else
		dtStr =	dateId;
	
	if (dtStr == "")
		return true;
					
	var daysInMonth = DaysArray(12);
	
	var pos1 = dtStr.indexOf(dtCh);
	var pos2 = dtStr.indexOf(dtCh,pos1+1);
	var strDay = dtStr.substring(0,pos1);
	var strMonth = dtStr.substring(pos1+1,pos2);
	var strYear = dtStr.substring(pos2+1);
	
	strYr = strYear;
	
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)

	for (var i = 1; i <= 3; i++)
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	
	if (strMonth.length<1 || month<1 || month>12)
	{
		//alert("Insira um mês válido");
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])
	{
		//alert("Insira um dia válido");
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear)
	{
		//alert("Insira un ano válido");					
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false)
	{
		//alert("Insira uma data válida");
		return false;
	}
	return true;
}
function isNIF(nif) 
{
	nif=nif+"";
	var ret=false;
	
	if ((nif.length == 9) && ((nif-0) > 0)) 
	{
		var soma = 0;
		for (i = 0,peso=9; (i < 8);i++,peso--)
		{
			digito = nif.substr(i,1);
			soma += (peso * digito);
		}
		var checkDigit = 11 - (soma % 11);
		if (checkDigit == 10 || checkDigit == 11)
			ret = (nif.substr(8,1) == 0);
		else
			ret = (nif.substr(8,1) == checkDigit);
	}
	return !ret;
}

/*
 *  Event Handler's (acceptXpto), browser detection, auto jump, showAlert
 */
var salta = true, ctg, idioma=1;

/* removed - not used and incompatible with menu library
function isIE(){return ((navigator.userAgent.toLowerCase()).indexOf("msie") != -1);}
function isNS(){return ((navigator.userAgent.toLowerCase()).indexOf("msie") == -1);}
*/

function acceptKey(cf,ev,ti,dc){
	if (isSpecialChar(getKeyCode(ev))) return true;
	if (ti==K_ISNUMERIC || ti==K_ISTELEPHONE) return acceptNumeric(ev,cf,dc);
	if (ti==K_ISCELLPHONE) return acceptCellPhone(ev,cf);
	if (ti==K_ISVALIDNAME) return acceptChar(ev,cf);
	return true;
}
function acceptNumeric(ev,cf,dc){
	var c=String.fromCharCode(getKeyCode(ev)), pv,val=cf.value;
	if (typeof(dc) != "number")
		dc = 0;
	var p=val.indexOf("."),v=val.indexOf(",");
	var aceitaSeparador = ((p < 0 ) && (v < 0) && (dc > 0));
	pv= (v<0) ? p : v;
	if ((c==',' || c=='.') && !aceitaSeparador)	return false;
	if ((p==0) || (v==0))return false;
	if (c.search(/[0-9,.]/) <0)	return false;
	if (pv  > -1 && (val.length - pv) > dc)	return false;
	return true;
}
function acceptCellPhone(ev,cf){
	var c, l;
	if (!acceptNumeric(ev,cf))	return false;
	c = String.fromCharCode(getKeyCode(ev));
	l = cf.value.length;
	if (l == 0 && c != '9')	return false;
	else if (l == 1 && (c != '1' && c != '3' && c != '6'))return false;
	return true;
}
function acceptChar(ev,cf){
	var c;
	c = String.fromCharCode(getKeyCode(ev));
	if (c == '^') return false;
	return true;
}
function getKeyCode(e){
	if (document.all) return e.keyCode;
	else return e.which;
}
function isSpecialChar(t){ return t<32 || (t>37 && t<40) && String.fromCharCode(t)!="'" && String.fromCharCode(t)!="&";}
function processJump(cf,ev,px,l,cb){
	if (!salta) return;
	if (!px) return;
	if (cb == true){
		try{px.focus()}catch(e){};
	}
	else{
		if (isSpecialChar(getKeyCode(ev))) return;
		if (typeof(px) == "undefined") return;
		if (typeof(l) == "undefined") return;
		if (!cf) return;
		if (!cf.value) return;
		if (cf.value.length >= l) try{px.focus();}catch(e){};
	}
}