String.prototype.trim = function()
{
  return( this.replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,'$1') );
}

var BROldValue="";

// CPF ///////////////////////////////////////////////////////////////////////////

function FormataCPF(fld, e)
{
	var sep = key = '';
	var len = 0;
	var intCheck = '0123456789';
	var strCheck = '.-';
	var aux = '';
	if (fld.readOnly) return false;
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 0 || whichCode == 8) return true;
	key = String.fromCharCode(whichCode);
	len = fld.value.length;
	if (len > 13) return false;
	if (len == 1 || len == 2 || len == 3 || len == 7 || len == 11)
	 {
	    if (strCheck.indexOf(key) == 0) {
	        if (len == 3 || len == 7) { return; }
	        else if (len < 3){
	            aux = '00' + fld.value;
	            fld.value = aux.substr(aux.length - 3 , 3) + key;
	            return false;
	         }
	    }
	    else if (strCheck.indexOf(key) == 1) {
	        if (len == 11) { return; }
	        else { return false; }
	    }
	    else {
	        if (intCheck.indexOf(key) >= 0) {
	           if (len < 3) { return; }
	           if (len < 11) { sep = '.'; }
	           else { sep = '-'; }
	           fld.value += sep + key;
	        }
	        return false;
	    }
	 }
	if (intCheck.indexOf(key) == -1) return false;
}

