/************************************************************************************************************************************

script.js Configurações Gerais para Paginas Dinamicas - AJAX e PHP
Copyright (C) 2004 - Daniel Arantes Loverde - Web Loverde - developer4web@gmail.com

************************************************************************************************************************************/
var CharEmail = new RegExp("[A-Za-z0-9_.-]+@([A-Za-z0-9_]+\.)+[A-Za-z]{2,4}");

function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return strReturn;
}
// url_encode version 1.0 
function url_encode(str) { 
    var hex_chars = "0123456789ABCDEF"; 
    var noEncode = /^([a-zA-Z0-9\_\-\.])$/; 
    var n, strCode, hex1, hex2, strEncode = ""; 

    for(n = 0; n < str.length; n++) { 
        if (noEncode.test(str.charAt(n))) { 
            strEncode += str.charAt(n); 
        } else { 
            strCode = str.charCodeAt(n); 
            hex1 = hex_chars.charAt(Math.floor(strCode / 16)); 
            hex2 = hex_chars.charAt(strCode % 16); 
            strEncode += "%" + (hex1 + hex2); 
        } 
    } 
    return strEncode; 
} 

// url_decode version 1.0 
function url_decode(str) { 
    var n, strCode, strDecode = ""; 

    for (n = 0; n < str.length; n++) { 
        if (str.charAt(n) == "%") { 
            strCode = str.charAt(n + 1) + str.charAt(n + 2); 
            strDecode += String.fromCharCode(parseInt(strCode, 16)); 
            n += 2; 
        } else { 
            strDecode += str.charAt(n); 
        } 
    } 
    return strDecode; 
}

function ajaxLoading( url, div )
{
	$( div ).load( url );
}

function ajaxPosting( uri, formulario )
{
	//$.blockUI('Aguarde processando...');

	var form = document.getElementById(formulario);
	var form_string = get(formulario);
	
	//alert(form_string);
	
	 $.ajax({
	   type: "POST",
	   url: uri,
	   data: form_string,
	   beforeSend: function(){
			
			//$('#fCadastro').show();
		},
		success: function(resposta){
			
			$('#fCadastro').html(resposta);
			// Limpo o formulário
			form.reset();
	   		//$.unblockUI();
		},
		error: function(resposta){
			$('#fCadastro').html(resposta);
	   		//$.unblockUI();
		}
	 });
}
/******************************************************************************************

	Funcao para (des)selecionar todos CheckBox

*******************************************************************************************/
function selecionaTodos ( formulario )
{
	for ( a = 0; a < document.getElementById(formulario).length; a++ )
	{
		if ( document.getElementById(formulario).elements[a].type == "checkbox" )
		{
			if ( document.getElementById(formulario).elements[a].checked == false )
			{
				document.getElementById(formulario).elements[a].checked = true;
			}
			else
			{
				document.getElementById(formulario).elements[a].checked = false;
			}
		}
	}
}
/******************************************************************************************

	Funcao para Validar campos de formularios

*******************************************************************************************/
function trataForm (qtd, url, target, formulario) {

	var total = 0;
	var titulo = "";
	todos = document.getElementsByTagName('input');
	//for( x = 0; x < document.getElementById(formulario).length; x++ ) {
//	
//		if( document.getElementById(formulario).elements[x].type == "checkbox" ) {
//			if( document.getElementById(formulario).elements[x].checked ){
//				total += 1;
//				titulo = document.getElementById(formulario).elements[x].title;
//			}
//		}
//		else
//		{
//			total = 1;
//		}
//	}
//	
//	if ( total == 0 )
//	{
//		//$.blockUI('');
//		alert('Escolha uma das opções da Caixa de Seleção ( Checkbox )');
//		//$.unblockUI();
//		return false;
//	}
	
	for ( d=1 ; d <= qtd ; d++ ){
	   if ( document.getElementById( "require"+d ).value == "" || document.getElementById( "require"+d ).value == 0 ) {
		   AlertFormField();
		   document.getElementById( "require"+d ).focus ();
		   //document.getElementById( "require"+d ).className="MissingField";
		   return false;
		   break;
	   }
		
		if ( document.getElementById( "require"+d ).title == "Email"  ) {
			if ( document.getElementById( "require"+d ).value.search(CharEmail) == -1 ){
				AlertFormInvalidMail();
				document.getElementById( "require"+d ).focus();
				//document.getElementById( "require"+d ).className="MissingField";
				return false;
		  		break;
			}
		}
	   
	   if ( document.getElementById( "require"+d ).value != "" && qtd == d  ) {
		   if(target){
			   	document.getElementById(formulario).target = target;
				document.getElementById(formulario).action = url;
		   		document.getElementById(formulario).submit();
		   }else{
			   ajaxPosting( url, formulario );
		   }
	   }
	}
}
/******************************************************************************************

	Funcao para listar TODOS os campos de formularios

*******************************************************************************************/
function get(obj) {
	var FormInput 		= document.forms[document.getElementById(obj).name].getElementsByTagName("input");
	var FormSelect		= document.forms[document.getElementById(obj).name].getElementsByTagName("select");
	var FormTextArea	= document.forms[document.getElementById(obj).name].getElementsByTagName("textarea");

	var getstr = "";
	for (i=0; i<FormInput.length; i++) {
		if (FormInput[i].type == "text") {
		   getstr += FormInput[i].name + "=" + url_encode(FormInput[i].value) + "&";
		}
	}
	for (i=0; i<FormInput.length; i++) {
		if (FormInput[i].type == "hidden") {
		   getstr += FormInput[i].name + "=" + url_encode(FormInput[i].value) + "&";
		}
	}
	for (i=0; i<FormInput.length; i++) {
		if (FormInput[i].type == "password") {
		   getstr += FormInput[i].name + "=" + url_encode(FormInput[i].value) + "&";
		}
	}
	for (i=0; i<FormInput.length; i++) {
		if (FormInput[i].type == "file") {
		   getstr += FormInput[i].name + "=" + url_encode(FormInput[i].value) + "&";
		}
	}
	for (i=0; i<FormInput.length; i++) {
		if (FormInput[i].type == "checkbox") {
		   if (FormInput[i].checked) {
			  getstr += FormInput[i].name + "=" + FormInput[i].value + "&";
		   } else {
			  getstr += FormInput[i].name + "=&";
		   }
		}
	}
	for (i=0; i<FormInput.length; i++) {
		if (FormInput[i].type == "radio") {
		   if (FormInput[i].checked) {
			  getstr += FormInput[i].name + "=" + FormInput[i].value + "&";
		   }
		}
	}
	for (i=0; i<FormTextArea.length; i++) {
		if (FormTextArea[i]) {
			   getstr += FormTextArea[i].name + "=" + url_encode(FormTextArea[i].value) + "&";
		}
	}
	for (i=0; i<FormSelect.length; i++) {
		if (FormSelect[i]) {
			var sel = FormSelect[i];
			getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
		}
	}
	
	return getstr;
}

