var urlToGo = domainUrlPrefix;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
function getHTTPObject() {
    var req;
    // Mozilla, Firefox, Safari, e Netscape
    if (window.XMLHttpRequest) {
        try {
            req = new XMLHttpRequest();
        } catch(e) {
            req = false;
        }
        return req;
    }

    // Internet Explorer
    if (window.ActiveXObject) {
        try {
            req = new ActiveXObject("Msxml3.XMLHTTP");
        } catch(e) {
            try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                try {
                    req = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e) {
                    req = false;
                }
            }
        }
        return req;
    }
    alert("Objeto XMLHTTP não e suportado pelo navegador.");
}
////////////////////////////////////////////////////////////////////
var xmlhttp = getHTTPObject();

function showHideAllCombos(state) {
	state = (!state)?"visible":state;
	var i = 0;
	var allCombosPage = document.getElementsByTagName("SELECT");
	
	if(allCombosPage.length) {
		for (i = 0; i < allCombosPage.length; i++) allCombosPage[i].style.visibility = state;
	}
	return;
}
function FormataData(Campo, teclapres){
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace("/", "");
	vr = vr.replace("/", "");
	tam = vr.length + 1;
	
	if (tecla != 9 && tecla != 8 && tecla != 46){
		if (tam > 2 && tam < 5) Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, tam);
		if (tam >= 5 && tam <=10) Campo.value = vr.substr(0,2) + '/' + vr.substr(2,2) + '/' + vr.substr(4,4);
	}
}
function ApenasNum(strParm) {
	strParm = String(strParm);
	var chrPrt = "0";
	var strRet = "";
	var j=0;
	for (var i=0; i < strParm.length; i++) {
 		chrPrt = strParm.substring(i, i+1);
 		if ( chrPrt.match(/\d/) ) {
	  		if (j==0) {
	   			strRet = chrPrt;
	   			j=1;
	  		}else{
	   			strRet = strRet.concat(chrPrt);
	  		}
 		}
	}
	
	return strRet;
}
function WorkLayers() {
	var args = WorkLayers.arguments, i = 0, obj = '';
	for(var i=0; i<args.length; i+=2)
	{
		obj = document.getElementById(args[i]);
		if(obj != null) {
			obj.style.display = args[i+1];
		}
	}
	return;
}
function WorkLayersVisible() {
	var args = WorkLayersVisible.arguments, i = 0, obj = '';
	for(var i=0; i<args.length; i+=2)
	{
		obj = document.getElementById(args[i]);
		if(obj != null) {
			obj.style['visibility'] = args[i+1];
		}
	}
	return;
}
function _go(p){top.location = p}
function setStyleCursor(state) { document.body.style.cursor = state; return; }
function focusObj(p) { if(document.getElementById(p)) document.getElementById(p).focus(); }
function selectTextObj(p) { if( document.getElementById(p) ) document.getElementById(p).select(); }
function setColorTextObj(p, color) { if( document.getElementById(p) ) document.getElementById(p).style.color = color; }
function disableInput(obj, status){ if( document.getElementById(obj) ) document.getElementById(obj).disabled=status; }
function bgObj(obj, bg){obj.style.background="#"+bg;}
function noSpace(keyB) { if(keyB.keyCode == 32) keyB.returnValue = false; }
function strUpper(str) { return (str.toUpperCase()); }
function strLower(str) { return (str.toLowerCase()); }
function toUpperString(obj) { obj.value = strUpper(obj.value); return; }
function toLowerString(obj) { obj.value = strLower(obj.value); return; }
function trimJS(string_param)
{
	var n_string = new String(string_param);
	return n_string.replace(/^\s*/, "").replace(/\s*$/, "");
}
function getAbsUrl() { 
	var urlPath = document.URL, a = 0, baseUrl = '';
	urlPath = urlPath.split('/');
	for(a=0; a<urlPath.length; a++) {
		baseUrl += urlPath[a]+"/";
		if(urlPath[a] == domainLocal || urlPath[a] == "www."+domainName || urlPath[a] == domainName) 
			break;
	}
	return baseUrl; 
}
function setHtmlInElement(idObjHtml, Content)
{
	if( document.getElementById(idObjHtml) ) {
		document.getElementById(idObjHtml).innerHTML = Content;
	}
	return;
}
function setSrcImage(objImg, newSrc) { if( document.getElementById(objImg) ) document.getElementById(objImg).src = newSrc; return; }
function joinVars2Url(nameArray, valueArray, typeRequest)
{
	var s = '';
	if(nameArray.length) {
		for(var i = 0; i<nameArray.length; i++) {
			if(i == 0) {
				s += (typeRequest == "GET")?'?':'';
			}else s += '&';
			s += nameArray[i]+'='+escape(valueArray[i]);
		}
	}
	return s;
}
function somenteNumeros(tecla) {
	if(tecla.keyCode < 48 || tecla.keyCode > 57)
		tecla.returnValue = false;
}
function clearForm()
{
	setTimeout("setCities()", 700);
}
function setBGFieldForm(tf, changeBackGroundField)
{
	for(var i=0; i<changeBackGroundField.length; i++) {
		bgObj(tf[changeBackGroundField[i]], 'FFFFF0');
	}
}
//////////////////////******************************************//////////////////////
//Função para Cálculo do Digito do CPF/CNPJ
function DigitoCPFCNPJ(numCIC) {
	var numDois = numCIC.substring(numCIC.length-2, numCIC.length);
	var novoCIC = numCIC.substring(0, numCIC.length-2);
	
	switch (numCIC.length){
 		case 11 :
  			numLim = 11;
  		break;
 		case 14 :
  			numLim = 9;
  		break;
 		default : return false;
	}
	
	var numSoma = 0;
	var Fator = 1;
	for (var i=novoCIC.length-1; i>=0 ; i--) {
 		Fator = Fator + 1;
 		if (Fator > numLim) {
  			Fator = 2;
 		}
 		numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
	}
	
	numSoma = numSoma/11;
	var numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));
   	if (numResto > 1) {
 		numResto = 11 - numResto;
   	}else{
 		numResto = 0;
    }
    //-- Primeiro dígito calculado.  Fará parte do novo cálculo.

    var numDigito = String(numResto);
    novoCIC = novoCIC.concat(numResto);
	numSoma = 0;
	Fator = 1;
	for (var i=novoCIC.length-1; i>=0 ; i--) {
 		Fator = Fator + 1;
 		if (Fator > numLim) {
  			Fator = 2;
 		}
 		numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
	}
	
	numSoma = numSoma/11;
	numResto = numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));
   	if (numResto > 1) {
 		numResto = 11 - numResto;
   }else{
 		numResto = 0;
   }
   
   //-- Segundo dígito calculado.
   numDigito = numDigito.concat(numResto);
   if (numDigito == numDois) {
   	return true;
   }else{
 	return false;
   }
}
//--< Fim da Função >--
//-- Retorna uma string apenas com os números da string enviada
function ApenasNum(strParm) {
	strParm = String(strParm);
	var chrPrt = "0";
	var strRet = "";
	var j=0;
	for (var i=0; i < strParm.length; i++) {
 		chrPrt = strParm.substring(i, i+1);
 		if ( chrPrt.match(/\d/) ) {
	  		if (j==0) {
	   			strRet = chrPrt;
	   			j=1;
	  		}else{
	   			strRet = strRet.concat(chrPrt);
	  		}
 		}
	}
	
	return strRet;
}
function PreencheCIC(objCIC) {
	var chrP = objCIC.value.substring(objCIC.value.length-1, objCIC.value.length);
	if ( !chrP.match(/[0-9]/) && !chrP.match(/[\/.-]/) ) {
 		objCIC.value = objCIC.value.substring(0, objCIC.value.length-1);
 		return false;
	}
	return true;
}
//--< Fim da Função >--
function FormataCIC (numCIC) {
	numCIC = String(numCIC);
	switch (numCIC.length){
		case 11 :
 			return numCIC.substring(0,11);
		case 14 :
 			return numCIC.substring(0,14);
		default :
 			alert("Tamanho incorreto do CPF ou CNPJ!");
 			return "";
	}
}
//--< Fim da Função >--
//-- Remove os sinais, deixando apenas os números e reconstroi o CPF ou CNPJ, verificando a validade
//-- Recebe como parâmetros o número do CPF ou CNPJ, com ou sem sinais e o atualiza com sinais é validado.
function ConfereCIC(objCIC) {
	if (objCIC.value == null) return false;
	
	var strCPFPat  = /^\d{11}$/;
	var strCNPJPat = /^\d{14}$/;
	numCPFCNPJ = ApenasNum(objCIC.value);
	
	if (!DigitoCPFCNPJ(numCPFCNPJ)) {
 		//alert("Atenção o Dígito verificador do CPF ou CNPJ é inválido!");
 		return false;
	}

	objCIC.value = FormataCIC(numCPFCNPJ);

	if (objCIC.value.match(strCNPJPat)) {
 		return true;
	}else if (objCIC.value.match(strCPFPat)) {
 		return true;
	}else{
 		//alert("Digite um CPF ou CNPJ válido!");
 		return false;
	}
}
/////////////////////***********************************************//////////////////
function processando()
{
	var tmp = '';
	tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td width="100%" align="center">';
	tmp += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="200" height="200">';
    tmp += '<param name="movie" value="imagens/loading_flash.swf">';
    tmp += '<param name="quality" value="high">';
    tmp += '<param name="wmode" value="transparent">';
    tmp += '<embed src="imagens/loading_flash.swf" width="200" height="200" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" wmode="transparent"></embed>';
	tmp += '</object>';
	tmp += '</td></tr></table>';
	return tmp;
}
function layerErro(msgError, t)
{
	var tmp = '';
	tmp = '<table border=0 cellspacing=0 cellpadding=5 width="100%" height="100%"><tr><td width="100%" align="center"><table border="0" style="border: 2px solid #ADB9C2" bgcolor="#FFFFFF" cellpadding="5" cellspacing="2" align="center" class="style6"><tr><td><img src="imagens/ico_aviso.gif" width="18" height="16" border="0" align="absmiddle" hspace="2"><b>Atenção, o(s) seguinte(s) erro(s) foram encontrado(s):</b></td></tr>';
	tmp += '<tr><td style="padding-left: 10px; line-height: 190%" class="style6">'+msgError+'</td></tr>';
	tmp += '<tr><td align="center"><input type="Button" id="btnVoltarErroForm" class="inputSubmitButton" value="Voltar" onclick="javascript: void backForm(\''+t+'\');"></td></tr>';
	tmp += '</table></td></tr></table>';
	return tmp;
}
function layerErroContent(msgError, t)
{
	var tmp = '';
	tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td width="100%" align="center"><table border="0" width="390" style="border: 2px solid #ADB9C2" bgcolor="#FFFFFF" cellpadding="5" cellspacing="2" align="center" class="style6"><tr><td>&nbsp;</td></tr>';
	tmp += '<tr><td align="center" style="line-height: 190%;" class="style6">'+msgError+'</td></tr>';
	tmp += '<tr><td align="center">&nbsp;</td></tr>';
	tmp += '</table></td></tr></table>';
	return tmp;
}
////////////////////////////////////////////////////////////////////
function FormChangeField(f){
	if(f.value.length==f.maxLength){
  	for(var i=0;i<f.form.length;i++){
    	if(f.form[i]==f){f.form[i+1].focus();break}
		}
	}
}

