// ------- Scripts globais --------------
// Validações
// Checa o email
function checkEmail( campo ) {
	if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(campo.value)) || campo.value == "") return(false); else return(true);
}
// Função para marcar/desmarcar todos checkbox do form
function checkAll(form,check) {
   for (var i=0;i<form.elements.length;i++) {
     var x = form.elements[i];
     if (x.name == check) { x.checked = form.todos.checked;}
   }
}
// Checa a validade da data
function checkDate( field,event )
{
	var checkstr = "0123456789";
	var DateField = field;
	var Datevalue = "";
	var DateTemp = "";
	var seperator = "/";
	var day;
	var month;
	var year;
	var leap = 0;
	var err = 0;
	var i;
	err = 0;
	DateValue = DateField.value;
	/* Delete all chars except 0..9 */
	for( i = 0; i < DateValue.length; i++ ) {
		if( checkstr.indexOf( DateValue.substr( i, 1 ) ) >= 0 ) {
			DateTemp = DateTemp + DateValue.substr( i, 1 );
		}
	}
	DateValue = DateTemp;
	/* Always change date to 8 digits - string*/
	/* if year is entered as 2-digit / always assume 20xx */
	if( DateValue.length == 6 ) {
		DateValue = DateValue.substr( 0, 4 ) + '20' + DateValue.substr( 4, 2 );
	}
	if( DateValue.length != 8 ) {
		err = 19;
	}
	/* year is wrong if year = 0000 */
	year = DateValue.substr( 4, 4 );
	if( year == 0 ) {
		err = 20;
	}
	/* Validation of month*/
	month = DateValue.substr( 2, 2 );
	if( ( month < 1 ) || ( month > 12 ) ) {
		err = 21;
	}
	/* Validation of day*/
	day = DateValue.substr( 0, 2 );
	if( day < 1 ) {
		err = 22;
	}
	/* Validation leap-year / february / day */
	if( ( year % 4 == 0 ) || ( year % 100 == 0 ) || ( year % 400 == 0 ) ) {
		leap = 1;
	}
	if( ( month == 2 ) && (leap == 1) && ( day > 29 ) ) {
		err = 23;
	}
	if( ( month == 2 ) && (leap != 1) && ( day > 28 ) ) {
		err = 24;
	}
	/* Validation of other months */
	if( ( day > 31 ) && ( ( month == "01" ) || ( month == "03" ) || ( month == "05" ) || ( month == "07" ) || ( month == "08" ) || ( month == "10" ) || ( month == "12" ) ) ) {
		err = 25;
	}
	if( ( day > 30 ) && ( ( month == "04" ) || ( month == "06" ) || ( month == "09" ) || ( month == "11" ) ) ) {
		err = 26;
	}
	/* if 00 ist entered, no error, deleting the entry */
	if( ( day==0 ) && ( month==0 ) && ( year==00 ) )  {
		err = 0;
		day = "00";
		month = "00";
		year = "0000";
	}

	/* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
	if( err == 0 ) {
		return true;
		/* Error-message if err != 0 */
	}
	else {
		event.returnValue = false;
		alert("Data inválida !!!");//return false;
		field.value = '';
	}
	/* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
//	if( err == 0 ) {
//		if( retorna == true ) {
//			return year + month + day;
//		}
//		else {
//			return true;
//		}
		/* Error-message if err != 0 */
//	}
//	else return false;
}