/******************************************************************************************

	Funcao para montar Alert em DIV

*******************************************************************************************/
// Funcao para Alert dos campos vazios
function AlertFormField(){
	alert('Preencha o campo '+document.getElementById( "require"+d ).title);
	return false;
}
// Funcao para Alert de email invalido
function AlertFormInvalidMail(){
	alert('O formato do campo '+document.getElementById( "require"+d ).title+' esta incorreto!');
	return false;
}
/******************************************************************************************

	Funcao para mudar as Abas

*******************************************************************************************/

function ChangeTab(IdAba, objAba, total, classShow, classHide, DivHide, DivShow) {
	
	for(var i=1; i<=total; i++) {
		
		if(document.getElementById(IdAba+i) == document.getElementById(objAba)) {
			
			document.getElementById(IdAba+i).className = classShow;
		}
		else {
			
			document.getElementById(IdAba+i).className = classHide;
		}
		
		if(document.getElementById(DivHide+i) == document.getElementById(DivShow)) {
			
			document.getElementById(DivHide+i).style.display = "";
		}
		else {
			document.getElementById(DivHide+i).style.display = "none";
		}
	}
}
/******************************************************************************************

	On Click link

*******************************************************************************************/
function goUrl(url)
{
	window.location=url;
}
/******************************************************************************************

	Link para FRAME

*******************************************************************************************/
function enviaRemessa(nome, url)
{
	frames[nome].location.href = url;
}
/******************************************************************************************

	Escolhendo PF ou PJ faz

*******************************************************************************************/
function trataOrcamento(qtd, url, target, formulario)
{
	var rdoEmpresaInput = document.forms[document.getElementById(formulario).name].getElementsByTagName("input");
	var EmpresaInput = document.forms[document.getElementById(formulario).name].getElementsByTagName("input");
	
	for ( d=1 ; d <= qtd ; d++ )
	{
	   if ( rdoEmpresaInput[1].checked && EmpresaInput[5].value == "" )
	   {
		   alert('Preencha o campo '+EmpresaInput[5].title);
		   EmpresaInput[5].focus ();
		   //EmpresaInput[5].className="MissingField";
		   return false;
		   break;
	   }
	   
	   if ( document.getElementById( "require"+d ).value == "" || document.getElementById( "require"+d ).value == 0 ) {
		   AlertFormField();
		   document.getElementById( "require"+d ).focus ();
		   //document.getElementById( "require"+d ).className="MissingField";
		   return false;
		   break;
	   }
		
		if ( document.getElementById( "require"+d ).title == "Email"  ) {
			if ( document.getElementById( "require"+d ).value.search(CharEmail) == -1 ){
				AlertFormInvalidMail();
				document.getElementById( "require"+d ).focus();
				//document.getElementById( "require"+d ).className="MissingField";
				return false;
		  		break;
			}
		}
	   
	   if ( document.getElementById( "require"+d ).value != "" && qtd == d  ) {
		   if(target){
			   	document.getElementById(formulario).target = target;
				document.getElementById(formulario).action = url;
		   		document.getElementById(formulario).submit();
		   }else{
			   ajaxPosting( url, formulario );
		   }
	   }
	}
}