function checkCPF(cpf)
{
    var cleaned = '';
    for (i = 0; i < cpf.length; i++) {
        num = cpf.charAt(i);
        if (!isNaN(num)) {
            cleaned = cleaned + num;
        }
    }
    cpf = cleaned;


    if (cpf.length != 11) {
        return false;
    } else if (cpf == '00000000000') {
        return false;
    } else {

    	number = new Array(10);

        number[0]  = parseInt(cpf.charAt(0), 10);
        number[1]  = parseInt(cpf.charAt(1), 10);
        number[2]  = parseInt(cpf.charAt(2), 10);
        number[3]  = parseInt(cpf.charAt(3), 10);
        number[4]  = parseInt(cpf.charAt(4), 10);
        number[5]  = parseInt(cpf.charAt(5), 10);
        number[6]  = parseInt(cpf.charAt(6), 10);
        number[7]  = parseInt(cpf.charAt(7), 10);
        number[8]  = parseInt(cpf.charAt(8), 10);
        number[9]  = parseInt(cpf.charAt(9), 10);
        number[10] = parseInt(cpf.charAt(10), 10);

        sum = 10*number[0]+9*number[1]+8*number[2]+7*number[3]+
            6*number[4]+5*number[5]+4*number[6]+3*number[7]+
            2*number[8];

        sum -= (11*(parseInt(sum/11, 10)));

        if (sum == 0 || sum == 1) {
            result1 = 0;
        } else {
            result1 = 11-sum;
        }

        if (result1 == number[9]) {
            sum = number[0]*11+number[1]*10+number[2]*9+number[3]*8+
                    number[4]*7+number[5]*6+number[6]*5+number[7]*4+
                    number[8]*3+number[9]*2;
            sum -= (11*(parseInt(sum/11, 10)));

            if (sum == 0 || sum == 1) {
                result2 = 0;
            } else {
                result2 = 11-sum;
            }

            if (result2 == number[10]) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}

// CNPJ //////////////////////////////////////////////////////////////////////////

function FormataCNPJ(fld, e)
{
	var sep = key = '';
	var len = 0;
	var intCheck = '0123456789';
	var strCheck = './-';
	var aux = '';
	if (fld.readOnly) return false;
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 0 || whichCode == 8) return true;
	key = String.fromCharCode(whichCode);
	len = fld.value.length;
	if (len > 17) return false;
	if (len == 1 || len == 2 || len == 6 || len == 10 || len == 15)
	 {
	    if (strCheck.indexOf(key) == 0) {
	        if (len == 2 || len == 6) { return; }
	        else if (len == 1){
	            aux = '0' + fld.value;
	            fld.value = aux + key;
	            return false;
	         }
	    }
	    else if (strCheck.indexOf(key) == 1) {
	        if (len == 10) { return; }
	        else { return false; }
	    }
	    else if (strCheck.indexOf(key) == 2) {
	        if (len == 15) { return; }
	        else { return false; }
	    }
	    else {
	        if (intCheck.indexOf(key) >= 0) {
	           if (len == 1) { return; }
	           if (len < 10) { sep = '.'; }
	           else if (len < 15) { sep = '/'; }
	           else { sep = '-'; }
	           fld.value += sep + key;
	        }
	        return false;
	    }
	 }

	if (intCheck.indexOf(key) == -1) return false;
}

function checkCNPJ(cnpj)
{
    cleaned = '';
    for (i = 0; i < cnpj.length; i++) {
        num = cnpj.charAt(i);
        if (!isNaN(num)) {
            cleaned = cleaned + num;
        }
    }
    cnpj = cleaned;
    if (cnpj.length != 14) {
        return false;
    } else if (cnpj == '00000000000000') {
        return false;
    } else {

    	number = new Array(13);

        number[0]  = parseInt(cnpj.charAt(0), 10);
        number[1]  = parseInt(cnpj.charAt(1), 10);
        number[2]  = parseInt(cnpj.charAt(2), 10);
        number[3]  = parseInt(cnpj.charAt(3), 10);
        number[4]  = parseInt(cnpj.charAt(4), 10);
        number[5]  = parseInt(cnpj.charAt(5), 10);
        number[6]  = parseInt(cnpj.charAt(6), 10);
        number[7]  = parseInt(cnpj.charAt(7), 10);
        number[8]  = parseInt(cnpj.charAt(8), 10);
        number[9]  = parseInt(cnpj.charAt(9), 10);
        number[10] = parseInt(cnpj.charAt(10), 10);
        number[11] = parseInt(cnpj.charAt(11), 10);
        number[12] = parseInt(cnpj.charAt(12), 10);
        number[13] = parseInt(cnpj.charAt(13), 10);

        sum = number[0]*5+number[1]*4+number[2]*3+number[3]*2+
               number[4]*9+number[5]*8+number[6]*7+number[7]*6+
               number[8]*5+number[9]*4+number[10]*3+number[11]*2;

		sum -= (11*(parseInt(sum/11, 10)));

        if (sum == 0 || sum == 1) {
            result1 = 0;
        } else {
            result1 = 11-sum;
        }

        if (result1 == number[12]) {
            sum = number[0]*6+number[1]*5+number[2]*4+number[3]*3+
                    number[4]*2+number[5]*9+number[6]*8+number[7]*7+
                    number[8]*6+number[9]*5+number[10]*4+number[11]*3+
                    number[12]*2;

            sum -= (11*(parseInt(sum/11, 10)));

            if (sum == 0 || sum == 1) {
                result2 = 0;
            } else {
                result2 = 11-sum;
            }

            if (result2 == number[13]) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}


// BRDate //////////////////////////////////////////////////////////////////////////

function FormataBRDate(fld, e, sep)
{
	sep = sep || '/';
	var key = '';
	var len = 0;
	var strCheck = '0123456789' + sep;
	if (fld.readOnly) return false;
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 0 || whichCode == 8) return true;
	key = String.fromCharCode(whichCode);
	if (strCheck.indexOf(key) == -1) return false;
	if (typeof(BROldValue) != 'undefined') {
		if (fld.value == BROldValue) { fld.value=''; }
	}
	len = fld.value.length;
	if (len > 9) return false;
	if (len == 2 || len == 5)
	 {
	    if (key == sep) {
	        return;
	     } else {
	        if (strCheck.indexOf(key) >= 0) {
	           fld.value += sep + key;
	        }
	        return false;
	     }
	 }
}

function checkBRDate(br_date)
{

	var regex = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;
	if (!regex.test(br_date))
	{
	 return false;
	}
	var arr_date = br_date.split( '/' );

	var mnum = parseInt(arr_date[1], 10);
	if ( mnum > 12 || mnum < 1 )
	{
	 return false;
	}
	var month = new Array();
	month[1]='Jan';
	month[2]='Feb';
	month[3]='Mar';
	month[4]='Apr';
	month[5]='May';
	month[6]='Jun';
	month[7]='Jul';
	month[8]='Aug';
	month[9]='Sep';
	month[10]='Oct';
	month[11]='Nov';
	month[12]='Dec';
	var newDate = new Date( arr_date[0] + ' ' + month[mnum] + ' ' + arr_date[2] );
	var gmtDate = newDate.toGMTString();
	var arr_gmt = gmtDate.split( ' ' );
	if (month[mnum] != arr_gmt[2])
	{
	 return false;
	}
	return true;
}


function getIdade(br_date, ref_br_date) {

	if (! checkBRDate(br_date)) return false;

	var arr_date = br_date.split( '/' );

	var dd = parseInt(arr_date[0], 10);
	var mm = parseInt(arr_date[1], 10);
	var yy = parseInt(arr_date[2], 10);

	if (ref_br_date == "") {
		var time = new Date();
		gdate  = time.getDate();
		gmonth = time.getMonth();
		gyear  = time.getFullYear();
	} else {
		if (! checkBRDate(ref_br_date)) return false;
		arr_date = ref_br_date.split( '/' );
		gdate  = parseInt(arr_date[0], 10);
		gmonth = parseInt(arr_date[1], 10) - 1;
		gyear  = parseInt(arr_date[2], 10);
	}


	if (mm == 2 && dd == 29) {
		if (! lyear(gyear)) dd--;
	}
	age = gyear - yy;

	if (mm > (gmonth + 1)) {
		age = age - 1;
	} else if (mm == (gmonth + 1)) {
		if (dd > parseInt(gdate, 10)) {
			age = age - 1;
		}
	}

	if (age < 0) age = 0;

	return age;
}


function lyear(a) {
	if(((a % 4 == 0) && (a % 100 != 0)) || (a % 400 == 0)) return true;
	else return false;
}

function getIsoDate() {

    var time = new Date();
	gdate  = time.getDate();
	gmonth = time.getMonth();
	gyear  = time.getFullYear();
	gmonth++;
    mes = '0' + gmonth.toString();
    if (mes.length > 2) mes = mes.substring(1);
    dia = '0' + gdate.toString();
    if (dia.length > 2) dia = dia.substring(1);
	return gyear.toString() + mes + dia;
}

function padZeros(number,length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

// Fone //////////////////////////////////////////////////////////////////////////

function FormataFone(fld, e)
{
	var key = '';
	var len = 0;
	var strCheck = '0123456789';
	if (fld.readOnly) return false;
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 0 || whichCode == 8) return true;
	key = String.fromCharCode(whichCode);
	len = fld.value.length;
	if (len > 8) return false;
	if (key == '-') {
	    if (len != 3 && len != 4) {
           return false;
        } else if(len == 4) {
           if (fld.value.indexOf('-') >= 0) return false;
        }
	} else {
	    if (strCheck.indexOf(key) == -1) return false;
	    if (len == 4) {
	       if (fld.value.indexOf('-') < 0) fld.value += '-';
	    } else if (len == 8) {
	       if (fld.value.indexOf('-') == 3) return false;
	    }
	}
	if (typeof(BROldValue) != 'undefined') {
		if (fld.value == BROldValue) { fld.value=''; }
	}


}

function checkFone(fone)
{

	var regex = /^[0-9]{3,4}[-, ]?[0-9]{4}$/;
	if (!regex.test(fone))
	{
	 return false;
	}
	return true;

}

// CEP //////////////////////////////////////////////////////////////////////////

function FormataCEP(fld, e)
{
	var key = '';
	var len = 0;
	var strCheck = '0123456789';
	if (fld.readOnly) return false;
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 0 || whichCode == 8) return true;
	key = String.fromCharCode(whichCode);
	if (strCheck.indexOf(key) == -1) return false;
	if (typeof(BROldValue) != 'undefined') {
		if (fld.value == BROldValue) { fld.value=''; }
	}
	len = fld.value.length;
	if (len > 8) return false;
	if (len == 5)
	 {
	    if (key == '-') {
	        return;
	     } else {
	        if (strCheck.indexOf(key) >= 0) {
	           fld.value += '-' + key;
	        }
	        return false;
	     }
	 }
}

function checkCEP(cep)
{

	var regex = /^[0-9]{5}-[0-9]{3}$/;
	if (!regex.test(cep))
	{
	 return false;
	}
	return true;

}

// Contabil //////////////////////////////////////////////////////////////////////////

function FormataContabil(fld, e, dec)
{
	var key = '';
	var i = j = n = 0;
	var len = 0;
	var stDec = stInt = '';
	var pDecSep = -1;
	var strCheck = '0123456789';
	if (fld.readOnly) return false;
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 0 || whichCode == 8) return true;

	var maxlen = fld.getAttribute('maxlength');
	if (isNaN(parseInt(maxlen,10)) || maxlen > 22) maxlen = 22;

	stValue = fld.value;

	if (typeof(BROldValue) != 'undefined') {
		if (stValue == BROldValue) { stValue=''; }
	}

	if (stValue.length >= maxlen) return false;

	dec = dec || 0;
	key = String.fromCharCode(whichCode);
    if (key == ',') {
    	if (dec > 0 ) {
    		pDecSep = stValue.length;
    	} else {
    		return false;
    	}
    } else {
    	if (strCheck.indexOf(key) >= 0) {
    		stValue += key;
    		pDecSep = stValue.indexOf(',');
    	} else {
    		return false;
    	}
    }

   	if (pDecSep < 0) pDecSep = stValue.length;
	//parte decimal, se houver
	if (dec > 0) {
	    for(i = pDecSep+1; i < stValue.length; i++) {
			if (strCheck.indexOf(stValue.charAt(i)) >= 0) stDec += stValue.charAt(i);
	    }
	}
	//verificar se já completou a parte decimal
	if (stDec.length > dec) {
		pDecSep += stDec.length - dec + 1;
		stDec = stDec.substr(stDec.length - dec);
	}
	//parte inteira
	//evitar 0 e , à esquerda
	for(n = 0; n < pDecSep-1; n++) {
		if (strCheck.indexOf(stValue.charAt(n)) > 0 && stValue.charAt(n) != '0') break;
	}
	//reformatar parte inteira
	j=0;
	for(i = pDecSep -1; i >=n; i--) {
		if (strCheck.indexOf(stValue.charAt(i)) >= 0) {
			if (j == 3) {
				stInt = '.' + stInt;
				j=1;
			} else {
				j++;
			}
			stInt = stValue.charAt(i) + stInt;
		}
	}
	if (stInt == '') stInt = '0';
	if (dec > 0) {
		if ((stInt.length + dec + 1) > maxlen) {
			if (stDec != '') {
				return false;
			} else {
				stInt = fld.value + "," + key;
			}
		}
		if (key == ',' || stDec != '') {
			stInt += ',' + stDec;
		}
	} else {
		if (stInt.length > maxlen) return false;
	}
	fld.value = stInt.substr(0, stInt.length - 1);
	// move o cursor para o final do campo

	if (fld.createTextRange) {
		var range = fld.createTextRange();
		range.collapse(false);
		range.select();
	}
	else if (fld.setSelectionRange) {
		fld.focus();
		var length = fld.value.length;
		fld.setSelectionRange(length, length);
	}
	return true;

}