function FormOnlyThisChars(numbers,letters,others,e){
	if(window.event)key=window.event.keyCode
	else if(e)key=e.which
	else return true
	S=(others)?others:''
	if(numbers)S+='0123456789'
	if(letters)S+='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
	if(key==null||key==0||key==8||key==9||key==13||key==27)return true
	else if(S.indexOf(String.fromCharCode(key))!=-1)return true
	else return false
}

function ZeroPad(f){
	if(f.value.length < 2 && f.value.length > 0){
		f.value = "0" + f.value;
	}
}
////////////////////////////////////////////////////////////////////
function sortItem(sortField, tId){
	var listBlock = document.getElementById('list'+tId);
	var heightlistBlock = listBlock.clientHeight;
	
	var tmp = '', method = 'GET', result = '', urlAjax = domainLocal;
	urlAjax += 'includes/exec/getList.php?sort_field='+sortField+'&t='+tId;
	
	tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td height="60" width="100%" class="CELULAS"><p align="center">';
	tmp += '<img src="images/loader.gif" border="0" width="16" height="16" align="absmiddle" hspace="4">';
	tmp += 'Buscando as empresas, por favor aguarde...';
	tmp += '</p></td></tr></table>';
	listBlock.style.height = heightlistBlock+'px';
	listBlock.innerHTML = tmp;
	tmp = '';
	
	if (typeof xmlhttp != "undefined") {
		xmlhttp.open(method, urlAjax, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4)
			{
				if (xmlhttp.status == 404) 
		            alert("Status HTTP Response: Get List DropDown - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else if (xmlhttp.status != 200) 
		            alert("Status HTTP Response: Get List DropDown - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else {
					result = xmlhttp.responseText;
					if(result == "NO RECORD") {
						tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td height="60" width="100%" class="CELULAS"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Não foi encontrada nenhuma empresa.';
						tmp += '</p></td></tr></table>';
						listBlock.innerHTML = tmp;
					}else if(result == "ERROR DB"){
						tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td height="60" width="100%" class="CELULAS"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Ocorreu um erro no banco de dados.';
						tmp += '</p></td></tr></table>';
						listBlock.innerHTML = tmp;
					}else if(result == "PARAM INVALID"){
						tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td height="60" width="100%" class="CELULAS"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Parametros inválidos.';
						tmp += '</p></td></tr></table>';
						listBlock.innerHTML = tmp;
					}else 
						listBlock.innerHTML = result;
				}
			}
		}
	    xmlhttp.send(null);
	}else 
		alert("Get List - Object xmlhttp nao foi encontrado.");
}
////////////////////////////////////////////////////////////////////
function showCat(tId){
	var icoStep2 = document.getElementById('icoStep2');
	var textStep2 = document.getElementById('textStep2');
	var listBlock = document.getElementById('catList2');
	listBlock.style.display = "block";
	
	var tmp = '', method = 'GET', result = '', urlAjax = domainLocal;
	urlAjax += 'includes/exec/getCatList.php?t='+tId;
	
	tmp = '<table border=0 cellspacing=0 width="100%" height="30%"><tr><td width="100%" class="TextObject" style="font-size: 13px"><p align="center">';
	tmp += '<img src="images/loader.gif" border="0" width="16" height="16" align="absmiddle" hspace="4">';
	tmp += 'Buscando as sub categorias, por favor aguarde...';
	tmp += '</p></td></tr></table>';
	listBlock.innerHTML = tmp;
	tmp = '';
	
	if (typeof xmlhttp != "undefined") {
		xmlhttp.open(method, urlAjax, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4)
			{
				if (xmlhttp.status == 404) 
		            alert("Status HTTP Response: Get Cat List DropDown - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else if (xmlhttp.status != 200) 
		            alert("Status HTTP Response: Get Cat List DropDown - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else {
					result = xmlhttp.responseText;
					if(result == "NO RECORD") {
						tmp = '<table border=0 cellspacing=0 width="100%" height="30%"><tr><td height="60" width="100%" class="TextObject" style="font-size: 13px"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Não foi encontrada nenhuma sub categoria.';
						tmp += '</p></td></tr></table>';
						listBlock.innerHTML = tmp;
					}else if(result == "ERROR DB"){
						tmp = '<table border=0 cellspacing=0 width="100%" height="30%"><tr><td height="60" width="100%" class="TextObject" style="font-size: 13px"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Ocorreu um erro no banco de dados.';
						tmp += '</p></td></tr></table>';
						listBlock.innerHTML = tmp;
					}else if(result == "PARAM INVALID"){
						tmp = '<table border=0 cellspacing=0 width="100%" height="30%"><tr><td height="60" width="100%" class="TextObject" style="font-size: 13px"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Parametros inválidos.';
						tmp += '</p></td></tr></table>';
						listBlock.innerHTML = tmp;
					}else{
						icoStep2.style.visibility = 'visible';
						textStep2.style.visibility = 'visible';
						listBlock.innerHTML = result;
					}
				}
			}
		}
	    xmlhttp.send(null);
	}else 
		alert("Get Cat List - Object xmlhttp nao foi encontrado.");
}
////////////////////////////////////////////////////////////////////
function showList(tId){
	var listAllBlock = document.getElementById('listAllBlock');
	
	var tmp = '', method = 'GET', result = '', urlAjax = domainLocal;
	urlAjax += 'includes/exec/getAllList.php?t='+tId;
	
	tmp = '<table border=0 cellspacing=0 width="100%"><tr><td width="100%" class="CELULAS" style="height: 30px"><p align="center">';
	tmp += '<img src="images/loader.gif" border="0" width="16" height="16" align="absmiddle" hspace="4">';
	tmp += 'Buscando as empresas, por favor aguarde...';
	tmp += '</p></td></tr></table>';
	listAllBlock.innerHTML = tmp;
	tmp = '';
	
	if (typeof xmlhttp != "undefined") {
		xmlhttp.open(method, urlAjax, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4)
			{
				if (xmlhttp.status == 404) 
		            alert("Status HTTP Response: Get All List DropDown - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else if (xmlhttp.status != 200) 
		            alert("Status HTTP Response: Get All List DropDown - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else {
					result = xmlhttp.responseText;
					if(result == "NO RECORD") {
						tmp = '<table border=0 cellspacing=0 width="100%"><tr><td width="100%" class="CELULAS" style="height: 200px"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Não foi encontrada nenhuma sub categoria.';
						tmp += '</p></td></tr></table>';
						listAllBlock.innerHTML = tmp;
					}else if(result == "ERROR DB"){
						tmp = '<table border=0 cellspacing=0 width="100%"><tr><td width="100%" class="CELULAS" style="height: 200px"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Ocorreu um erro no banco de dados.';
						tmp += '</p></td></tr></table>';
						listAllBlock.innerHTML = tmp;
					}else if(result == "PARAM INVALID"){
						tmp = '<table border=0 cellspacing=0 width="100%"><tr><td width="100%" class="CELULAS" style="height: 200px"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Parametros inválidos.';
						tmp += '</p></td></tr></table>';
						listAllBlock.innerHTML = tmp;
					}else 
						listAllBlock.innerHTML = result;
				}
			}
		}
	    xmlhttp.send(null);
	}else 
		alert("Get All List - Object xmlhttp nao foi encontrado.");
}
////////////////////////////////////////////////////////////////////
function viewData(id) 
{
	return;
}
////////////////////////////////////////////////////////////////////
function checkAssinante()
{
	var cellResult = document.getElementById('cellResult');
	var cpfcnpj = document.getElementById('cpfcnpj').value;
	var codassinatura = document.getElementById('codassinatura').value;
	
	var tmp = '', method = 'GET', result = '', urlAjax = domainLocal;
	urlAjax += 'includes/exec/consultaAssinante.php?cpfcnpj='+cpfcnpj+'&codassinatura='+codassinatura;
	
	cellResult.innerHTML = '<center><br><img src="images/loader.gif" border="0" width="16" height="16" align="absmiddle" hspace="4">Consultando a base de dados de Assinantes<br>do Correio do Estado. Por favor, aguarde...<br></center>';
	
	if (typeof xmlhttp != "undefined") {
		xmlhttp.open(method, urlAjax, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4)
			{
				if (xmlhttp.status == 404) 
		            alert("Status HTTP Response: consultaAssinante - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else if (xmlhttp.status != 200) 
		            alert("Status HTTP Response: consultaAssinante - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else {
					result = xmlhttp.responseText;
					if(result == "NO RECORD") 
						cellResult.innerHTML = '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">Assinante não encontrado!';
					else if(result.substring(0, 7) == "ERROR DB")
						cellResult.innerHTML = '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">'+result;
					else if(result == "PARAM INVALID")
						cellResult.innerHTML = '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">Parêmetros incorretos. Informe o CPF/CNPJ e o Código do Assinante.';
					else {
						result = result.split("|");
						tmp = '<font color="green"><b>Dados do Assinante:</b></font><br>';
						tmp += '<b>Código: </b>'+result[0]+'<br>';
						tmp += '<b>Nome: </b>'+result[1]+'<br>';
						tmp += '<b>E-mail: </b>'+result[2]+'<br>';
						tmp += '<b>CPF/CNPJ: </b>'+result[3]+'<br>';
						tmp += '<b>Situação Contratual: </b>'+result[4]+'<br>';
						cellResult.innerHTML = tmp;
					}
				}
			}
		}
	    xmlhttp.send(null);
	}else 
		alert("consultaAssinante - Object xmlhttp nao foi encontrado.");
}
///&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&/////////////////
function checkAssinanteNovo()
{
	var cellResult = document.getElementById('cellResult');
	var cpfcnpj = document.getElementById('cpfcnpj');
	var codassinatura = document.getElementById('codassinatura');
	var aceitaRegulamento = document.getElementById('aceitaRegulamento');
	
	var tmp = '', method = 'GET', result = '', urlAjax = domainLocal;
	
	cpfcnpj.value = cpfcnpj.value.replace(/ /g,'');
	codassinatura.value = codassinatura.value.replace(/ /g,'');
	//codassinatura.value = ApenasNum(codassinatura.value);
	if(!ConfereCIC(cpfcnpj)) {
		alert("O CPF ou CNPJ informado é inválido.");
		cpfcnpj.focus();
		return;
	}
	if(codassinatura.value.length <= 0) {
		alert("Informe o código de assinante.");
		codassinatura.focus();
		return;
	}
	if(aceitaRegulamento.checked == false) {
		alert("Você deve ler e aceitar o regulamento da promoção.");
		return;
	}
	
	urlAjax += 'includes/exec/consultaAssinante.php?cpfcnpj='+cpfcnpj.value+'&codassinatura='+codassinatura.value;
	
	cellResult.innerHTML = '<br><img src="images/loader.gif" border="0" width="16" height="16" align="absmiddle" hspace="4">Consultando a base de dados de Assinantes do Correio do Estado. Por favor, aguarde...<br>';
	
	if (typeof xmlhttp != "undefined") {
		xmlhttp.open(method, urlAjax, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4)
			{
				if (xmlhttp.status == 404) 
		            alert("Status HTTP Response: consultaAssinante - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else if (xmlhttp.status != 200) 
		            alert("Status HTTP Response: consultaAssinante - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else {
					result = xmlhttp.responseText;
					if(result == "NO RECORD") 
						cellResult.innerHTML = '<div style="padding-top: 10px; padding-left: 20px"><img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">Nenhum assinante encontrado com os dados informados.</div><br>Certifique-se de ter informado os dados corretamente, caso tenha dúvidas entre em <a href="contato">contato conosco</a>.';
					else if(result.substring(0, 7) == "ERROR DB")
						cellResult.innerHTML = '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">'+result;
					else if(result == "PARAM INVALID")
						cellResult.innerHTML = '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">Parêmetros incorretos. Informe o CPF/CNPJ e o Código do Assinante.';
					else {
						result = result.split("|");
						tmp = '<br><b>Confirme seus dados abaixo:</b><br><br><table border="0" cellpadding="2" cellspacing="2" class="style6">';
						tmp += '<tr><td><b>Código de Assinante: </b></td><td>'+result[0]+'</td></tr>';
						tmp += '<tr><td><b>Nome: </b></td><td>'+result[1]+'</td></tr>';
						tmp += '<tr><td><b>E-mail: </b></td><td>'+result[2]+'</td></tr>';
						tmp += '<tr><td><b>CPF/CNPJ: </b></td><td>'+result[3]+'</td></tr>';
						tmp += '<tr><td><b>Situação Contratual: </b></td><td>'+result[4]+'</td></tr>';
						tmp += '<tr><td colspan="2" align="center" style="padding-top: 4px"><input type="Hidden" id="codassinante" value="'+result[0]+'">';
						tmp += '<input type="Hidden" id="nome" value="'+result[1]+'"><input type="Hidden" id="email" value="'+result[2]+'">';
						tmp += '<input type="Hidden" id="cpfcnpjret" value="'+result[3]+'"><input type="Hidden" id="stc_id" value="'+result[5]+'">';
						tmp += '<input type="Button" class="inputSubmitButton" value="Confirmar" onclick="javascript: void cadastreSePromocao();">';
						tmp += '</td></tr>';
						tmp += '</table><br>';
						cellResult.innerHTML = tmp;
					}
				}
			}
		}
	    xmlhttp.send(null);
	}else 
		alert("consultaAssinante - Object xmlhttp nao foi encontrado.");
}