function change( url, div )
{
	var Opcoes = document.getElementById('fCadastro').selEstado;
	
	if( url == "" )
	{
		ajaxLoading( '/cadastro_participantes/sel_cidade.php?estado_id='+Opcoes.options[Opcoes.selectedIndex].value, div );
	}
	else
	{
		ajaxLoading( '/cadastro_participantes/sel_cidade.php?'+url, div );
	}
	//ajaxLoading2( uri, dados, div )
	//alert(Opcoes.options[Opcoes.selectedIndex].value);
}
function ativa_cadastro( documento )
{
	var Opcoes = documento;
	
	if( Opcoes.options[Opcoes.selectedIndex].value == '1' )
	{
		document.getElementById('fCadastro').pCNPJ.disabled = true;
		document.getElementById('fCadastro').pCNPJ.value = '';
		document.getElementById('fCadastro').pRazao.disabled = true;
		document.getElementById('fCadastro').pRazao.value = '';
		
		document.getElementById('fCadastro').pCPF.disabled = false;
	}
	else if( Opcoes.options[Opcoes.selectedIndex].value == '2' )
	{
		document.getElementById('fCadastro').pCNPJ.disabled = true;
		document.getElementById('fCadastro').pCNPJ.value = '';
		document.getElementById('fCadastro').pRazao.disabled = true;
		document.getElementById('fCadastro').pRazao.value = '';
		document.getElementById('fCadastro').pCPF.disabled = false;
	}
	else if( Opcoes.options[Opcoes.selectedIndex].value == '3' )
	{
		document.getElementById('fCadastro').pCNPJ.disabled = false;
		document.getElementById('fCadastro').pRazao.disabled = false;
		
		document.getElementById('fCadastro').pCPF.disabled = true;
		document.getElementById('fCadastro').pCPF.value = '';
	}
	//alert(Opcoes.options[Opcoes.selectedIndex].value);
}
function trataFormAcmdd (qtd,url)
{
	if( document.getElementById('fCadastro').pPessoa.value == 0 )
	{
		alert('Preencha o campo Tipo de Cadastro');
		document.getElementById('fCadastro').pPessoa.focus();
		return false;
	}
	if( document.getElementById('fCadastro').pPessoa.value == "1" && document.getElementById('fCadastro').pCPF.value == "" )
	{
		alert('Preecha o campo CPF.');
		document.getElementById('fCadastro').pCPF.focus();
		return false;
	}
	if( document.getElementById('fCadastro').pPessoa.value == "2" && document.getElementById('fCadastro').pCPF.value == "" )
	{
		alert('Preecha o campo CPF.');
		document.getElementById('fCadastro').pCPF.focus();
		return false;
	}
	else if( document.getElementById('fCadastro').pPessoa.value == "3" && document.getElementById('fCadastro').pRazao.value == "" )
	{
		alert('Preecha o campo Razão Social.');
		document.getElementById('fCadastro').pRazao.focus();
		return false;
	}
	else if( document.getElementById('fCadastro').pPessoa.value == "3" && document.getElementById('fCadastro').pCNPJ.value == "" )
	{
		alert('Preecha o campo CNPJ.');
		document.getElementById('fCadastro').pCNPJ.focus();
		return false;
	}
	else if( document.getElementById('fCadastro').pLoja.value != 0 && document.getElementById('fCadastro').pContato.value == "" )
	{
		alert('Preecha o campo Contato de Referência.');
		document.getElementById('fCadastro').pContato.focus();
		return false;
	}
	else if( document.getElementById('fCadastro').pRegistro.value == "" )
	{
		alert('Preecha o campo CREA/ABD\n\nCaso não possua deixe o campo preenchido com:\n\nNão Possuo.');
		document.getElementById('fCadastro').pRegistro.value = "Não Possuo";
		return false;
	}
	else
	{
		return trataForm (qtd, url, '_self', 'fCadastro');
	}
}
