

//var url = 'http://localhost/embrace/';
var url = 'http://www.euindicocyrela.com.br/';

function formata(src, mask) 
{
  var i = src.value.length;
  var saida = mask.substring(0,1);
  var texto = mask.substring(i)
if (texto.substring(0,1) != saida)
  {
	src.value += texto.substring(0,1);
  }
}


function load_url(url, id)
{
//	Element.show( 'loader' );
//	var id = 'content-box';
	
	new Ajax.Updater
	(
		id,       // DIV id
		url,      // URL
		{         // options
			method:'get',
			onComplete: function(element)
			{
//				$("loader").style.display = 'none';
//				Element.hide('loader');
			}
		}
	);
}




function novaSenha(cpf)
{
	if (!ValidaCPF(cpf))
	{
		alert("O CPF está inválido.");
		cpf.focus();
		return 0;
	}
	
	load_url(url + '/requests/novasenha/cpf/' + cpf.value,  'userreg');
}





function chk(obj)
{
	while ( obj.value.search(/\"/) != -1 )
	{
		obj.value = obj.value.replace(/\"/,"'");
	}
}





function chk_hifen(obj)
{
	while ( obj.value.search(/-/) != -1 )
	{
		obj.value = obj.value.replace(/-/,"");
	}
}






/*
function habilita(obj, class)
{
	var nomes = $$('.' + class);
	var dis = true;
	if (obj.value == 0)
		dis = true;
	else
		dis = false;
//	alert("elementos: " + nomes.length);
	for(var i = 0; i < nomes.length; i++)
	{
		nomes[i].disabled = dis;
	}
}
*/




function hab_out(stat, outro)
{
	$(outro).disabled = stat;
	if (stat == false)
	{
		$(outro).focus();
		$(outro).removeClassName('disabled');
		$(outro).addClassName('enabled');
	}
	else
	{
		$(outro).removeClassName('enabled');
		$(outro).addClassName('disabled');
	}
}





function am()
{
	alert("É necessário preencher os Dados de Identificação antes.");
}




function update_area(id, url)
{
	$("loading").style.display = '';
	var ajax = new Ajax.Updater(
		id,       // DIV id
		url,      // URL
		{         // options
			method:'get',
			onComplete: function(element)
			{
				$("loading").style.display = 'none';
			}
		});
}








function expande(element)
{
	if ($(element).style.display == 'none')
		new Effect.BlindDown(element);
	else
		new Effect.BlindUp(element);
}


/*
function admins_submit()
{
	if($('tipo').selectedIndex == 0)
	{
		alert("É necessário selecionar um tipo de administrador, 'Embrace' ou 'Cyrela'.\nO administrador 'Embrace' contém todos os previlégios de acesso, já o 'Cyrela' contém algumas restrições.");
		$('tipo').focus();
		return 0;
	}
	else
		form_submit();
}
*/

function form_indicado()
{
	if (!checkMail($('email')))
	{
		alert("O campo de e-mail está inválido.");
		$('email').focus();
		return 0;
	}

	if ($('nome').value == "")
	{
		alert("O campo Nome é necessário.");
		$('nome').focus();
		return 0;
	}
/*	
	new Ajax.Request(
//		url + 'requests/verificacpf/cpf/' + $('cpf').value,
		url + 'index',
	{
		method: 'get',
		onComplete: function(transport)
		{
//			if (transport.responseText == '0')
			$('mensagem').update('completo!');
		},
		onCreate: function()
		{
			$('mensagem').update('criado!');
		},
		onLoading: function()
		{
			$('mensagem').update($('cpf').value);
		},
		onFailure: function()
		{
			$('mensagem').update('não deu!');
		}
	});*/

	new Ajax.Request(
		//url + 'requests/verificaemail/email/' + $('email').value,
		'/requests/verificaemail/email/' + $('email').value,
	{
		method: 'get',
		onSuccess: function(transport)
		{
			if (transport.responseText == '0')
				form_submit();
			else if (transport.responseText == '1')
			{
				alert ("Este e-mail já está cadastrado em nosso sistema; provavelmente " + $('nome').value + " já foi indicado por outra pessoa.\n Continue indicando novas pessoas!");
				$('nome').focus();
				return 0;
			}
		}
	});

}


function form_submit()
{
	/* Verifica campos REQUERIDOS */
	var fields_required = $$(".REQUIRED");
	
	for(var i = 0; i < fields_required.length; i++)
	{
		if (fields_required[i].value == "")
		{
			alert("O campo '" + fields_required[i].title + "' é necessário.");
			fields_required[i].focus();
			return 0;
		}
	}

	/* Verifica campos de DATA */
	var fields_data = $$(".DATA");
	
	for(var i = 0; i < fields_data.length; i++)
	{
		if (!ValidaData(fields_data[i]))
		{
			alert("O campo de data '" + fields_data[i].title + "' parece inválido. A data deve ser inserida no formato exemplo '10/08/1977'");
			fields_data[i].focus();
			return 0;
		}
	}

	/* Verifica campos de CPF */
	var fields_data = $$(".CPF");
	
	for(var i = 0; i < fields_data.length; i++)
	{
		if (!ValidaCPF(fields_data[i]))
		{
			alert("O campo de CPF está inválido.");
			fields_data[i].focus();
			return 0;
		}
	}

	/* Verifica campos de CNPJ */
	var fields_data = $$(".CNPJ");
	
	for(var i = 0; i < fields_data.length; i++)
	{
		if (!ValidaCNPJ(fields_data[i]))
		{
			alert("O campo de CNPJ está inválido.");
			fields_data[i].focus();
			return 0;
		}
	}

	/* Verifica campos de E-MAIL */
	var fields_data = $$(".MAIL");
	
	for(var i = 0; i < fields_data.length; i++)
	{
		if (!checkMail(fields_data[i]))
		{
			alert("O campo de E-MAIL está inválido.");
			fields_data[i].focus();
			return 0;
		}
	}

	/* Verifica campos de CEP */
	var fields_data = $$(".CEP");
	
	for(var i = 0; i < fields_data.length; i++)
	{
		if (!checkCEP(fields_data[i]))
		{
			alert("O campo de CEP está inválido.");
			fields_data[i].focus();
			return 0;
		}
	}

	/* Verifica campos de SENHA */
	var fields_senha = $$(".SENHA");
	if(fields_senha.length == 2)
	{
		if (fields_senha[0].value != fields_senha[1].value)
		{
			alert("As senhas não conferem, redigite-as.");
			fields_senha[0].value = '';
			fields_senha[1].value = '';
			fields_senha[0].focus();
			return 0;
		}
	}

	$("form_dados").submit();

}








function ValidaData(field){
	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 || year > 9999 || year <= 0000) {
	if (year == 0 || year > 9999) {
		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 = ""; month = ""; year = ""; seperator = "";
	}
	/* if no error, write the completed date to Input-Field (e.g. 13.12.2001) */
	if (err == 0) {
		DateField.value = day + seperator + month + seperator + year;
	return true;
	}
	/* Error-message if err != 0 */
	else {
//       alert("Data inválida.");
		//DateField.value = '';
		DateField.focus();
		DateField.select();
	return false;
	}
}



function checkMail(mail){
	var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
	if(typeof(mail) == "string")
	{
		if(er.test(mail)){ return true; }
	}
	else if(typeof(mail) == "object")
	{
		if(er.test(mail.value))
		{
			return true;
		}
	}else
	{
		return false;
	}
}


 function ValidaCNPJ(Campo) {
         CNPJ = Campo.value;
         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 Trim(strTexto)
    {
        // Substitúi os espaços vazios no inicio e no fim da string por vazio.
        return strTexto.replace(/^\s+|\s+$/g, '');
    }

// Função para validação de CEP.
function checkCEP(Campo)
    {
		var strCEP = Campo.value;
        // Caso o CEP não esteja nesse formato ele é inválido!
        var objER = /^[0-9]{5}-[0-9]{3}$/;

        strCEP = Trim(strCEP)
        if(strCEP.length > 0)
            {
                if(objER.test(strCEP))
                    return true;
                else
                    return false;
            }
        else
            return true;
    }

function ValidaCPF(Campo){
	var i;
	var s = Campo.value;
	
	while ( s.search(/-/) != -1 )
	{
		s = s.replace(/-/,"");
	}

	if (s != "")
	{
		s = s.replace(".","");
		s = s.replace(".","");
		s = s.replace(".","");
		s = s.replace("-","");
		
		
		var c = s.substr(0,9);
		var dv = s.substr(9,2);
		var d1 = 0; 
		
		for (i = 0; i < 9; i++)
		{
			d1 += c.charAt(i)*(10-i);
		}
		
		if (d1 == 0)
		{
//			alert("CPF Inválido");
			Campo.focus();
			Campo.select();
			return false;
		}
		
		d1 = 11 - (d1 % 11);
		
		if (d1 > 9)
			d1 = 0;
		
		if (dv.charAt(0) != d1)
		{
//			alert("CPF Inválido");
			Campo.focus();
			Campo.select();
			return false;
		}
		
		d1 *= 2;
		
		for (i = 0; i < 9; i++)
		{
			d1 += c.charAt(i)*(11-i);
		}
		
		d1 = 11 - (d1 % 11);
		
		if (d1 > 9)
			d1 = 0;
		
		if (dv.charAt(1) != d1)
		{
//			alert("CPF Inválido")
			Campo.focus();
			Campo.select();
			return false;
		}
		
		return true;
	}
}


/* POST request */

	var http_request = false;
	var form_obj;
	var area_up;
	
	
	function makePOSTRequest(url, parameters) {
		http_request = false;
		if (window.XMLHttpRequest) { // Mozilla, Safari,...
			http_request = new XMLHttpRequest();
			if (http_request.overrideMimeType) {
				// set type accordingly to anticipated content type
				//http_request.overrideMimeType('text/xml');
				http_request.overrideMimeType('text/html');
			}
		} else if (window.ActiveXObject) { // IE
			try {
				http_request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					http_request = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}
		if (!http_request) {
			alert('Cannot create XMLHTTP instance');
			return false;
		}
		
		http_request.onreadystatechange = alertContents;
		http_request.open('POST', url, true);
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http_request.setRequestHeader("Content-length", parameters.length);
		http_request.setRequestHeader("Connection", "close");
		http_request.send(parameters);
		
/*		$('title').value='';
		$('title').focus();*/
		
/*		if ($('item_opt').value == 'edit_submit')
			revert_edit_item();*/
	}

	function alertContents() {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				//alert(http_request.responseText);
				result = http_request.responseText;
//            $(form_obj.name).innerHTML = result;
				$(area_up).innerHTML = result;
//            Element.hide( 'loader' );
					$("loader").style.display = 'none';
			} else {
				alert('There was a problem with the request.');
			}
		}
	}
		
	function post(class_name, act, area) {
		$("loader").style.display = '';
		
		if($("title").value == "")
		{
			alert("O Campo 'Nome do Ítem' está vazio.");
			$("loader").style.display = 'none';
			return 0;
		}
		var poststr = "";
		area_up = area;
		//Element.show( 'loader' );
		var fields_data = $$('.' + class_name);
		
		for(var i = 0; i < fields_data.length; i++)
		{
			poststr += fields_data[i].name + "=" + encodeURI(fields_data[i].value) + "&";
		}
		
		makePOSTRequest(act, poststr);
	}


/* Fim do POST request */








/* PEGA O ÍTEM PRÉVIO DE UM SELECTBOX PARA PODER REVERTELO DEPOIS */
/*
var item = '';

function getSelected(obj)
{
	alert(item);
	if (item == '')
		item = obj.selectedIndex;
}
*/





/* SETA STATUS DOS INDICADOS, POR CORRETORES OU ADMIN */

function setStatus(obj, id)
{
	if (confirm("Deseja realmente mudar o status deste indicado?\nATENÇÃO: Se este indicado está inativo, ao ativar ele será atribuído a um corretor!"))
	{
		removeClasses(id);
		switch(obj.value)
		{
			case '0':
				$('tr_' + id).addClassName('inativo');
				break;
			case '1':
				$('tr_' + id).addClassName('ativo');
				break;
			case '2':
				$('tr_' + id).addClassName('emtrabalho');
				break;
		}
	
		$("loader").style.display = '';
		var poststr = "";
		area_up = 'mensagem';
		poststr = obj.name + "=" + encodeURI(obj.value) + '&id=' + encodeURI(id);
		makePOSTRequest(url + 'requests/setstatus', poststr);
	}
/*	else
		obj.selectedIndex = item;
	
	item = '';*/
}

function setStatusSelBox(obj, id)
{
	if (confirm("Deseja realmente mudar o status deste indicado?\nATENÇÃO: Se este indicado está inativo, ao ativar ele será atribuído a um corretor!"))
	{
		removeClasses(id);
		switch(obj.checked)
		{
			case false:
				$('tr_' + id).addClassName('ativo');
				obj.value = 1;
				break;
			case true:
				$('tr_' + id).addClassName('emtrabalho');
				obj.value = 2;
				break;
		}
	
		$("loader").style.display = '';
		var poststr = "";
		area_up = 'mensagem';
		poststr = obj.name + "=" + encodeURI(obj.value) + '&id=' + encodeURI(id);
		makePOSTRequest(url + 'requests/setstatus', poststr);
	}
}

function setMalaEnv(obj, id)
{
	if (confirm("Realmente mandou a mala direta para esta pessoa?"))
	{
		switch(obj.checked)
		{
			case false:
				obj.value = 0;
				break;
			case true:
				obj.value = 1;
				break;
		}
	
		$("loader").style.display = '';
		var poststr = "";
		area_up = 'mensagem';
		poststr = obj.name + "=" + encodeURI(obj.value) + '&id=' + encodeURI(id);
		makePOSTRequest(url + 'requests/setmalaenv', poststr);
	}
}

function removeClasses(id)
{
	$('tr_' + id).removeClassName('inativo');
	$('tr_' + id).removeClassName('ativo');
	$('tr_' + id).removeClassName('emtrabalho');
}



/* MODIFICA 'INDICADO' PARA 'INDICADOR' E VICE-VERSA */

function setTipo(obj, id)
{
	if (confirm("Deseja realmente mudar o tipo desta pessoa (indicado X indicador)?"))
	{
		$("loader").style.display = '';
		var poststr = "";
		area_up = 'mensagem';
		poststr = obj.name + "=" + encodeURI(obj.value) + '&id=' + encodeURI(id);
		makePOSTRequest('/requests/setindicador', poststr);
	}
/*	else
		obj.selectedIndex = item;
	
	item = '';*/
}



/* MODIFICA 'INDICADO' PARA 'INDICADOR', USANDO BUTTON */

function setTipoBtn(obj, id)
{
	if (confirm("Deseja realmente mudar esta pessoa para indicador?"))
	{
		$("loader").style.display = '';
		var poststr = "";
		area_up = 'mensagem';
		poststr = obj.name + "=" + encodeURI(obj.value) + '&id=' + encodeURI(id);
		makePOSTRequest(url + 'requests/setindicador', poststr);
//		Effect.BlindUp('tr_' + id, { duration: 1.0 });
		$('tr_' + id).style.display = 'none';
	}
}




/* MODIFICA O CORRETOR */

function setCorretor(obj, id)
{
	if (confirm("Deseja realmente mudar o corretor desta pessoa?"))
	{
		$("loader").style.display = '';
		var poststr = "";
		area_up = 'mensagem';
		poststr = obj.name + "=" + encodeURI(obj.value) + '&id=' + encodeURI(id);
		makePOSTRequest(url + 'requests/setcorretor', poststr);
	}
/*	else
		obj.selectedIndex = item;
	
	item = '';*/
}




/* MOSTRA TIPO DE INDICADO */

function mostraTipo(obj)
{
	self.location.href = url + 'corretores/indicados/mostra/' + encodeURI(obj.value);
}

function mostraTipoIND(obj, id)
{
		$("loader").style.display = '';
		var poststr = "";
		area_up = 'indicados_area';
		poststr = "status=" + encodeURI(obj.value) + '&ind=' + encodeURI(id);
		makePOSTRequest(url + 'requests/indicadoresdetails', poststr);
}

/* DELETA USUÁRIO */

function excluir(local)
{
	if (confirm("ATENÇÃO: Deseja realmente exclui-lo?\nSeja criterioso ao excluir qualquer ítem, isto pode quebrar a integridade das informações do sistema."))
	{
		self.location.href = url + local;
	}
}

function excluir1()
{
//	alert(local.title);
	alert('oi');
/*	if (confirm("ATENÇÃO: Deseja realmente exclui-lo?\nSeja criterioso ao excluir qualquer ítem, isto pode quebrar a integridade das informações do sistema."))
	{
		self.location.href = url + local;
	}*/
}