function MaskContabil(stNumber, dec)
{
	var i = j = n = 0;
	var stDec = stInt = '';
	var strCheck = '0123456789';
	var pDecSep = -1;

	stNumber = stNumber || '';
	dec = dec || 0;
    pDecSep = stNumber.indexOf(',');
   	if (pDecSep < 0) pDecSep = stNumber.length;
	//parte decimal, se houver
	if (dec > 0) {
	    for(i = pDecSep+1; i < stNumber.length; i++) {
			if (strCheck.indexOf(stNumber.charAt(i)) >= 0) stDec += stNumber.charAt(i);
	    }
	}
	//verificar se já completou a parte decimal
	//trunca no numero de casas
	if (stDec.length > dec) {
		stDec = stDec.substr(0, dec);
	} else {
		//completar zeros
		n = dec - stDec.length;
		for(i = 0; i < n ; i++) {
			stDec += '0';
		}
	}
	//parte inteira
	//evitar 0 e , à esquerda
	for(n = 0; n < pDecSep-1; n++) {
		if (strCheck.indexOf(stNumber.charAt(n)) > 0 && stNumber.charAt(n) != '0') break;
	}
	//reformatar parte inteira
	stInt = '';
	j=0;
	for(i = pDecSep -1; i >=n; i--) {
		if (strCheck.indexOf(stNumber.charAt(i)) >= 0) {
			if (j == 3) {
				stInt = '.' + stInt;
				j=1;
			} else {
				j++;
			}
			stInt = stNumber.charAt(i) + stInt;
		}
	}
	if (stInt == '') stInt = '0';
	if (dec > 0) stInt += ',' + stDec;
	return stInt;
}


