﻿/*
------------------------------------------------------------------------------------------
? Digital Industry - 2008
Autor:		Rafael Cronemberger de Assis
Cliente: 	Fitness Brasil
------------------------------------------------------------------------------------------
*/

// Global Variables
var nmOpacity 			= 100;
var fgNs4 				= (navigator.appName == 'Netscape') ? 1:0;

function showModal(stPage){
	var args 		= new Object;
	args.window 	= window;
	showModalDialog(stPage, args);
}

function dynamicSimpleValidate(objForm){
	var objElements 	= objForm.elements
	var nmElements 		= objForm.elements.length
	var objField;

	for(var nmInc = 0; nmInc < nmElements; nmInc++){
		try{
			var objField	= objElements[nmInc]

			var boValidate	= new Boolean(objField.getAttribute('boValidate'))
			var stValidate	= new String(objField.getAttribute('boValidate'))
			var stMsgError	= new String(objField.getAttribute('stMsgError'))
			var stFieldType	= new String(objField.getAttribute('stFieldType'))
			var stValue		= new String(objField.value)
			var stNome		= new String(objField.getAttribute('name'))

		}
		
		catch(stError){
			//alert(stError)
		}

		/* Valida??o Simples */
		if(stFieldType == 'null' || stFieldType == ''){
			if(stValidate == 'true' && stValue == ''){
				alert(stMsgError);
				objField.focus();
				return false;
			}
			
		/* Date */
		}else if(stFieldType == 'date'){
			if(CheckDate(stValue) == false){
				alert(stMsgError);
				objField.focus();
				return false;
			}
			
		/* E-mail */
		}else if(stFieldType == 'email'){
			if(validateRegexEmail(stValue) == false){
				alert(stMsgError);
				objField.focus();
				return false;
			}

		/* Numbers */
		}else if(stFieldType == 'number'){
			if(isNaN(stValue) || stValue == ''){
				alert(stMsgError);
				objField.focus();
				return false;
			}
	
		/* Select Multiple (Only for PHP) */
		}else if(stFieldType == 'select_multiple'){
			/* Check all fields. */
			selectElements(objField)
			
		
		}else if(stFieldType == 'radio'){
			if(verificaRadio(objForm, stNome) == false){
				alert(stMsgError);
				objField.focus();
				return false;
			}
		/* CPF */
		}else if(stFieldType == 'cpf'){
			if(validaCpf(stValue) == false){
				alert(stMsgError);
				objField.focus();
				return false;
			}
		}else if(stFieldType == 'youtube'){
			  if(validateRegexYoutube(stValue) == false){
				alert('Favor preencher o campo URL Youtube corretamente!\n\nEx: http://www.youtube.com/watch?v=XXXX');
				objField.focus();
				return false;
			  }
		}
			
			
		
		/* Hora */
		else if(stFieldType	== 'time'){
			if(validaHora(stValue) == false){
				alert(stMsgError);
				objField.focus();
				return false;
			}
		}
		
	   	else if(stFieldType == 'cnpj'){
	   		if(validaCNPJ(stValue) == false){
	   			alert(stMsgError);
	   			objField.focus();
	   			return false;
	   		}
	   	}
       
       else if(stFieldType == 'checkbox' && objField.type == 'checkbox'){
           if(objField.checked == false){
               alert(stMsgError);
               objField.focus();
               return false;
           }
       }
		
	}
}

function verificaRadio(objForm, stNome){
	var nmCount = 0, nmErro = 0;
	//validacao de radio buttons sem saber quantos sao
	for(nmInc = 0; nmInc < objForm.length; nmInc++){ // loop de elementos do formulário
		if(objForm.elements[nmInc].type == 'radio' && objForm.elements[nmInc].name == stNome){ // verifica se é do tipo radio e o nome é igual ao enviado
			nmCount++; // conta o número de radios com o mesmo nome
			if(objForm.elements[nmInc].checked == false){ // verifica se está checkado
				nmErro += 1;
			}
		}
	}
	if(nmCount == nmErro){
		return false;
	}else{
		//return true;
	}
}

function selectElements(objElement){
	var nnInc				= 0;
	var nmCount				= objElement.length;
	for(nmInc = 0; nmInc < nmCount; nmInc ++){
		objElement[nmInc].selected = true
	}
}

function redirectUser(stDestino){
	document.location.href=(stDestino)
}

function openCenterPopup(stUrl, stWindowName, stParameters, nmWidth, nmHeight){
	stWindowParameters 	= ', width='+nmWidth+', height='+nmHeight+'';
	stParameters		= stParameters += stWindowParameters;
	objPopUp 			= window.open(stUrl, stWindowName, stParameters)

	try{
		centerObject(objPopUp, nmWidth, nmHeight)
	}catch(ex){}
	
	objPopUp.focus();
}

