// CRIA OBJETO AJAX
function getXmlHttpRequest(){ 
   if (window.XMLHttpRequest){ 
      return new XMLHttpRequest(); 
   } 
   else if (window.ActiveXObject){ 
      try{ 
         return new ActiveXObject("Msxml2.XMLHTTP"); 
      }catch (e){
         try{
            return new ActiveXObject("Microsoft.XMLHTTP");
         }catch (e){}
      }
   }
}

var xmlhttp = getXmlHttpRequest();

function execJS(texto, div){
	var conteudo = $(div);
	var ini = texto.indexOf('<script>', 0);
	var fim = texto.indexOf('</script>', 0);
	var objScript = document.createElement("script");
	while (ini != -1){
		ini = ini+8;
		fim = fim-ini;
		objScript.text = texto.substr(ini, fim);
		eval(objScript.text);
		ini = texto.indexOf('<script>', ini);
	}
}


// CHAMA CONTEÚDO VIA AJAX
function conteudoAjax(arquivo, div){
	var xmlhttp = getXmlHttpRequest();
	$(div).innerHTML = '<img src="'+raiz+'/img/diversos/loader.gif"> Aguarde...';
	xmlhttp.open("POST", arquivo, true);
	xmlhttp.setRequestHeader("Content-Type", "text/html; charset=iso-8859-1");
	xmlhttp.setRequestHeader("Cache-Control", "no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4){
			$(div).innerHTML = xmlhttp.responseText;
			execJS(xmlhttp.responseText, div);
		}
	}
	xmlhttp.send(null);
}


// CARREGA OPTIONS DO COMBOBOX
function carregarCombo(combo, arquivo, id, valor){
	var comboboxAux  = $(combo);

	if (id != ''){
		xmlhttp.open("GET", raiz+'/action/'+arquivo+'.php?id='+id, true);
		xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xmlhttp.onreadystatechange = function(){
			if (xmlhttp.readyState == 1){
				comboboxAux.innerHTML = '';
				addCombo(comboboxAux, 0, "Carregando...");
			}

			if (xmlhttp.readyState == 4){
				var resultado = unescape(xmlhttp.responseText);
				var array = resultado.split(',');
				var tamanho = array.length;
				comboboxAux.innerHTML = '';
				addCombo(comboboxAux, 0, "Selecione");
				for(var i=0; i<tamanho-1; i++){
					addCombo(comboboxAux, array[i], array[i+1]);
					i++;
				}
				if(valor){ comboboxAux.value = valor; }
			}
		}
		xmlhttp.send(null);
	} else {
		comboboxAux.innerHTML = '';
		addCombo(comboboxAux, 0, "Selecione");
	}
}

// ENVIA O FORM
function submitForm(formulario, funcao){
	var metodo = $(formulario).method.toUpperCase();
    var action = $(formulario).action+"?";
	var tipoInput;   var valueInput; var nameInput;    var auxInput;
	var auxSelect;	 var obrigatorio; var nomeGrupo;
	var erro = 0;    var variaveis = "";

	for (var i=0;i<$(formulario).length;i++){
	    tipoInput   = document.forms[formulario].elements[i].type.toUpperCase();
		obrigatorio = document.forms[formulario].elements[i].getAttribute('obrigatorio');
		valueInput  = document.forms[formulario].elements[i].value;
		nameInput   = document.forms[formulario].elements[i].name;

		if (tipoInput != 'SELECT-ONE' && tipoInput != "CHECKBOX" && tipoInput != 'RADIO' && tipoInput != ''){
			auxInput = document.forms[formulario].elements[i].className;
			auxInput = auxInput.split(' ');
			document.forms[formulario].elements[i].className = auxInput[0];
		}
		
		if(tipoInput == 'RADIO' && nomeGrupo != document.forms[formulario].elements[i].name){
			var nomeGrupo = document.forms[formulario].elements[i].name;
			var tamanhoGrupo = document.forms[formulario].elements[nomeGrupo].length;
			var checado = 0;
			for(j=0; j<tamanhoGrupo; j++){
				if (document.forms[formulario].elements[nomeGrupo][j].checked){ 
					checado = 1;
					variaveis += document.forms[formulario].elements[nomeGrupo][j].id+"="+escape(document.forms[formulario].elements[nomeGrupo][j].value)+"&";
				}
			}
			
			if (obrigatorio && checado == 0){ erro = 1; }
		
		// PEGAR CHECKBOX SELECIONADO
		} else if(tipoInput == "CHECKBOX"){
			if (obrigatorio && !document.forms[formulario].elements[i].checked){
				erro = 1;
			} else {
				if(document.forms[formulario].elements[i].checked){
					variaveis += nameInput+"="+escape(valueInput)+"&";
				}
			}
			
		} else if (tipoInput == "TEXT" || tipoInput == "TEXTAREA" || tipoInput == "PASSWORD" || tipoInput == "FILE" || tipoInput == "HIDDEN"){
			if (obrigatorio && valueInput == ''){
				erro = 1;
			} else {
				variaveis += nameInput+"="+escape(valueInput)+"&";
			}
		} else if (tipoInput == "SELECT-ONE"){
			document.forms[formulario].elements[i].className = 'selectPadrao';
			
			if (obrigatorio && valueInput == 0){
				erro = 1;
			} else {
				variaveis += nameInput+"="+escape(valueInput)+"&";
			}
		}
    }

	//alert(variaveis);
	
	if (erro == 0){
		$(div).style.display = '';
		$(div).innerHTML = '<img style="padding-left:2px" src="'+raiz+'/img/diversos/loader.gif"> Aguarde...';
		if (funcao){
			xmlhttp.open(metodo, action, true); 
			xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
			eval('xmlhttp.onreadystatechange = '+funcao+';');
			xmlhttp.send(variaveis);
		} else {
			$(formulario).submit();
		}
	} else {
		janelaAviso('Preencha os campos obrigatórios!');
		for (var i=0;i<$(formulario).length;i++){
			obrigatorio = document.forms[formulario].elements[i].getAttribute('obrigatorio');
			tipoInput = document.forms[formulario].elements[i].type.toUpperCase();
			if (obrigatorio && (document.forms[formulario].elements[i].value == '' && tipoInput != 'SELECT-ONE') ||
				(document.forms[formulario].elements[i].value == 0 && tipoInput == 'SELECT-ONE')){
				auxInput = document.forms[formulario].elements[i].className;
				document.forms[formulario].elements[i].className = auxInput+' inputErro';
			}
		}
	}
	return false;
}