function checkContabil(cont)
{

	var regex = /^[0-9]{1,3}(\.?[0-9]{3})*(,[0-9]+)?$/;
	if (!regex.test(cont))
	{
	 return false;
	}
	return true;

}

function strToFloat(str) {
    var flt = str.replace(".", "");
    flt = flt.replace(",", ".");
    return parseFloat(flt);
}

function BRRangeContabilValidatorEvaluateIsValid(val)
{
    var ctrl  = dom_getAttribute(val, "controltovalidate");
    if (null == ctrl) return true;
    var Sval  = checkContabil(ctrl, ValidatorGetValue(ctrl)) ? ValidatorGetValue(ctrl) : '0,00';
	var value = parseFloat(Sval.replace(/\./g,'').replace(',','.'));
	var Smin  = checkContabil(ctrl, dom_getAttribute(val,"minimumvalue")) ? dom_getAttribute(val,"minimumvalue") : '0,00';
    var min   = parseFloat(Smin.replace(/\./g,'').replace(',','.'));
    var Smax  = checkContabil(ctrl, dom_getAttribute(val,"maximumvalue")) ? dom_getAttribute(val,"maximumvalue") : '0,00';
    var max   = parseFloat(Smax.replace(/\./g,'').replace(',','.'));
    return value >= min && value <= max;
}