function centerObject(objElement, nmWidth, nmHeight){
	try{
		/* Popups */
		var nmX	= (screen.width - nmWidth) / 2;
		var	nmY = (screen.height - nmHeight) / 2;

		objElement.moveTo(nmX, nmY)
	}
	catch(ex){
		/* Elements */
		var nmLeft	= (screen.width - nmWidth) / 2;
		var	nmTop 	= ((screen.height - nmHeight) / 2) + (parseInt(document.documentElement.scrollTop) / 2);
		//var	nmTop 	= (	parseInt(document.body.scrollTop)	+	parseInt(document.body.offsetHeight / 2) );
		objElement.style.left 	= nmLeft;
		objElement.style.top 	= nmTop;
	}
}

function maskCurrency(objTextBox, stSeparadorMilesimo, stSeparadorDecimal, e){
	var nmSep 		= 0;
	var stKey 		= '';
	var 			i = j = 0;
	var nmLen 		= nmLen2 = 0;
	var stCheck 	= '0123456789';
	var stAuxiliar 	= stAuxiliar2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;

	if(whichCode == 13) return true;
	stKey = String.fromCharCode(whichCode);

	if(stCheck.indexOf(stKey) == -1) return false;
	nmLen = objTextBox.value.length;
	
	for(i = 0; i < nmLen; i++)
		if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != stSeparadorDecimal)) break;

	stAuxiliar = '';

	for(; i < nmLen; i++)
		if (stCheck.indexOf(objTextBox.value.charAt(i))!=-1) stAuxiliar += objTextBox.value.charAt(i);
	
	stAuxiliar 	+= stKey;
	nmLen 		= stAuxiliar.length;

	if (nmLen == 0) objTextBox.value = '';
	if (nmLen == 1) objTextBox.value = '0'+ stSeparadorDecimal + '0' + stAuxiliar;
	if (nmLen == 2) objTextBox.value = '0'+ stSeparadorDecimal + stAuxiliar;
	if (nmLen > 2){
	stAuxiliar2 = '';

	for (j = 0, i = nmLen - 3; i >= 0; i--){
		if (j == 3){
			stAuxiliar2 += stSeparadorMilesimo;
			j = 0;
		}
		stAuxiliar2 += stAuxiliar.charAt(i);
		j++;
	}

	objTextBox.value	=	'';

	nmLen2 = stAuxiliar2.length;

	for (i = nmLen2 - 1; i >= 0; i--)
		objTextBox.value += stAuxiliar2.charAt(i);
		objTextBox.value += stSeparadorDecimal + stAuxiliar.substr(nmLen - 2, nmLen);
	}
	return false;
}

function resetDropDown(objDropDown){
	objDropDown.options.length = 0;
}

function formatCurrency(nmValor){
	nmValor = nmValor.toString().replace(/\$|\,/g,'');
	if(isNaN(nmValor)) nmValor = "0";

	fgValor 	= (nmValor == (nmValor = Math.abs(nmValor)));
	nmValor 	= Math.floor(nmValor * 100 + 0.50000000001);
	nmCentavos 	= nmValor % 100;
	nmValor = Math.floor(nmValor/100).toString();
	if(nmCentavos < 10) nmCentavos = "0" + nmCentavos;
	
	for (var i = 0; i < Math.floor((nmValor.length-(1+i)) / 3); i++)
	nmValor 	= nmValor.substring(0,nmValor.length-(4*i+3))+'.'+

	nmValor.substring(nmValor.length-(4*i+3));
	return (((fgValor)?'':'-') + 'R$ ' + nmValor + ',' + nmCentavos);
}

function timeOut(nmSeconds, stAction){
	alert(stAction)
	window.setTimeout(stAction, nmSeconds);	
}

function showHideElement(objElement, fgDisplay){
	if(fgDisplay == 1)
		objElement.style.display = ''
	else
		objElement.style.display = 'none'
}

function BlockUnblockElement(objElement, fgBlock){
	if(fgBlock == 1)
		objElement.disabled = false
	else
		objElement.disabled = true
}

function validateRegexEmail(stEmail){
	if(!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(stEmail)){
		return false;
	}
}

function displayFlash(nmWidth, nmHeight, stSwf){
	document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="'+nmWidth+'" height="'+nmHeight+'" id="objFlash" align="middle">');
	document.write('<param name="allowScriptAccess" value="sameDomain" /><param name="wmode" value="transparent" />');
	document.write('<param name="movie" value="'+stSwf+'" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><embed src="'+stSwf+'" wmode="transparent" quality="best" width="'+nmWidth+'" height="'+nmHeight+'" name="div" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash"/>');
	document.write('</object>');
}