function cadastreSePromocao()
{
	var cellResult = document.getElementById('cellResultCad'), promocaoCod = document.getElementById('promocaoCod');
	var codassinante = document.getElementById('codassinante'), nome = document.getElementById('nome'), email = document.getElementById('email');
	var cpfcnpjret = document.getElementById('cpfcnpjret'), stc_id = document.getElementById('stc_id'), btnEnviar = document.getElementById('btnEnviar');
	var cpfcnpj = document.getElementById('cpfcnpj'), codassinatura = document.getElementById('codassinatura');
	
	var tmp = '', method = 'GET', result = '', urlAjax = domainLocal;
	urlAjax += 'includes/exec/cadastre-sePromocao.php';
	urlAjax += '?acao=cadastrar&promo_id='+promocaoCod.value+'&codassinante='+codassinante.value+'&stc_id='+stc_id.value+'&cpfcnpj='+cpfcnpjret.value;
	urlAjax += '&nome='+nome.value+'&email='+email.value;
		
	cpfcnpj.disabled = true;
	codassinatura.disabled = true;
	btnEnviar.disabled = true;
	
	cellResult.innerHTML = '<br><img src="images/loader.gif" border="0" width="16" height="16" align="absmiddle" hspace="4">Enviando seu cadastro para esta promoção. Por favor, aguarde...<br>';
	
	if (typeof xmlhttp != "undefined") {
		xmlhttp.open(method, urlAjax, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4)
			{
				if (xmlhttp.status == 404) 
		            alert("Status HTTP Response: cadastre-sePromocao - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else if (xmlhttp.status != 200) 
		            alert("Status HTTP Response: cadastre-sePromocao - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else {
					result = xmlhttp.responseText;
					if(result == "CADASTRADO") 
						cellResult.innerHTML = '<div style="padding-left: 40px"><img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">Você já se cadastrou nesta promoção !</div>';
					else if(result.substring(0, 7) == "ERROR DB")
						cellResult.innerHTML = '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">Ocorreu um erro ao realizar seu cadastro para participar da promoção. Por favor entre em contato conosco, clique <a href="contato">aqui</a>.';
					else if(result == "OK")
						cellResult.innerHTML = '<img src=imagens/aviso_ok.gif width=26 height=31 hspace=4 align=absmiddle>Seu cadastro foi realizado com sucesso, agora você está participando desta promoção. Obrigado e Boa Sorte!';
				}
			}
		}
	    xmlhttp.send(null);
	}else 
		alert("cadastre-sePromocao - Object xmlhttp nao foi encontrado.");
}
//////////////////////////////////////////////////////////////////////////