function BRCompareContabilValidatorEvaluateIsValid(val) {
    var ctrl = dom_getAttribute(val, "controltovalidate");
    var ctrl = dom_getAttribute(val, "controltovalidate");
    if (null == ctrl) return true;
    var value = ValidatorGetValue(ctrl);
    if (ValidatorTrim(value).length == 0) return true;
    var ctrl2 = dom_getAttribute(val, "controltocompare");
    var compareTo = dom_getAttribute(val, "valuetocompare");
    if (compareTo == null) {
    	compareTo = ValidatorGetValue(ctrl2);
    }
    if (compareTo == "") return true;
    var decimals  = dom_getAttribute(val, "decimals");
    var multiplo  = dom_getAttribute(val, "multiplo");
    var operator  = dom_getAttribute(val, "operator");
    var op1 = value.contabilToFloat();
    var op2 = compareTo.contabilToFloat() * parseFloat(multiplo);
    op2 = Math.round(op2 * Math.pow(10, decimals)) / Math.pow(10, decimals);
    switch (operator) {
        case "NotEqual":
            return (op1 != op2);
        case "GreaterThan":
            return (op1 > op2);
        case "GreaterThanEqual":
            return (op1 >= op2);
        case "LessThan":
            return (op1 < op2);
        case "LessThanEqual":
            return (op1 <= op2);
        default:
            return (op1 == op2);
    }

}

// Inteiro //////////////////////////////////////////////////////////////////////////

function FormataInteiro(fld, e)
{
  var key = '';
  var intCheck = '0123456789';
  if (fld.readOnly) return false;
  var whichCode = (window.Event) ? e.which : e.keyCode;
  if (whichCode == 0 || whichCode == 8) return true;
  /*
  var maxlen = fld.getAttribute('maxlength');
  if (isNaN(parseInt(maxlen,10)) || maxlen > 50) maxlen = 50;
  var len = fld.value.length;
  if (len >= maxlen) return false;
  */
  key = String.fromCharCode(whichCode);
  if (intCheck.indexOf(key) < 0) {
      return false;
  }
}

function checkInteiro(num)
{

	var regex = /^[0-9]+$/;
	if (!regex.test(num))
	{
	 return false;
	}
	return true;

}

// Maxlength for TextArea ////////////////////////////////////////////////////////////

function textAreaLimit(field, maxlen) {
    if (field.value.length > maxlen) {
        field.value = field.value.substring(0, maxlen);
    }
}

// Se o Formulário foi alterado e não foi salvo //////////////////////////////////////

//Requires global associative array: arr_dirty
function isDirty() {
	var dirty = false;
	var val;
	var num = document.forms[0].elements.length;
	for (i=0;i<num;i++) {
		val = '';
		fld = document.forms[0].elements[i];
		if (fld.name != '') {
			if (fld.type == 'checkbox') {
				val = fld.checked ? '1' : '0';
			} else if (fld.type == 'radio') {
				radio = eval('document.forms[0].' + fld.name);
				for (j=0;j<radio.length;j++) {
					if (radio[j].checked) val = radio[j].value;
				}

			} else {
				val = fld.value;
			}
			if (typeof(arr_dirty[fld.name]) != 'undefined') {
				if (arr_dirty[fld.name] != val) {
				//alert(fld.name + ' -> ' + val + ' != ' + arr_dirty[fld.name]);
				dirty = true;
				break;
				}
			}
		}
	}
	return dirty;
}