// Checa a validade da data
function checkHour( field,event ){
	var checkstr = "0123456789";
	var DateField = field;
	var Datevalue = "";
	var DateTemp = "";
	var seperator = ":";
	var hour;
	var min;
	var leap = 0;
	var err = 0;
	var i;
	err = 0;
	DateValue = DateField.value;
	/* Delete all chars except 0..9 */
	for( i = 0; i < DateValue.length; i++ ) {
		if( checkstr.indexOf( DateValue.substr( i, 1 ) ) >= 0 ) {
			DateTemp = DateTemp + DateValue.substr( i, 1 );
		}
	}
	DateValue = DateTemp;

	if( DateValue.length < 4 ) {
		err = 10;
	}
	hours = DateValue.substr(0,2);
	minu = DateValue.substr(2,2);
	/* Validation of hour*/
	if( (hour < 0) || (hour > 23) ) {
		err = 10;
	}
	/* Validation of minute*/
	if((min < 0) || (min > 59)) {
		err = 10;
	}
	/* if 00 ist entered, no error, deleting the entry */
	if( (( hour == 0 ) && ( min == 0 )) || DateValue=='' ) {
		err = 0;
		hour = "00";
		min = "00";
	}
	/* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
	if( err == 0 ) {
		return true;
		/* Error-message if err != 0 */
	}
	else {
		event.returnValue = false;
		alert("Hora inválida !!!");//return false;
		field.value = '';
	}
}
// Compara as datas
function compDateAlt( Data, Comp ){
	// se a data for menor que o comparativo, retorna true (para a pagina de notas.asp)
	DataValue = checkDate( Data, true );
	CompValue = checkDate( Comp, true );
	if( DataValue < CompValue ) return true;
	else return false;
}
/**
* Compara as datas passadas
*/
function compDate(DataBase,DataComp,Equal)
{
	// dt1 e dt2: Devem ser tipo String, para evitar confusao de tipos
	if(typeof DataComp != "string" || typeof DataBase != "string")
	{
		alert("As datas devem ser passadas como strings");
		return true;
	}

	if(DataBase=='HOJE')
	{
		var objData = new Date();
		DataBase	= objData.getDate()+'/'+objData.getMonth()+'/'+objData.getFullYear();
	}

	arrayDataBase = DataBase.split('/');
	arrayDataComp = DataComp.split('/');

	DataBaseUS = arrayDataBase[1]+'/'+arrayDataBase[0]+'/'+arrayDataBase[2];
	DataCompUS = arrayDataComp[1]+'/'+arrayDataComp[0]+'/'+arrayDataComp[2];

	// Instanciamos as datas, para poder usar getTime();
	dataB = new Date(DataBaseUS);
	dataC = new Date(DataCompUS);

	if(!dataB || !dataC)
	{
		alert("Erro ao criar objetos Date");
		return true;
	}

	// milliSegundos
	milliSegundosB = dataB.getTime();
	milliSegundosC = dataC.getTime();

	// Comparando millisegundos
	if(Equal && (milliSegundosB == milliSegundosC))
	{
		return true;
	}
	else if(milliSegundosB > milliSegundosC)
	{
		return true;
	}
	else {return false;}
}