function FieldOnFocus(objForm, stFieldValue){
	if(eval(objForm).value == stFieldValue){
		eval(objForm).value = '';
	}
}

function FieldOnBlur(objForm, stFieldValue){
	if(eval(objForm).value == ''){
		eval(objForm).value = stFieldValue;
	}
}

function Ltrim(stValue) {
	var re = /\s*((\S+\s*)*)/;
	return stValue.replace(re, '$1');
}

function Rtrim(stValue) {
	var re = /((\s*\S+)*)\s*/;
	return stValue.replace(re, '$1');
}

function Trim(stValue){
	stValue = Ltrim(Rtrim(stValue));
	return stValue.replace(/^\s+|\s+$/g, '');
}

function FadeElement(idElement, stMethod, nmVelocity){
	var objElement	= document.getElementById(idElement)
	if(objElement){
		if(nmOpacity == 100 && stMethod == 'in') nmOpacity = 10; fgContinue	= true; showHideElement(objElement, 1);
	
		if(nmOpacity > 0){
			if(stMethod == 'in'){
				fgDisplay = 	1;
				nmOpacity += 	10;
			}else{
				fgDisplay 	= 	0;
				nmOpacity -= 	10
			}
			fgContinue	= true;
		}else{
			fgContinue	= false;
		}
		
		if(nmOpacity == 100 && stMethod == 'in') fgContinue = false;
	
		if(fgContinue == true){
			objElement.style.filter = 'alpha(style=0,opacity=' + nmOpacity + ')';
			objTimer  				= setTimeout ("FadeElement('"+idElement+"', '"+stMethod+"', "+nmVelocity+");", nmVelocity);
		}else{
			showHideElement(objElement, fgDisplay)
			nmOpacity 				= 100;
			objElement.style.filter = 'alpha(style=0,opacity=' + nmOpacity + ')';
		}
	}
}

function BlockChars(){
	if(!fgNs4){
		if(event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;
	}else{
		if(event.which < 45 || event.which > 57) returnfalse;
	}
}

function BlockSpecialChars(){
	if(!fgNs4){
		if ((event.keyCode > 32 && event.keyCode < 48) || (event.keyCode > 57 && event.keyCode < 65) || (event.keyCode > 90 && event.keyCode < 97)) event.returnValue = false;
	}else{
		if((event.which > 32 && event.which < 48) || (event.which > 57 && event.which < 65) || (event.which > 90 && event.which < 97)) return false;
	}
}

function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;   
    if((tecla>47 && tecla<58)) return true;
    else{
        if (tecla==8 || tecla==0) return true;
    else  return false;
    }
}

function DataChars(){
	if(!fgNs4){
		if(event.keyCode < 48 || event.keyCode > 57){
			event.returnValue = false;
		}
	}
}

function CheckDate(stDate){
	var arrayDate		= stDate.split("/");
	var stCheck 		= '0123456789';
	var stDateTemp 		= '';
	var stSeparator 	= '/';
	var nmDay			= arrayDate[0];
	var nmMonth			= arrayDate[1];
	var nmYear			= arrayDate[2];
	var nmLoop 			= 0;
	var nmError 		= 0;
	var nmInc;
	var nmData			= new Date();
	nmData				= nmData.getFullYear();
	nmData				= nmData + 3;

	for (nmInc = 0; nmInc < stDate.length; nmInc++) {
		if (stCheck.indexOf(stDate.substr(nmInc,1)) >= 0) {
			stDateTemp = stDateTemp + stDate.substr(nmInc,1);
		}
	}
	
	stDate = stDateTemp;
	
	if (stDate.length == 6)					stDate = stDate.substr(0,4) + '20' + stDate.substr(4,2);
	nmYear 	= stDate.substr(4,4);

	if (nmYear == 0) 						nmError = 1;

	if ((nmMonth < 1) || (nmMonth > 12)) 	nmError = 1;

	if (nmDay < 1) 							nmError = 1;
	if ((nmYear % 4 == 0) || (nmYear % 100 == 0) || (nmYear % 400 == 0)) 	nmLoop = 1;
	if ((nmMonth == 2) && (nmLoop == 1) && (nmDay > 29)) 					nmError = 1;
	if ((nmMonth == 2) && (nmLoop != 1) && (nmDay > 28)) 					nmError = 1;
	if ((nmDay > 31) && ((nmMonth == 1) || (nmMonth == 3) || (nmMonth == 5) || (nmMonth == 7) || (nmMonth == 8) || (nmMonth == 10) || (nmMonth == 12))) nmError = 1;
	if ((nmDay > 30) && ((nmMonth == 4) || (nmMonth == 6) || (nmMonth == 9) || (nmMonth == 11))) nmError = 1;
	if (nmYear > nmData) nmError = 1;
	if ((nmDay == 0) && (nmMonth == 0) && (nmYear == 00)) nmError = 0; nmDay = ''; nmMonth = ''; nmYear = ''; stSeparator = '';

	if(stDate.length != 8 && stDate.length != 7) nmError = 1;

	if (nmError == 0) {
		return true;
	}else{
		return false;
	}
}

