// JavaScript Document
function isNumber(pValor){ if(!isNaN(pValor)){return true;}else{return false;}}

function isEmail(email){
	if (email.length != 0) {
		if (email.indexOf("@") != -1) {
			if (email.lastIndexOf(".") > email.indexOf("@")) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function isDate(date){
	
	if(parseInt(date.length) != 10) {
		return false;
	}
	
	if(date.substring(0,2) > 31 || date.substring(3,5) > 12) {
		return false;
	}
	
	return true;
}

function isCPF(cpf) {
	
	var cpf = cpf.replace(".", "");
	var cpf = cpf.replace(".", "");
	var cpf = cpf.replace("-", "");
	
	isValid = true;
	
	if (cpf.length != 11 || cpf == "___.___.___-__" || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999") {
		isValid = false;
	}
	
	add = 0;
	for (i=0; i < 9; i ++){
		add += parseInt(cpf.charAt(i)) * (10 - i);
		rev = 11 - (add % 11);
	}
	
	if (rev == 10 || rev == 11) rev = 0;
	if (rev != parseInt(cpf.charAt(9))) isValid = false;
	
	add = 0;
	for (i = 0; i < 10; i ++){
		add += parseInt(cpf.charAt(i)) * (11 - i);
		rev = 11 - (add % 11);
	}
	
	if (rev == 10 || rev == 11) rev = 0;
	if (rev != parseInt(cpf.charAt(10))) isValid = false;
	
	//alert(isValid);
	return isValid;
}


function isCNPJ(cnpj){
 
	if(cnpj != '__.___.___/____-__'){
		
		cnpj = cnpj.replace('.','').replace('.','').replace('-','').replace('/','');
		
		var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
		
		digitos_iguais = 1;
		
		if (cnpj.length < 14 && cnpj.length < 15){
			return false;
		}
		
		for (i = 0; i < cnpj.length - 1; i++)
		
		if (cnpj.charAt(i) != cnpj.charAt(i + 1)){
			digitos_iguais = 0;
			break;
		}
		
		if (!digitos_iguais){
			
			tamanho = cnpj.length - 2
			numeros = cnpj.substring(0,tamanho);
			digitos = cnpj.substring(tamanho);
			soma = 0;
			pos = tamanho - 7;
			
			for (i = tamanho; i >= 1; i--){
				soma += numeros.charAt(tamanho - i) * pos--;
				if (pos < 2) pos = 9;
			}
			
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			
			if (resultado != digitos.charAt(0)){
				return false;
			}
			
			tamanho = tamanho + 1;
			numeros = cnpj.substring(0,tamanho);
			soma = 0;
			pos = tamanho - 7;
			
			for (i = tamanho; i >= 1; i--){
				soma += numeros.charAt(tamanho - i) * pos--;
				if (pos < 2) pos = 9;
			}
			
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			
			if (resultado != digitos.charAt(1)){
				return false;
			}
			return true;
		}
		else{
			return false;
		}
	}
}

//Novas funções
function jAlert2(type, title, mesage, object){
	jAlert(type, mesage, title, function(){
		if($("#"+object).length == 1){
			if($("#"+object).get(0).tagName == 'SELECT'){
				$("#"+object).addClass('textbox-error').focus().hover(function(){
					$("#"+object).removeClass('textbox-error');
				})
			}else{
				$("#"+object).addClass('textbox-error').focus().click(function(){
					$("#"+object).removeClass('textbox-error');
				})
			}
		}
	});
}

function disableButtons(){
	
	if($("#button-insert").length == 1){
		$("#button-insert").attr("disabled", true); 
	}

	if($("#button-update").length == 1){
		$("#button-update").attr("disabled", true); 
	}

	if($("#button-back").length == 1){
		$("#button-back").attr("disabled", true); 
	}
	
}
//--------------------------------------------------------------
//------------------------FORMATAÇÕES---------------------------
//--------------------------------------------------------------
//$("#yourTextBoxName").onlyNumber(); 
jQuery.fn.onlyNumber = function(){ 
	return this.each(function(){ 
		$(this).keydown(function(e){ 
			var key = e.charCode || e.keyCode || 0; 
			// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY 
			return ( 
				key == 8 ||  
				key == 9 || 
				key == 46 || 
				(key >= 37 && key <= 40) || 
				(key >= 48 && key <= 57) || 
				(key >= 96 && key <= 105)); 
		}) 
	}) 
};


//--------------------------------------------------------------
//-------------------------------AJAX---------------------------
//--------------------------------------------------------------
function getUrl(url,method,asc){
	
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
		 xmlhttp = new XMLHttpRequest();
	}else{// code for IE6, IE5
		 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if(url.indexOf("?") != -1){
		url += "&ramdom="+Math.random();
	}else{
		url += "?ramdom="+Math.random();
	}
	
	xmlhttp.open((!method )? "get" : "post", url,(!asc) 	? false : true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send(null);
	
	return xmlhttp.responseText;
	
}

function retornaValores(Cam, Tab, Fil, Ord){
	return getUrl("includes/ajax.asp?Tipo=3&Cam="+Cam+"&Tab="+Tab+"&Fil="+Fil+"&Ord="+Ord);
}

function loadSelect(Select,subSelect,id,name,table,filter,order,sel) {

	$('#'+subSelect).attr('length',0).append('<option value="">[Selecione uma opção]</option>');
	
	if(!sel){sel = 0}

	if($(Select).get(0).selectedIndex != 0){
		$.ajax({
			type: "GET",
			url: "includes/ajax.asp",
			data: "Tipo=1&Cam="+id+","+name+"&Tab="+table+"&Fil="+filter+"&Ord="+order+"&sel="+sel+"&ramdom="+Math.random(),
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(data){
				$.each(data.results, function(index) { 
					$('#'+subSelect).append('<option value="' + data.results[index].chave + '">' + data.results[index].texto + '</option>');
				}); 
				$('#'+subSelect).get(0).selectedIndex = data.selected;
			}
	  });
	}
} 

function buscaCEP(objCEP, idUF, idCid, idBai, idLog){
	if($(objCEP).val() != "_____-___"){
		if($(objCEP).val().length < 9 || $(objCEP).val() == "00000-000" || $(objCEP).val() == "11111-111" || $(objCEP).val() == "22222-222" || $(objCEP).val() == "33333-333" || $(objCEP).val() == "44444-444" || $(objCEP).val() == "55555-555" || $(objCEP).val() == "66666-666" || $(objCEP).val() == "77777-777" || $(objCEP).val() == "88888-888" || $(objCEP).val() == "99999-999"){
			jAlert2('warning', 'Ocorreu um erro', 'O <b>CEP</b> informado é <b>inválido</b> !');			
			$(objCEP).val("");
		}else{
			$(objCEP).after('<img src="img/loading.gif" id="loading" width="24" height="24" />');
			$('#'+idUF).attr('length',0).append('<option value="">[Selecione uma opção]</option>');	
			$('#'+idCid).attr('length',0).append('<option value="">[Selecione uma opção]</option>');
			$('#'+idBai).attr('length',0).append('<option value="">[Selecione uma opção]</option>');
			$("#"+idLog).val("");
			$.ajax({
					type: "GET",
					url: "includes/ajax.asp",
					data: "tipo=4&CEP="+$(objCEP).val(),
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					success: function(data){
						$("#loading").remove();
						if(data.success == 1){
							loadSelect(this,idUF,'EstCod','EstNome','Estado','EstCod <> 0','EstNome ASC', data.results[0].Estado);
							loadSelect(this,idCid,'CidCod','CidNome','Cidade','EstCod = ' + data.results[0].Estado,'CidNome ASC', data.results[0].Cidade);
							loadSelect(this,idBai,'BaiCod','BaiNome','Bairro','CidCod = ' + data.results[0].Cidade,'BaiNome ASC', data.results[0].Bairro);
							$("#"+idLog).val(data.results[0].Logradouro);
						}else{
							jAlert2('warning', 'Ocorreu um erro', 'O <b>CEP</b> informado é <b>inválido</b> !');
						}
						
					}
			});
		}
	}
}

//--------------------------------------------------------------
//-----------------VALIDAÇÕES DA LOJA---------------------------
//--------------------------------------------------------------
function validaContato(){
	
	if($("#ConNome").val() == ''){
		jAlert2('warning',"Mensagem do Site", "Por favor, preencha o campo <b>Nome</b> !", "ConNome");
		return false;
	}
	
	if(!isEmail($("#ConEmail").val())){
		jAlert2('warning',"Mensagem do Site", "Por favor, preencha um <b>E-mail</b> válido !", "ConEmail");
		return false;
	}

	if($("#MidCod").selectedIndex == 0){
		jAlert2('warning',"Mensagem do Site", "Por favor, selecione <b>Onde nos conheceu</b> !", "MidCod");
		return false;
	}

	if($("#ConMensagem").val() == ''){
		jAlert2('warning',"Mensagem do Site", "Por favor, preencha o campo <b>Mensagem</b> !", "ConMensagem");
		return false;
	}
	
	return true;
}