//================================================
/*//// FORMATAÇÕES ////*/
//================================================
// Formata telefone
function formatFone( campo, teclapres ) {
	var tecla = teclapres.keyCode;
	var vr = campo.value;
	vr = vr.replace( "(", "" );
	vr = vr.replace( ")", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( " ", "" );
	tam = vr.length;
	if( (tecla >= 48 && tecla <= 57 ) || ( tecla >= 96 && tecla <= 105 ) ){
		if( ( tam > 4 ) && ( tam <= 8 ) ){
			campo.value = vr.substr( 0, tam - 4 ) + '-' + vr.substr( tam - 4, tam );
		}
		if( ( tam >= 9 ) ){
			campo.value = '(' + vr.substr( 0, tam - 8 ) + ') ' + vr.substr( tam - 8, 4 ) + '-' + vr.substr( tam - 4, tam ) ;
		}
	}
}
// Formata CEP
function formatCEP( campo, teclapres ) {
	var tecla = teclapres.keyCode;
	var vr = campo.value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "-", "" );
	vr = vr.replace( " ", "" );
	tam = vr.length;
	if( (tecla >= 48 && tecla <= 57 ) || ( tecla >= 96 && tecla <= 105 ) ){
		if( ( tam > 3 ) && ( tam <= 5 ) ){
			campo.value = vr.substr( 0, tam - 3 ) + '.' + vr.substr( tam - 3, tam );
		}
		if( ( tam > 5 ) ){
			campo.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, 3 ) + '-' + vr.substr( 5, 3 ) ;
		}
	}
}
// Formata data
function formatDate( vdata, vEvent )
{
	var checkstr = "0123456789";
	var Datevalue = "";
	var DateTemp = "";
	var seperator = "/";
	var day;
	var month;
	var year;
	var leap = 0;
	var err = 0;
	var i;

	if( !isNum(vEvent) || vdata.value.length > 10 ) err = 10;

	isNav4 = navigator.appName == "Netscape" && navigator.appVersion < "5";
	if (!isNav4) {
		if (vdata.value.length == 2 || vdata.value.length == 5)
			if (vEvent.keyCode != 46)
				if (vEvent.keyCode != 8)
					vdata.value = vdata.value + ((vdata.value.length == 2)?"/":"/");
		else vdata.value = vdata.value.substr(0,vdata.value.length-1);
	}
	else
		if (vdata.value.length == 10)
			vdata.value = vdata.value.substr(0,2) + "/" +
			vdata.value.substr(2,2) + "/" +
			vdata.value.substr(4,4);
}