function mascaraData(objField){
	var stDate = objField.value;
	if (stDate.length == 2){
		stDate = stDate + '/';
		objField.value = stDate;
		return true;
	}
	if (stDate.length == 5){
		stDate = stDate + '/';
		objField.value = stDate;
	return true;
	}
}

function resetForm(objForm){
	objForm.reset();
}

function DeleteItemParam(stParameters){
	if(confirm('Este item só sera excluido se não estiver mais relaionado a outras categorias')){
		location.href=(stParameters)
	}
}

function DeleteItem(stParameters){
	if(confirm('Tem certeza que deseja excluir este item? Todos os itens ligados a ele serão excluídos também!')){
		location.href=(stParameters)
	}
}

function ItemInativo(stParameters){
	if(confirm('Tem certeza que deseja inserir um item como inativo?')){
		location.href=(stParameters)
	}
}

function deleteConfirm(stParameters){
	if(confirm('Tem certeza que deseja excluir este item?')){
		location.href=(stParameters)
	}
}




function Timer(nmSeconds, stAction){
	window.setTimeout(stAction, nmSeconds);	
}

function teste(objField){
	if(objField.value) Timer(2000, 'Resgate();');
}

function Resgate(){
	alert(1)
	var objField
	var stCpf
	var stValue = objField.value
	
	alert(stValue)

	objField 		= document.frmDados.nmCpf
	stValue			= objField.value
	alert(stValue)

	objField.value	= stValue.replace(".", "");
}



function moveSelectItem(fbox, tbox){
	var arrFbox = new Array();
	var arrTbox = new Array();
	var arrLookup = new Array();
	var i;
	for (i = 0; i < tbox.options.length; i++){
		arrLookup[tbox.options[i].text] = tbox.options[i].value;
		arrTbox[i] = tbox.options[i].text;
	}

	var fLength = 0;
	var tLength = arrTbox.length;
	for(i = 0; i < fbox.options.length; i++) {
		arrLookup[fbox.options[i].text] = fbox.options[i].value;
		if (fbox.options[i].selected && fbox.options[i].value != "") {
			arrTbox[tLength] = fbox.options[i].text;
			tLength++;
		}else{
			arrFbox[fLength] = fbox.options[i].text;
			fLength++;
	   }
	}
	
	arrFbox.sort();
	arrTbox.sort();

	fbox.length = 0;
	tbox.length = 0;
	
	var c;
	for(c = 0; c < arrFbox.length; c++) {
		var no = new Option();
		no.value = arrLookup[arrFbox[c]];
		no.text = arrFbox[c];
		fbox[c] = no;
	}

	for(c = 0; c < arrTbox.length; c++){
		var no = new Option();
		no.value = arrLookup[arrTbox[c]];
		no.text = arrTbox[c];
		tbox[c] = no;
	}
}

function validaCpf(stCpf) {
	stCpf 	= stCpf.replace(".", "");
	stCpf 	= stCpf.replace(".", "");
	stCpf 	= stCpf.replace("-", "");
	nmErro 	= new Number;
	nmErro	= 0;

	if (stCpf.length < 11) nmErro ++;
	var nonNumbers = /\D/;
	if (nonNumbers.test(stCpf)) nmErro ++;
	if (stCpf == "00000000000" || stCpf == "11111111111" || stCpf == "22222222222" || stCpf == "33333333333" || stCpf == "44444444444" || stCpf == "55555555555" || stCpf == "66666666666" || stCpf == "77777777777" || stCpf == "88888888888" || stCpf == "99999999999"){
			nmErro ++;
	}
	var a = [];
	var b = new Number;
	var c = 11;
	for (i=0; i<11; i++){
		a[i] = stCpf.charAt(i);
		if (i < 9) b += (a[i] *  --c);
	}
	if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
	b = 0;
	c = 11;
	for (y=0; y<10; y++) b += (a[y] *  c--); 
	if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
	if ((stCpf.charAt(9) != a[9]) || (stCpf.charAt(10) != a[10])){
		nmErro ++;
	}

	if (nmErro > 0){
		return false
	}
}