// Verifica se tem plugin do frashi =:P

var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
if (plugin) {
	plugin = parseInt(plugin.description.substring(plugin.description.indexOf(".")-1)) >= 6;
} else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.userAgent.indexOf("Windows 95")>=0 || navigator.userAgent.indexOf("Windows 98")>=0 || navigator.userAgent.indexOf("Windows NT")>=0)) {
	document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n');
	document.write('on error resume next \n');
	document.write('plugin = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.5")))\n');
	document.write('if ( plugin <= 0 ) then plugin = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.6")))\n');
	document.write('<\/SCR' + 'IPT\> \n');
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function irSiteGrupo()
{
	var drop = document.getElementById('dropGrupo');
	if(drop.value != "") window.open(drop.value, '_blank');
}

function dropConvenio()
{
	var drop = document.getElementById('dropVantagens'), u = domainLocal+'vantagens?cat=';
	if(drop.value != "") {
		u += drop.value;
		window.open(u, '_top');
	}
}
////////////////////////////////////////////////////////////////////////////////
function backForm(t)
{
	if(t != '') { focusObj(t); selectTextObj(t); }
	disableInput('btnEnviar', false);
	disableInput('btnLimpar', false);
	showHideAllCombos('visible');
	WorkLayers('statusSendForm', 'none');
	setHtmlInElement('statusSendForm', '');
	return;
}
function submitForm(tf, tipo)
{
	var ret = false, tmp = '';
	
	disableInput('btnEnviar', true);
	disableInput('btnLimpar', true);
	showHideAllCombos('hidden');
	WorkLayers('statusSendForm', 'block');
	tmp = processando();
	setHtmlInElement('statusSendForm', tmp);
	tmp = '';
	
	if(tipo == "contato") {
		ret = vContato(tf);
		if(ret) sendContato(tf);
	}else if(tipo == "newsletter_cad") {
		ret = vCadNewsletter(tf);
		if(ret) sendCadNewsletter(tf);
	}else if(tipo == "newsletter_rem") {
		ret = vRemNewsletter(tf);
		if(ret) sendRemNewsletter(tf);
	}
	
	return false;
}
////////////////////////////////@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@?/////////////////////////////////////////################################///////////////////
function vContato(tf)
{
	var msgError = '', t = ''; tmp = '', ret = true, idxCBGF = 0, changeBackGroundField = new Array();
	
	for(var i=0; i<tf.elements.length; i++) {
		tf.elements[i].value = trimJS(tf.elements[i].value);
	}
	
	if ( tf['fcd_id'].value.length <= 0 ) {
		msgError += '• O campo com o "Destinatário" é obrigatório.<br>';
		t = (!t)?'fcd_id':t;
	}
	if ( tf['fctp_id'].value.length <= 0 ) {
		msgError += '• O campo com o "Tipo da Mensagem" é obrigatório.<br>';
		t = (!t)?'fctp_id':t;
	}
	if ( tf['nome'].value.length <= 0 ) {
		msgError += '• O campo com o "Nome" é obrigatório.<br>';
		t = (!t)?'nome':t;
		changeBackGroundField[idxCBGF] = 'nome';
		idxCBGF++;
	}
	if ( tf['email'].value.length <= 0 ) {
		msgError += '• O campo com o "E-mail" é obrigatório.<br>';
		t = (!t)?'email':t;
		changeBackGroundField[idxCBGF] = 'email';
		idxCBGF++;
	}else{
		if (!tf['email'].value.match(/^([\w\.\_\-]+)@([\w\_\-]+)((\.(\w+))+)$/)) {
    		msgError += '• E-mail inválido ou com mais de um e-mail preenchido.<br>';
			t = (!t)?'email':t;
			changeBackGroundField[idxCBGF] = 'email';
			idxCBGF++;
    	}
	}
	if ( tf['cidade'].value.length <= 0 ) {
		msgError += '• O campo com a "Cidade" é obrigatório.<br>';
		t = (!t)?'cidade':t;
		changeBackGroundField[idxCBGF] = 'cidade';
		idxCBGF++;
	}
	if ( tf['estado'].value.length <= 0 ) {
		msgError += '• O campo com a "Estado" é obrigatório.<br>';
		t = (!t)?'estado':t;
		changeBackGroundField[idxCBGF] = 'estado';
		idxCBGF++;
	}else{
		if ( tf['estado'].value.length < 2 ) {
			msgError += '• O campo com a "Estado" não foi preenchido corretamente.<br>';
			t = (!t)?'estado':t;
			changeBackGroundField[idxCBGF] = 'estado';
			idxCBGF++;
		}
	}
	if (tf['ddd'].value.replace(/ /g,'').length<=0 && tf['telefone'].value.replace(/ /g,'').length<=0){
		msgError += '• O campo com o "DDD" e "Telefone" são obrigatórios.<br>';
		t = (!t)?'ddd':t;
		changeBackGroundField[idxCBGF] = 'ddd';
		idxCBGF++;
	}else{
		if (tf['ddd'].value.replace(/ /g,'').length>0){
		    if (!tf['ddd'].value.match(/^\d\d$/) && !tf['ddd'].value.match(/^0(3|8)00/)){
		    	msgError += '• O campo com o "DDD" não foi preenchido corretamente.<br>';
				t = (!t)?'ddd':t;
				changeBackGroundField[idxCBGF] = 'ddd';
				idxCBGF++;
		    }
			if (!(tf['telefone'].value.match(/^\d{3,4}\-?\d\d\d\d$/) || tf['telefone'].value.match(/^0(3|8)00\-?\d{6,9}$/))){
		        msgError += '• O campo com o "Telefone" não foi preenchido corretamente.<br>';
				t = (!t)?'telefone':t;
				changeBackGroundField[idxCBGF] = 'telefone';
				idxCBGF++;
		    }
		}
	}
	if ( tf['assunto'].value.length <= 0 ) {
		msgError += '• O campo com o "Assunto" é obrigatório.<br>';
		t = (!t)?'assunto':t;
		changeBackGroundField[idxCBGF] = 'assunto';
		idxCBGF++;
	}
	if ( tf['mensagem'].value.length <= 0 ) {
		msgError += '• O campo com a "Mensagem" é obrigatório.<br>';
		t = (!t)?'mensagem':t;
		changeBackGroundField[idxCBGF] = 'mensagem';
		idxCBGF++;
	}
	if ( tf['imageVerification'].value.length <= 0 ) {
		msgError += '• O campo com o que está escrito na "Imagem de Verificação" não foi informado.\n';
		t = (!t)?'imageVerification':t;
		changeBackGroundField[idxCBGF] = 'imageVerification';
		idxCBGF++;
	}else{
		if(tf['imageVerification'].value.length != 4 ) {
			msgError += '• O campo com o que está escrito na "Imagem de Verificação" deve ter 4 caracteres.\n';
			t = (!t)?'imageVerification':t;
			changeBackGroundField[idxCBGF] = 'imageVerification';
			idxCBGF++;
		}
	}
	
	if(msgError != "") {
		tmp = layerErro(msgError, t);
		setBGFieldForm(tf, changeBackGroundField);
		setTimeout("setHtmlInElement('statusSendForm', tmp)", 600);
		setTimeout("focusObj('btnVoltarErroForm')", 900);
		ret = false;
	}
	
	return ret;
}
function sendContato(tf)
{
	var i = 0, idxDataForm = 0, strUrl = '', tmp = '', method = 'POST', urlAjax = domainLocal;
	urlAjax += 'includes/exec/sendContact.php';
	urlToGo += 'contato/';
	
	var dataForm = new Array();
	var nameDataForm = new Array();
	
	if (typeof xmlhttp != "undefined") {
		disableInput('btnEnviar', true);
		disableInput('btnLimpar', true);
		WorkLayers('statusSendForm', 'block');
		tmp = processando();
		setHtmlInElement('statusSendForm', tmp);
		tmp = '';
		
		for(i; i<tf.elements.length; i++) {
			switch (tf.elements[i].name) {
				case 'actForm':
				case 'fcd_id':
				case 'fctp_id':
				case 'nome':
				case 'email':
				case 'cidade':
				case 'estado':
				case 'ddd':
				case 'telefone':
				case 'assunto':
				case 'mensagem':
				case 'imageVerification':
					dataForm[idxDataForm] = tf.elements[i].value;
					nameDataForm[idxDataForm] = tf.elements[i].name;
					idxDataForm++;
					break;
				default: continue;
			}
		}
		strUrl = joinVars2Url(nameDataForm, dataForm, method);
		
		if(method == "GET") urlAjax += strUrl;
		
		xmlhttp.open(method, urlAjax, true);
		
		if(method == "POST") {
			//xmlhttp.setRequestHeader('Content-Type','text/xml');
			//xmlhttp.setRequestHeader('Content-Type','text/html');
			xmlhttp.setRequestHeader('Encoding','ISO-8859-1');
			xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlhttp.setRequestHeader('Content-length', strUrl.length);
		}
		
        xmlhttp.onreadystatechange = handle_sendContato;
        
		if(method == "POST") xmlhttp.send(strUrl);
		else xmlhttp.send(null);
		
    }else{
		alert("Object xmlhttp nao foi encontrado.");
	}
}
function handle_sendContato()
{
	var result;
	if (xmlhttp.readyState == 4)
	{
		if (xmlhttp.status == 404) 
            alert("Status sendContato HTTP Response: " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
        else if (xmlhttp.status != 200) 
            alert("Status sendContato HTTP Response: " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
        else {
			result = xmlhttp.responseText.split("|");
			
			if(result[0]=="enviado") {
				WorkLayersVisible('formPage', 'hidden');
				tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td width="100%" align="center">';
				tmp += '<table border="0" width="390" style="border: 2px solid #ADB9C2" bgcolor="#FFFFFF" cellpadding="5" cellspacing="2" align="center" class="style6">';
				tmp += '<tr><td align="center" style="line-height: 190%" class="style6"><b>'+result[1]+'</b></td></tr>';
				tmp += (urlToGo)?'<tr><td align="center"><input type="Button" class="inputSubmitButton" value="OK" style="width: 70px" onclick="javascript: void _go(\''+urlToGo+'\');"></td></tr>':'';
				tmp += '</table></td></tr></table>';
			}else if(result[0]=="erro") {
				tmp = layerErro(result[1], '');
			}
			
			setHtmlInElement('statusSendForm', tmp);
		}
	}
	return;
}

function vCadNewsletter(tf)
{
	var msgError = '', t = ''; tmp = '', ret = true, idxCBGF = 0, changeBackGroundField = new Array();
	
	for(var i=0; i<tf.elements.length; i++) {
		tf.elements[i].value = trimJS(tf.elements[i].value);
	}
	
	if ( tf['nome'].value.length <= 0 ) {
		msgError += '• O campo com o "Nome" é obrigatório.<br>';
		t = (!t)?'nome':t;
		changeBackGroundField[idxCBGF] = 'nome';
		idxCBGF++;
	}
	if ( tf['email'].value.length <= 0 ) {
		msgError += '• O campo com o "E-mail" é obrigatório.<br>';
		t = (!t)?'email':t;
		changeBackGroundField[idxCBGF] = 'email';
		idxCBGF++;
	}else{
		if (!tf['email'].value.match(/^([\w\.\_\-]+)@([\w\_\-]+)((\.(\w+))+)$/)) {
    		msgError += '• E-mail inválido ou com mais de um e-mail preenchido.<br>';
			t = (!t)?'email':t;
			changeBackGroundField[idxCBGF] = 'email';
			idxCBGF++;
    	}
	}
	if ( tf['uf_id'].value.length <= 0 ) {
		msgError += '• O campo com a "Estado" é obrigatório.<br>';
		t = (!t)?'uf_id':t;
		changeBackGroundField[idxCBGF] = 'uf_id';
		idxCBGF++;
	}
	
	if ( tf['cid_id'].value.length <= 0 ) {
		msgError += '• O campo com a "Cidade" é obrigatório.<br>';
		t = (!t)?'cid_id':t;
		changeBackGroundField[idxCBGF] = 'cid_id';
		idxCBGF++;
	}
	
	if ( tf['ncad_diaaniversario'].value.length > 0  || tf['ncad_mesaniversario'].value.length > 0 ) {
		if ( (tf['ncad_diaaniversario'].value.length <= 0  && tf['ncad_mesaniversario'].value.length > 0) || (tf['ncad_diaaniversario'].value.length > 0  && tf['ncad_mesaniversario'].value.length <= 0) ) {
			msgError += '• Preencha corretamente o campo "Aniversário", selecione o dia e mês.<br>';
			t = (!t)?'ncad_diaaniversario':t;
			changeBackGroundField[idxCBGF] = 'ncad_diaaniversario';
			idxCBGF++;
		}
	}
	
	if(msgError != "") {
		tmp = layerErro(msgError, t);
		setBGFieldForm(tf, changeBackGroundField);
		setTimeout("setHtmlInElement('statusSendForm', tmp)", 600);
		setTimeout("focusObj('btnVoltarErroForm')", 900);
		ret = false;
	}
	
	return ret;
}

function sendCadNewsletter(tf)
{
	var i = 0, idxDataForm = 0, strUrl = '', tmp = '', method = 'POST', urlAjax = domainLocal;
	urlAjax += 'includes/exec/sendCadNewsletter.php';
	urlToGo += 'newsletter/';
	
	var dataForm = new Array();
	var nameDataForm = new Array();
	
	if (typeof xmlhttp != "undefined") {
		disableInput('btnEnviar', true);
		disableInput('btnLimpar', true);
		WorkLayers('statusSendForm', 'block');
		tmp = processando();
		setHtmlInElement('statusSendForm', tmp);
		tmp = '';
		
		for(i; i<tf.elements.length; i++) {
			switch (tf.elements[i].name) {
				case 'actForm':
				case 'nome':
				case 'email':
				case 'uf_id':
				case 'cid_id_hidden':
				case 'cid_id':
				case 'ap_id':
				case 'ncad_diaaniversario':
				case 'ncad_mesaniversario':
					dataForm[idxDataForm] = tf.elements[i].value;
					nameDataForm[idxDataForm] = tf.elements[i].name;
					idxDataForm++;
					break;
				default: continue;
			}
		}
		strUrl = joinVars2Url(nameDataForm, dataForm, method);
		
		if(method == "GET") urlAjax += strUrl;
		
		xmlhttp.open(method, urlAjax, true);
		
		if(method == "POST") {
			//xmlhttp.setRequestHeader('Content-Type','text/xml');
			//xmlhttp.setRequestHeader('Content-Type','text/html');
			xmlhttp.setRequestHeader('Encoding','ISO-8859-1');
			xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlhttp.setRequestHeader('Content-length', strUrl.length);
		}
		
        xmlhttp.onreadystatechange = handle_sendCadNewsletter;
        
		if(method == "POST") xmlhttp.send(strUrl);
		else xmlhttp.send(null);
		
    }else{
		alert("Object xmlhttp nao foi encontrado.");
	}
}
function handle_sendCadNewsletter()
{
	var result;
	if (xmlhttp.readyState == 4)
	{
		if (xmlhttp.status == 404) 
            alert("Status sendContato HTTP Response: " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
        else if (xmlhttp.status != 200) 
            alert("Status sendContato HTTP Response: " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
        else {
			result = xmlhttp.responseText.split("|");
			
			if(result[0]=="enviado") {
				WorkLayersVisible('formPage', 'hidden');
				tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td width="100%" align="center">';
				tmp += '<table border="0" width="390" style="border: 2px solid #ADB9C2" bgcolor="#FFFFFF" cellpadding="5" cellspacing="2" align="center" class="style6">';
				tmp += '<tr><td align="center" style="line-height: 190%" class="style6"><b>'+result[1]+'</b></td></tr>';
				tmp += (urlToGo)?'<tr><td align="center"><input type="Button" class="inputSubmitButton" value="OK" title="'+urlToGo+'" style="width: 70px" onclick="javascript: void _go(\''+urlToGo+'\');"></td></tr>':'';
				tmp += '</table></td></tr></table>';
			}else if(result[0]=="duplicado") {
				tmp = layerErro(result[1], '');
			}else if(result[0]=="erro") {
				tmp = layerErro(result[1], '');
			}
			
			setHtmlInElement('statusSendForm', tmp);
		}
	}
	return;
}


function vRemNewsletter(tf)
{
	var msgError = '', t = ''; tmp = '', ret = true, idxCBGF = 0, changeBackGroundField = new Array();
	
	for(var i=0; i<tf.elements.length; i++) {
		tf.elements[i].value = trimJS(tf.elements[i].value);
	}
	
	if ( tf['codigo'].value.length <= 0 || tf['nome'].value.length <= 0 || tf['email'].value.length <= 0 ) {
		msgError += '• E-mail não encontrado em nossa base de dados.<br>Caso queira entre em contato conosco clicando <a href="'+urlToGo+'/falecom/">aqui</a><br>';
	}
	
	if(msgError != "") {
		tmp = layerErro(msgError, t);
		setTimeout("setHtmlInElement('statusSendForm', tmp)", 600);
		setTimeout("focusObj('btnVoltarErroForm')", 900);
		ret = false;
	}
	
	return ret;
}
function sendRemNewsletter(tf)
{
	var i = 0, idxDataForm = 0, strUrl = '', tmp = '', method = 'POST', urlAjax = domainLocal;
	urlAjax += 'includes/exec/sendRemNewsletter.php';
	urlToGo += 'newsletter/';
	
	var dataForm = new Array();
	var nameDataForm = new Array();
	
	if (typeof xmlhttp != "undefined") {
		disableInput('btnEnviar', true);
		disableInput('btnLimpar', true);
		WorkLayers('statusSendForm', 'block');
		tmp = processando();
		setHtmlInElement('statusSendForm', tmp);
		tmp = '';
		
		for(i; i<tf.elements.length; i++) {
			switch (tf.elements[i].name) {
				case 'actForm':
				case 'codigo':
					dataForm[idxDataForm] = tf.elements[i].value;
					nameDataForm[idxDataForm] = tf.elements[i].name;
					idxDataForm++;
					break;
				default: continue;
			}
		}
		strUrl = joinVars2Url(nameDataForm, dataForm, method);
		
		if(method == "GET") urlAjax += strUrl;
		
		xmlhttp.open(method, urlAjax, true);
		
		if(method == "POST") {
			//xmlhttp.setRequestHeader('Content-Type','text/xml');
			//xmlhttp.setRequestHeader('Content-Type','text/html');
			xmlhttp.setRequestHeader('Encoding','ISO-8859-1');
			xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlhttp.setRequestHeader('Content-length', strUrl.length);
		}
		
        xmlhttp.onreadystatechange = handle_sendRemNewsletter;
        
		if(method == "POST") xmlhttp.send(strUrl);
		else xmlhttp.send(null);
		
    }else{
		alert("Object xmlhttp nao foi encontrado.");
	}
}
function handle_sendRemNewsletter()
{
	var result;
	if (xmlhttp.readyState == 4)
	{
		if (xmlhttp.status == 404) 
            alert("Status sendContato HTTP Response: " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
        else if (xmlhttp.status != 200) 
            alert("Status sendContato HTTP Response: " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
        else {
			result = xmlhttp.responseText.split("|");
			
			if(result[0]=="enviado") {
				WorkLayersVisible('formPage', 'hidden');
				tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td width="100%" align="center">';
				tmp += '<table border="0" width="390" style="border: 2px solid #ADB9C2" bgcolor="#FFFFFF" cellpadding="5" cellspacing="2" align="center" class="style6">';
				tmp += '<tr><td align="center" style="line-height: 190%" class="style6"><b>'+result[1]+'</b></td></tr>';
				tmp += (urlToGo)?'<tr><td align="center"><input type="Button" class="inputSubmitButton" value="OK" style="width: 70px" onclick="javascript: void _go(\''+urlToGo+'\');"></td></tr>':'';
				tmp += '</table></td></tr></table>';
			}else if(result[0]=="erro") {
				tmp = layerErro(result[1], '');
			}
			
			setHtmlInElement('statusSendForm', tmp);
		}
	}
	return;
}
////////////////////////////////////////////////////////////////////
function clearFormCadNewsletter()
{
	setTimeout("setCities()", 700);
}
////////////////////////////////////////////////////////////////////
function setCities()
{
	var uf = document.getElementById('uf_list');
	var city_list = document.getElementById('city_list');
	var cid_id_hidden = document.getElementById('cid_id_hidden');
	var selectUfResult = document.getElementById('selectUfResult');
	var newOption, setSelectedOption = 0;
	var urlAjax = domainLocal;
	urlAjax += 'includes/exec/list_cities_dropdown.php?uf_id='+uf.value+'&cid_id='+cid_id_hidden.value;
	
	city_list.innerHTML = "";
	newOption = createOption('', 'Selecionando cidades...');
	city_list.appendChild(newOption);
	city_list.disabled = true;
	
	var method = 'GET', result = '', string = '', i = 0, dados;
	
	if (typeof xmlhttp != "undefined") {
		xmlhttp.open(method, urlAjax, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4)
			{
				if (xmlhttp.status == 404) 
		            alert("Status HTTP Response: Get List Cities DropDown - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else if (xmlhttp.status != 200) 
		            alert("Status HTTP Response: Get List Cities DropDown - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else {
					result = xmlhttp.responseText;
					if(result == "NO RECORD") 
						selectUfResult.innerHTML = 'Não foram encontradas cidades.';
					else if(result == "ERROR DB") 
						selectUfResult.innerHTML = 'Ocorreu um erro no banco de dados.';
					else {
						result = result.split("#");
						
						city_list.innerHTML = "";
						for(i=0; i<result.length; i++) {
							dados = result[i].split("|");
							if(dados[2]=="selected") setSelectedOption = i;
							newOption = createOption(dados[0], dados[1]);
							city_list.appendChild(newOption);
						}
						setTimeout("setSelectedCities("+setSelectedOption+")", 100);
					}
				}
			}
		}
	    xmlhttp.send(null);
	}else 
		alert("Get List Cities DropDown - Object xmlhttp nao foi encontrado.");
}
function setSelectedCities(n)
{
	var city_list = document.getElementById('city_list');
	city_list.disabled = false;
	city_list.selectedIndex = n;
}
function createOption(valueOption, textOption) {
	var newOpt = document.createElement("option");
	newOpt.setAttribute("value", valueOption);
	var tempTextOption = document.createTextNode(textOption);
	newOpt.appendChild(tempTextOption);
	return newOpt;
}
/////////////////////////////////////////////////@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@??????????????///////////////#################################//////////////////
var codsFaq = new Array();
function showHideFaq(codFaq)
{
	var p = document.getElementById('pergunta_'+codFaq);
	var r = document.getElementById('resposta_'+codFaq);
	
	if(r.style.display == 'none') r.style.display = 'block';
	else if(r.style.display == 'block') r.style.display = 'none';
}
function showHideAllFaq(acao)
{
	for(var i=0; i<codsFaq.length; i++) {
		if(document.getElementById('resposta_'+codsFaq[i]) != null) {
			document.getElementById('resposta_'+codsFaq[i]).style.display = acao;
		}
	}
}

////////////////////////////////////////////////////////////////////////////////////////

function sortConveniados(sortField, tId){
	var listBlock = document.getElementById('list'+tId);
	var heightlistBlock = listBlock.clientHeight;
	var qbusca = document.frmq.q.value;
	
	var tmp = '', method = 'GET', result = '', urlAjax = domainLocal;
	urlAjax += 'includes/exec/getList.php?sort_field='+sortField+'&t='+tId+'&q='+qbusca;
	
	tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td height="60" width="100%" class="style6"><p align="center">';
	tmp += '<img src="images/loader.gif" border="0" width="16" height="16" align="absmiddle" hspace="4">';
	tmp += 'Buscando as empresas, por favor aguarde...';
	tmp += '</p></td></tr></table>';
	listBlock.style.height = heightlistBlock+'px';
	listBlock.innerHTML = tmp;
	tmp = '';
	
	if (typeof xmlhttp != "undefined") {
		xmlhttp.open(method, urlAjax, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4)
			{
				if (xmlhttp.status == 404) 
		            alert("Status HTTP Response: Get List DropDown - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else if (xmlhttp.status != 200) 
		            alert("Status HTTP Response: Get List DropDown - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else {
					result = xmlhttp.responseText;
					if(result == "NO RECORD") {
						tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td height="60" width="100%" class="CELULAS"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Não foi encontrada nenhuma empresa.';
						tmp += '</p></td></tr></table>';
						listBlock.innerHTML = tmp;
					}else if(result == "ERROR DB"){
						tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td height="60" width="100%" class="CELULAS"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Ocorreu um erro no banco de dados.';
						tmp += '</p></td></tr></table>';
						listBlock.innerHTML = tmp;
					}else if(result == "PARAM INVALID"){
						tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td height="60" width="100%" class="CELULAS"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Parametros inválidos.';
						tmp += '</p></td></tr></table>';
						listBlock.innerHTML = tmp;
					}else 
						listBlock.innerHTML = result;
				}
			}
		}
	    xmlhttp.send(null);
	}else 
		alert("Get List - Object xmlhttp nao foi encontrado.");
}

////////////////////////////////////////////////////////////////////////////////////

function browser () {
	var b = navigator.appName;
	var v = this.version = navigator.appVersion;
	var ua = navigator.userAgent.toLowerCase();	
	this.v = parseInt(v);
	this.safari = ua.indexOf("safari")>-1;	// always check for safari & opera 
	this.opera = ua.indexOf("opera")>-1;	// before ns or ie
	this.ns = !this.opera && !this.safari && (b=="Netscape");
	this.ie = !this.opera && (b=="Microsoft Internet Explorer");
	this.gecko = ua.indexOf('gecko')>-1; // check for gecko engine
	if (this.ns) {
		this.ns4 = (this.v==4);
		this.ns6 = (this.v>=5);	
		this.b = "Netscape";
	}else if (this.ie) {
		this.ie4 = this.ie5 = this.ie55 = this.ie6 = false;
		if (v.indexOf('MSIE 4')>0) {this.ie4 = true; this.v = 4;}
		else if (v.indexOf('MSIE 5')>0) {this.ie5 = true; this.v = 5;}
		else if (v.indexOf('MSIE 5.5')>0) {this.ie55 = true; this.v = 5.5;}
		else if (v.indexOf('MSIE 6')>0) {this.ie6 = true; this.v = 6;}
		this.b = "MSIE";
	}else if (this.opera) {
		this.v=parseInt(ua.substr(ua.indexOf("opera")+6,1)); // set opera version
		this.opera6=(this.v>=6);
		this.opera7=(this.v>=7);
		this.b = "Opera";
	}else if (this.safari) {
		this.ns6 = (this.v>=5);	// ns6 compatible correct?
		this.b = "Safari";
	}
	this.dom = (document.createElement && document.appendChild && document.getElementsByTagName)? true : false;
	this.def = (this.ie||this.dom);
	this.win32 = ua.indexOf("win")>-1;
	this.mac = ua.indexOf("mac")>-1;
	this.other = (!this.win32 && !this.mac);
	this.supported = (this.def||this.ns4||this.ns6||this.opera)? true:false;
};

window.onresize = init;
var block;
var a = 0;
function init(divId){
	naveg = new browser();
	
	divId = (!divId)?"divDados":divId;
	
	if(naveg.ie || naveg.opera){
		//alert(window.screenLeft)
		if(document.all[divId]) block = document.all[divId].style;
		//block.left = (window.screen.availWidth-parseInt(block.width)-33)
		//block.left = (document.body.clientWidth-parseInt(block.width))-document.body.scrollLeft - 10;
		//block.left = 350;
	} else if (naveg.ns4){
		alert("2");
		if(document.layers[divId]) block = document.layers[divId];
		//block.left = (window.screen.availWidth-33)-142
		//block.left = (window.innerWidth-100)-window.pageXOffset - 70;
		//block.left = 350;
	} else if (naveg.ns6){
		if( document.getElementById(divId) ) block = document.getElementById(divId).style;
		//block.left = (window.screen.availWidth-parseInt(block.width)-30)
		//block.left = (document.body.clientWidth-parseInt(block.width))-window.pageXOffset - 12;
		//block.left = 350;
	}
	//a = 0;
}
function ad(){
 if(block)
 {
	if(naveg.ie || naveg.opera){
		posY = document.body.scrollTop;
	} else if (naveg.ns){
		posY = window.pageYOffset;
	} else if (naveg.ns6){
		posY = window.pageYOffset;
	}
	if((posY % 2) !== 0) posY-=1;
	if(posY+12 != parseInt(block.top))
	{
		for(i=0; i<5; i++){
			if (posY+12 > parseInt(block.top)) a+= 2; else a-=2;
			block.top = a;
		}
	}
	setTimeout("ad()",10);
 }
}
//////////////////////////////////////////////////////////////////////////////////
function detalhesConveniado(cadId){
	var tmp = '', method = 'GET', result = '', urlAjax = domainLocal;
	urlAjax += 'includes/exec/getDetails.php?cad_id='+cadId;
	var tLayer = document.getElementById('divDados');
	
	tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td height="60" width="100%" class="style6"><p align="center">';
	tmp += '<img src="images/loader.gif" border="0" width="16" height="16" align="absmiddle" hspace="4">';
	tmp += 'Buscando dados da empresa, por favor aguarde...';
	tmp += '</p></td></tr></table>';
	tLayer.innerHTML = tmp;
	tLayer.style.display = 'block';
	tmp = '';
		
	if (typeof xmlhttp != "undefined") {
		xmlhttp.open(method, urlAjax, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4)
			{
				if (xmlhttp.status == 404) 
		            alert("Status HTTP Response: getDetails DropDown - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else if (xmlhttp.status != 200) 
		            alert("Status HTTP Response: getDetails DropDown - " + xmlhttp.status + "\nError: " + xmlhttp.statusText);
		        else {
					result = xmlhttp.responseText;
					if(result == "NO RECORD") {
						tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td height="60" width="100%" class="CELULAS"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Não foi encontrada nenhuma empresa.';
						tmp += '</p></td></tr></table>';
						tLayer.innerHTML = tmp;
					}else if(result == "ERROR DB"){
						tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td height="60" width="100%" class="CELULAS"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Ocorreu um erro no banco de dados.';
						tmp += '</p></td></tr></table>';
						tLayer.innerHTML = tmp;
					}else if(result == "PARAM INVALID"){
						tmp = '<table border=0 cellspacing=0 width="100%" height="100%"><tr><td height="60" width="100%" class="CELULAS"><p align="center">';
						tmp += '<img src="images/ico_ops.gif" border="0" width="12" height="12" align="absmiddle" hspace="4">';
						tmp += 'Parametros inválidos.';
						tmp += '</p></td></tr></table>';
						tLayer.innerHTML = tmp;
					}else 
						tLayer.innerHTML = result;
				}
			}
		}
	    xmlhttp.send(null);
	}else 
		alert("getDetails - Object xmlhttp nao foi encontrado.");
}

function fecharDetalhes()
{
	var tLayer = document.getElementById('divDados');
	tLayer.style.display = 'none';
	tLayer.innerHTML = '';
}