// ENVIAR CONTATO SITE
function retornoEnviarContato(){
	if(xmlhttp.readyState == 4){
		$(div).innerHTML = '';
		$(div).style.display = 'none';
		var resultado = xmlhttp.responseText;
		switch(parseInt(resultado)){
			case 1 :
				janelaAviso('E-mail enviado com sucesso!');
				$('contato[nome]').value		= '';
				$('contato[email]').value		= '';
				$('contato[assunto]').value		= '';
				$('contato[msg]').value			= '';
				$('contato[confirmacao]').value = '';
			break;
			case 2 : janelaAviso("Erro na confirmação. Tente novamente!"); break;
			case 3 : janelaAviso("Erro ao enviar e-mail. Tente novamente!"); break;
		}
	}
}

// VALIDAR EMAIL PARA CADASTRO DA NEWS
function retornoEmailNews(){
	if(xmlhttp.readyState == 4){
		$(div).innerHTML = '';
		$(div).style.display = 'none';
		var resultado = xmlhttp.responseText;
		switch(parseInt(resultado)){
			case 1 : redir(raiz+'/news/cadastro/'); break;
			case 2 : janelaAviso("E-mail já cadastrado. Tente novamente!"); break;
		}
	}
}


// VALIDAR EMAIL PARA CADASTRO DA TV
function retornoEmailTv(){
	if(xmlhttp.readyState == 4){
		$(div).innerHTML = '';
		$(div).style.display = 'none';
		var resultado = xmlhttp.responseText;
		switch(parseInt(resultado)){
			case 1 : janelaAviso("E-mail cadastrado com sucesso!"); $('cad[email]').value = ''; break;
			case 2 : janelaAviso("E-mail já cadastrado. Tente novamente!"); break;
		}
	}
}

// ENVIA FORMULÁRIO DE LOGIN NO ESPAÇO DO CLIENTE
function retornoEspacoCliente(){
	if(xmlhttp.readyState == 4){
		$(div).innerHTML = '';
		$(div).style.display = 'none';
		var resultado = xmlhttp.responseText;
		switch(parseInt(resultado)){
			case 1 : redir(raiz+'/espaco/'); break;
			case 2 : janelaAviso("Usuário ou senha inválidos. Tente novamente!"); break;
		}
	}
}

// ENVIAR FORMULÁRIO DE CADASTRO DA NEWS
function retornoCadNews(){
	if(xmlhttp.readyState == 4){
		$(div).innerHTML = '';
		$(div).style.display = 'none';
		var resultado = xmlhttp.responseText;
		switch(parseInt(resultado)){
			case 1 :
				janelaAviso("Cadastro realizado com sucesso!");
				$('news[nome]').value = '';
				$('news[data_nascimento]').value = '';
				$('news[empresa]').value = '';
				$('news[cargo]').value = '';
				$('news[endereco]').value = '';
				$('news[bairro]').value = '';
				$('news[cep]').value = '';
				$('news[cidade]').value = '';
				$('news[email]').value = '';
				$('news[confirmacao]').value = '';
				$('news[tipo1]').checked = true;
				$('news[usuario]').value = '';
				$('news[senha]').value = '';
				$('newsSite').style.display = 'none';
			break;
			case 2 : janelaAviso("E-mail já cadastrado. Tente novamente!"); break;
			case 3 : janelaAviso("Erro ao cadastrar. Tente novamente!"); break;
			case 4 : janelaAviso("Usuário já cadastrado. Tente novamente!"); break;
			case 5 : janelaAviso("Erro na confirmação. Tente novamente!"); break;
		}
	}
}

// ENVIAR FORMULÁRIO DE LOGIN NA NEWS
function retornoAcessarNews(){
	if(xmlhttp.readyState == 4){
		$(div).innerHTML = '';
		$(div).style.display = 'none';
		var resultado = xmlhttp.responseText;
		switch(parseInt(resultado)){
			case 1 : redir(raiz+'/news/visualizacao/'); break;
			case 2 : janelaAviso("Usuário ou senha inválidos. Tente novamente!"); break;
		}
	}
}

// ENVIAR FORMULÁRIO DE INDICAR PÁGINA
function retornoIndicar(){
	if(xmlhttp.readyState == 4){
		$(div).innerHTML = '';
		$(div).style.display = 'none';
		var resultado = xmlhttp.responseText;
		switch(parseInt(resultado)){
			case 1 : janelaAviso("E-mail enviado com sucesso!"); break;
			case 2 : janelaAviso("Erro ao enviar e-mail. Tente novamente!"); break;
		}
	}
}