function upperCase(stParameter){
	return stParameter.toUpperCase();
}



function mascaraHora(objField){
	var nmHora;
	nmHora	= objField.value;
	if (nmHora.length == 2){
		nmHora = nmHora + ':';
		objField.value = nmHora;
	}
}

function validaHora(stValue){
	var nmHora	= (stValue.substring(0,2));
	var nmMin	= (stValue.substring(3,5));
	var nmErro 	= 0;
	if ((nmHora < 00 || nmHora > 23) || (nmMin < 00 || nmMin > 59)){
		nmErro 	= 1;
	}else if(stValue.length  != 5){
		nmErro 	= 1;
	}
	if (nmErro == 1){
		return false;
	}
}

function validaCNPJ(stCnpj) {
	CNPJ = stCnpj
    erro = new String;
    if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\n"; 
    if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
    	if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
    }
    //substituir os caracteres que não são números
    if(document.layers && parseInt(navigator.appVersion) == 4){
    	x = CNPJ.substring(0,2);
    	x += CNPJ. substring (3,6);
    	x += CNPJ. substring (7,10);
    	x += CNPJ. substring (11,15);
    	x += CNPJ. substring (16,18);
    	CNPJ = x; 
    }else {
    	CNPJ = CNPJ. replace (".","");
    	CNPJ = CNPJ. replace (".","");
    	CNPJ = CNPJ. replace ("-","");
    	CNPJ = CNPJ. replace ("/","");
    }
    var nonNumbers = /\D/;
   	if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n"; 
   	var a = [];
   	var b = new Number;
   	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
   	for (i=0; i<12; i++){
   		a[i] = CNPJ.charAt(i);
   		b += a[i] * c[i+1];
   	}
   	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
   		b = 0;
   		for (y=0; y<13; y++) {
   			b += (a[y] * c[y]); 
   		}
   		if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
   		if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
   			erro +="Dígito verificador com problema!";
   		}
   		if (erro.length > 0){
   			//alert(erro);
   			return false;
   		}else{
   			//alert("CNPJ valido!");
   		}
   		return true;
}

	function clear_form_elements(ele) {
	  $(ele).find(':input').each(function() {
		  switch(this.type) {
			  case 'password':
			  case 'select-multiple':
			  case 'select-one':
			  case 'text':
			  case 'textarea':
				  $(this).val('');
				  break;
			  case 'checkbox':
			  case 'radio':
				  this.checked = null;
		  }
	  });
	}
	
	function Compara_Datas(data_inicial, data_final){  
 	//Verifica se a data inicial é maior que a data final  
    var data_inicial = document.getElementById(data_inicial);  
    var data_final   = document.getElementById(data_final); 
    str_data_inicial = data_inicial.value;  
    str_data_final   = data_final.value;  
    dia_inicial      = data_inicial.value.substr(0,2);  
    dia_final        = data_final.value.substr(0,2);  
    mes_inicial      = data_inicial.value.substr(3,2);  
    mes_final        = data_final.value.substr(3,2);  
    ano_inicial      = data_inicial.value.substr(6,4);  
    ano_final        = data_final.value.substr(6,4);  
    if(ano_inicial > ano_final){  
        alert("A data inicial deve ser menor que a data final.");   
        data_inicial.focus();  
        return false  
    }else{  
    if(ano_inicial == ano_final){  
    if(mes_inicial > mes_final){  
    alert("A data inicial deve ser menor que a data final.");  
                data_final.focus();  
                return false  
            }else{  
                if(mes_inicial == mes_final){  
                    if(dia_inicial > dia_final){  
                        alert("A data inicial deve ser menor que a data final.");  
                        data_final.focus();  
                        return false  
                    }  
                }  
            }  
        }  
    }  
}  

function valorPadraoLimpaCampo(id, textoPadrao, textoAtual)
{
	obj = document.getElementById(id);
	
	if((obj != null && obj != undefined) && textoPadrao == textoAtual)
	{
		obj.value = "";			
	}
}

function validateRegexYoutube(stEmail){
    if(!/[\\?\\&]v=([^\\?\\&]+)/.test(stEmail)){
        return false;
    }
}

function checkSenha(idSenha, idSenhaCompara, callback)
{
	senha			= document.getElementById(idSenha).value;
	confirmaSenha	= document.getElementById(idSenhaCompara).value;
	
	if(senha != null && confirmaSenha != null)
	{
		
		if(senha != confirmaSenha)
		{
			alert('As senhas não conferem');
			return false;
		}

	}
	
	return eval(callback);
}