// Formata hora
function formatHour( vdata,vEvent ) {
	var err = 0;

	if(!isNum(vEvent)||vdata.value.length>4) err = 10;

	/* Validation of hours*/
	isNav4 = navigator.appName == "Netscape" && navigator.appVersion < "5";

	if (!isNav4) {
		if (vdata.value.length == 2)
			if (vEvent.keyCode != 46)
				if (vEvent.keyCode != 8)
					vdata.value = vdata.value + ((vdata.value.length == 2)?":":":");
		else vdata.value = vdata.value.substr(0,vdata.value.length-1);
	}
	else
		if (vdata.value.length == 5)
			vdata.value = vdata.value.substr(0,2) + ":" +
			vdata.value.substr(2,2);

	if(vdata.value.length >= 4){
		hours = vdata.value.substr(0,2);
		minutes = vdata.value.substr(3,2);
		unidade = vdata.value.substr(3,1);

		/* Validation of hour*/
		if( (hours < 0) || (hours > 23) ) {
			err = 20;
		}
		/* Validation of minute*/
		if((minutes < 0) || (minutes > 59) || (unidade > 5)) {
			err = 20;
		}
	}

	if(err!=0){
		vEvent.returnValue = false;
		if( (err==20) || (err==21) )
			alert("Hora inválida !!!");
	}
}
// Formata o CNPJ
function formatCNPJ( campo, tammax, teclapres ) {

	var tecla = teclapres.keyCode;
	var vr = campo.value;
	vr = vr.replace( "-", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;

	if (tam < tammax && tecla != 13){ tam = vr.length + 1 ; }

	if (tecla == 13 ){	tam = tam - 1 ; }

	if ( tecla == 13 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105) ){
		if ( tam <= 2 ){
			campo.value = vr ; }
			tam = tam - 1;
			if ( (tam > 2) && (tam <= 5) ){
				campo.value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
				if ( (tam >= 6) && (tam <= 8) ){
					campo.value = vr.substr( 0, tam - 6 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
					if ( (tam >= 9) && (tam <= 11) ){
						campo.value = vr.substr( 0, tam - 9 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }
						if ( (tam >= 12) && (tam <= 14) ){
							campo.value = vr.substr( 0, tam - 12 ) + '.' + vr.substr( tam - 12, 3 ) + '.' + vr.substr( tam - 9, 3 ) + '/' + vr.substr( tam - 6, 4 ) + '-' + vr.substr( tam - 2, tam ) ; }

	}
}

// Ajusta o valor para duas casa decimais
function ajusVal(valor) {
	valor = parseFloat(valor);
	if (valor<=0.99) {
		newDollar = '0';
	} else {
		newDollar = parseInt(valor);
	}
	newCent = parseInt((valor+.0008 - newDollar)* 100);
	if (eval(newCent) <= 9) newCent='0'+newCent;
	newString = newDollar + '.' + newCent;
	return (newString);
}
// Formata o field para para moeda
function formatValue(fld,coin,e) {
	var sep = 0;
	var key = milSep = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var decSep = '.';

	if(coin='BRL')
	{
		milSep = '.';
		decSep = ',';
	}
	else if(coin='USD')
	{
		milSep = ',';
		decSep = '.';
	}
	else
	{
		milSep = '';
		decSep = '.';
	}

	var whichCode = (window.Event) ? e.which : e.keyCode;

	if (whichCode == 13) return true;  // Enter
	//if (e.which) return fld.value = '0'+ decSep + '00';  // ESC
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key

	len = fld.value.length;
	for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';
	for(; i < len; i++)
		if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
		fld.value += aux2.charAt(i);
		fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}

// Formata o valor inteiro
function formatInt(fld, milSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;

	if (whichCode == 13) return true;  // Enter
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	len = fld.value.length;
	for(i = 0; i < len; i++)
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != milSep)) break;
	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	//	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	//	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 0) {
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
		fld.value += aux2.charAt(i);
		//		fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}
// Formata o valor para o especificado
function moneyFormat(valor,milSep,decSep) {
	var inteiro = parseInt(valor);
	var len = inteiro.toString().length;
	var novovalor = "";

	//alert("Inteiro:"+inteiro);
	//alert("Tamanho:"+len);

	for(i=0;i<len;i++){
		//alert(valor.substr(i,1));
		if((len>3&&i==(len-3))||(len>6&&i==(len-6))||(len>9&&i==(len-9)))
			novovalor += milSep+valor.substr(i,1).toString();
		else novovalor += valor.substr(i,1).toString();
	}

	novovalor = novovalor+decSep+valor.substr(valor.length-2,2);

	return novovalor;
}

// converte o valor na moeda passada ou para o padrão do sistema
function converteMoeda(Valor,Moeda){
	Valor = Valor.toString();

	var ponto = Valor.indexOf(".");
	var virgula = Valor.indexOf(",");

	if(virgula==-1) var base = ""; // Base sistema
	else if(ponto<virgula){ // Base BRL
		Valor = Valor.replace(".","|");
		Valor = Valor.replace(".","|");
		Valor = Valor.replace(".","|");
		Valor = Valor.replace(",",".");
		Valor = Valor.replace(",",".");
		Valor = Valor.replace(",",".");
		Valor = Valor.replace("|","");
		Valor = Valor.replace("|","");
		Valor = Valor.replace("|","");
	}
	else{ // Base USD
		Valor = Valor.replace(",","");
		Valor = Valor.replace(",","");
		Valor = Valor.replace(",","");
		Valor = Valor.replace(",","");
	}
	//alert("Valor sem ajusVal:"+Valor);
	if(Valor!='') Valor = ajusVal(Valor);
	else Valor = '0.00';
	//alert("Valor com ajusVal:"+Valor);

	//1,000.00
	// 1000.00
	//1.000,00

	if(Moeda=="BRL"){
		Valor = moneyFormat(Valor,".",",");
	}
	else if(Moeda=="USD") {
		Valor = moneyFormat(Valor,",",".");
	}
	else Valor = parseFloat(moneyFormat(Valor,"","."));

	//alert(Valor);

	return Valor;
}

/**
* Funcção para incluir um arquivo
*/
function include(arquivo)
{
	var novo = document.createElement("<script>");
 	novo.setAttribute('type', 'text/javascript');
 	novo.setAttribute('src', arquivo);
 	document.getElementsByTagName('body')[0].appendChild(novo);
}
