// JavaScript Document
//---------------------------------------------------------------------------------------------
//Mostra e some um objeto
function showHide(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}else {
		el.style.display = 'block';
	}
}

//---------------------------------------------------------------------------------------------
// FUNÇÃO QUE RETORNA O OBJETO COM DO ID INFORMADO
function getObj(id) {
	if(document.getElementById(id)){
		el = document.getElementById(id);
		return el;
	}
}
//---------------------------------------------------------------------------------------------
// MY NAVEGATOR
// myNavegator ();
function myNavSuport () {
	var ttNS4 = (document.layers) ? true : false;           // the old Netscape 4
	var ttIE4 = (document.all) ? true : false;              // browser wich uses document.all
	var ttDOM = (document.getElementById) ? true : false;   // DOM-compatible browsers
	if (ttDOM) { // if DOM-compatible
		return ('DOM');
	}
	else if (ttIE4) {
		return ('IE4');
	}
	else if (ttNS4) {
		return ('NS4');
	}
}
//---------------------------------------------------------------------------------------------
// APARECE E SOME COM UM OBJETO SEM DEFORMAR O LAYOUT COM FADEIN E FADEOUT OPICIONAL
// showHideStay('ID','On' ou 0) --> 0 = zero
function showHideStay (obj,fade) {
	if(document.getElementById(obj)){
		var el = document.getElementById(obj);
		if ( el.style.visibility != 'hidden' ) {
			if(fade == 'On'){
				// aplica um fade in no objeto
				fadeOut(obj,1);
			}
			el.style.visibility = 'hidden';
			return true;
		}else {
			if(fade == 'On'){
				// aplica um fade in no objeto
				fadeIn(obj,1);
			}
			el.style.visibility = 'visible';
			return true;
		}
	}else{
		return false;
	}	
}
//---------------------------------------------------------------------------------------------
// SIMULADOR DE PAGEX E PAGEY PARA O IE
// pageXYforIE(id);
// retorna as coordenadas X e Y em um array onde:
// o indice 1 = eixo X, e 
// o indice 2 = eixo Y
function pageXYforIE (id) {
    // reference to TooltipContainer
    if (id) {
		  nav = myNavSuport();
        if (nav == 'NS4') {
            objTarget = document.id;
        } else if (nav == 'IE4') {
            objTarget = document.all(id);
        } else if (nav == 'DOM') {
            objTarget = document.getElementById(id);
        } else {
            return;
        }

        if ( typeof( objTarget ) == 'undefined' ) {
            return;
        }
    }
	 var ttXpos = 0, ttYpos = 0;
	 var ttXadd = 0, ttYadd = 0;
    var plusX=0, plusY=0, docX=0, docY=0;
    var divHeight = objTarget.clientHeight;
    var divWidth  = objTarget.clientWidth;
    if (navigator.appName.indexOf("Explorer")!=-1) {
        if (document.documentElement && document.documentElement.scrollTop) {
            plusX = document.documentElement.scrollLeft;
            plusY = document.documentElement.scrollTop;
            docX = document.documentElement.offsetWidth + plusX;
            docY = document.documentElement.offsetHeight + plusY;
        } else {
            plusX = document.body.scrollLeft;
            plusY = document.body.scrollTop;
            docX = document.body.offsetWidth + plusX;
            docY = document.body.offsetHeight + plusY;
        }
    } else {
        docX = document.body.clientWidth;
        docY = document.body.clientHeight;
    }

    ttXpos = ttXpos + plusX;
    ttYpos = ttYpos + plusY;

    if ((ttXpos + divWidth) > docX)
        ttXpos = ttXpos - (divWidth + (ttXadd * 2));
    if ((ttYpos + divHeight) > docY)
        ttYpos = ttYpos - (divHeight + (ttYadd * 2));

    pageXY = new Array(2);
	 pageXY[1] = (ttXpos + ttXadd);
	 pageXY[2] = (ttYpos + ttYadd);
    return(pageXY);
}

//---------------------------------------------------------------------------------------------
// APARECE E SOMO COM UM OBJETO DEFORMANDO O LAYOUT COM FADEIN E FADEOUT OPICIONAL
// showHideOut('ID','On' ou 0) --> 0 = zero
function showHideOut (obj,fade,hideroot) {
	//alert(window.currentlyVisibleElement);
	if(document.getElementById(obj)){
		var el = document.getElementById(obj);
		if ( el.style.display != 'none' ) {
			if(fade == 'On'){
				// aplica um fade in no objeto
				fadeOut(obj,1);
			}
			el.style.display = 'none';
			if (hideroot == 1) {
				window.currentlyVisibleElement = false;
			}
			return true;
		}else {
			if(fade == 'On'){
				// aplica um fade in no objeto
				fadeIn(obj,1);
			}
			if (hideroot == 1) {
				hideCurrentElement();
				window.currentlyVisibleElement = obj;
			}
			el.style.display = 'block';
			return true;
		}
	}else{
		return false;
	}
}
//---------------------------------------------------------------------------------------------
// FUNÇÃO PARA O IE TROCAR O BACKGROUND DE UM ELEMENTO ONMOUSEOVER EVENT (SEM SER UM LINK)
function bgChangeHover (obj,color) {
	if(getStyles(obj)) {
		newBackground = getStyles(obj);
		newBackground.backgroundColor = color;
		return true;
	} else {
		return false;
	}
}
//---------------------------------------------------------------------------------------------
// APARECE UMA POPUP NA POSIÇÃO DO MOUSE
// showPopup ('ID', event) --> event não altera
// variáveis de armzenamento para controlar onde a popup irá aparecer em relação à posição do cursor
// súmeros positivos estão abaixo e a direita do cursor, números negativos estão acima e a esquerda

function showPopup (targetObjectId,eventObj) {
	var xOffset = 20;//30
	var yOffset = -5;//-5
    if(eventObj) {
	// esconde qualque popup visível
	hideCurrentPopup();
	// interrompe propagação de eventos fugitivos (event Bublling) no core do navegador)
	eventObj.cancelBubble = true;
	// move a div popup para a posição atual do cursor  
	// simulação do pageX e pageY para o IE com a função pageXYforIE();
	IEscroll = pageXYforIE(targetObjectId);
	var newXCoordinate = (eventObj.pageX)?eventObj.pageX + xOffset:eventObj.clientX + xOffset + ((IEscroll[1])?IEscroll[1]:0);
	var newYCoordinate = (eventObj.pageY)?eventObj.pageY + yOffset:eventObj.clientY + yOffset + ((IEscroll[2])?IEscroll[2]:0);
	moveObject(targetObjectId, newXCoordinate, newYCoordinate);
	// e a torna visível
	if( showHideOut(targetObjectId,'On') ) {
	    // se a popup foi apresentada corretamente
	    // armazena seu Id em um objeto de acessibilidade global
	    window.currentlyVisiblePopup = targetObjectId;
	    return true;
	} else {
	    // não pode mostrar a popup!
	    return false;
	}
    } else {
	// não há evento do objeto, sem permisão para reposicionamento, parou aqui.
	return false;
    }
} // showPopup

//---------------------------------------------------------------------------------------------
// ESCONDE OU APRESENTA A POPUP ARMAZENADA NO OBJETO GLOBAL window.currentlyVisiblePopup
function hideCurrentPopup () {
    if(window.currentlyVisiblePopup) {
		getStyles(window.currentlyVisiblePopup).display = 'none';
		window.currentlyVisiblePopup = false;
    }
} // hideCurrentPopup

//---------------------------------------------------------------------------------------------
// ESCONDE OU APRESENTA ELEMENTO ARMAZENADO NO OBJETO GLOBAL window.currentlyVisibleElement
function hideCurrentElement () {
    if(window.currentlyVisibleElement) {
		getObj(window.currentlyVisibleElement).style.display = 'none';
		window.currentlyVisibleElement = false;
    }
} // hideCurrentPopup
//---------------------------------------------------------------------------------------------
// FUNÇÃO CROSS-BROWSER OBTER O STYLE DE UM OBJETO POR MEIO DE SEU ID
function getStyles (objectId) {
    if(document.getElementById && document.getElementById(objectId)) {
	// W3C DOM
	return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
	// MSIE 4 DOM
	return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
	// NN 4 DOM.. nota: este não encontrava layers aninhadas
	return document.layers[objectId];
    } else {
	return false;
    }
} // getStyles

//---------------------------------------------------------------------------------------------
// MOVIMENTA O OBJETO ALTERANDO SUAS COORDENADAS.
// OBTEM ATRAVÉS DA FUNÇÃO CROSS-BROWSER getStyles, O STYLE DO OBJETO PELO ID,
// OBSERVANDO SE O OBJETO REALMENTE EXISTE
function moveObject (objectId, newXCoordinate, newYCoordinate) {
	var styleObject = getStyles(objectId);
    if(styleObject) {
		styleObject.left = newXCoordinate+'px';
		styleObject.top = newYCoordinate+'px';
		return true;
   	} else {
		// o objeto não foi encontrado, logo ele não será movimentado
		return false;
    }
} // moveObject

//---------------------------------------------------------------------------------------------
// ADICIONA O VALOR DE UM OBJETO NÓ A UM TEXTBOX APARTIR DE UM EVENTO (ON EVENT)
function putValueTxt (originText,targetText) {
	var txtOrigin = document.getElementById(originText);
	var objTarget = document.getElementById(targetText);	
	if ( objTarget && txtOrigin ) {
		objTarget.value = txtOrigin.firstChild.nodeValue;
	}
}

//---------------------------------------------------------------------------------------------
// ADICIONA O VALOR DE UM OBJETO NÓ PARA OUTRO APARTIR DE UM EVENTO (ON EVENT)
// putObjText (targetText,originText) --> targetText é o id do obj receptor 
// e o originText é o obj que tem o texto original
function putObjText (originText,targetText) {
	var txtOrigin = document.getElementById(originText);
	var objTarget = document.getElementById(targetText);
	if ( objTarget && txtOrigin ) {
		objTarget.innerHTML = txtOrigin.firstChild.nodeValue;
	}		
}
//---------------------------------------------------------------------------------------------
// ADICIONA O VALOR DE TEXTO A UM OBJETO APARTIR DE UM EVENTO (ON EVENT)
function putTexto (text,targetText) {
	var objTarget = document.getElementById(targetText);	
	if (objTarget) {
		objTarget.value = text;
	}
}
//---------------------------------------------------------------------------------------------
// APRESENTA OU ESCONDE UM OBJETO, COM REDIRECIONAMENTO.
// A FUNÇÃO REDIRECT() NECESSITA ESTAR CARREGADA
function showHideRedir (obj,redirectto) {
	if(document.getElementById(obj)){
		var el = document.getElementById(obj);
		if ( el.style.display != 'none' ) {
			el.style.display = 'none';
		}else {
			el.style.display = 'block';
		}
	}else {
		redirect(redirectto);
	}
}
//---------------------------------------------------------------------------------------------
// REDIRECIONA PÁGINAS
function redirect (redirectto){
	window.location.href ='http://'+redirectto;
}
//---------------------------------------------------------------------------------------------
// FUNÇÃO POPUP 
function popup (url,width,height){
	window.open(url,'MANECO','width='+width+',height='+height+',top=200,left=300');
}
//---------------------------------------------------------------------------------------------
// FUNÇÃO PARA FAZER UM RELOAD NA PÁGINA
function rld () {
document.location.reload()
}
//-----------------------------------------------------------------------------------------------
// FUNÇÃO PARA CRIAR UM JUMP MENU 
// AO FAZER ALGUMA ALTERAÇÃO NO MENU ELE REDIRECIONA PARA A URL NO VALUE DA TAG OPTION
// MM_jumpMenu('parent',this,0)
<!--
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}
//-->

//-----------------------------------------------------------------------------------------------
// FUNÇÃO PARA FAZER UM FADE IN OU FADE OUT (USADA NA FUNÇÃO SHOWPOPUP)
// fadeOut('ID', 1) --> 1 é o tempo
// fadeIn('ID', 1)
function fadeOut(id, time) {
	target = document.getElementById(id);
	alpha = 100;
	timer = time;//(time*1000)/50;
	var i = setInterval(
			function() {
				if (alpha <= 0)
					clearInterval(i);
				setAlpha(target, alpha);
				alpha -= 2;
			}, timer);
}
// FUNÇÃO FADE IN
function fadeIn(id, time) {
	target = document.getElementById(id);
	alpha = 0;
	timer = time;//(time*1000)/50;
	var i = setInterval(
			function() {
				if (alpha >= 100)
					clearInterval(i);
				setAlpha(target, alpha);
				alpha += 2;
			}, timer);
}
// ESTA FUNÇÃO DEFINE A TRANSPARÊNCIA (USADA NAS FUNÇÕES FADEOUT E FADEIN)
function setAlpha(target, alpha) {
	target.style.filter = "alpha(opacity="+ alpha +")";
	target.style.opacity = alpha/100;
}
//-----------------------------------------------------------------------------------------------
// PARA ACESSAR ELEMENTOS APARTIR DA KEYWORD THIS
// getThis(element) --> element == 'id' ou um element
// retorna o objeto(elemento) --> obj = getThis(this); --> obj.style.top ou obj.
// getThis('id').firstChild.innerHTML += getThis('id').firstChild.innerHTML;
function getThis(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (Object.isString(element))
    element = document.getElementById(element);
  return Element.extend(element);
}
//-----------------------------------------------------------------------------------------------
// SCROLL TO ID ( Precisa do Scriptaculos + Prototype)
function scrollToId (id) {
	new Effect.ScrollTo(id,{duration:3.0});
}
//-----------------------------------------------------------------------------------------------
// TEXT FIELD READYONLY TRUE OR FALSE
// set_readonly('obj','objListen');
function set_readonly(obj,objListen) {
	obj = getThis(obj);
	objListen = getThis(objListen);
   if (objListen.style.display == 'none') {
       obj.removeAttribute('readonly');
   } else {
       obj.setAttribute('readonly', 'true');
   }
}
//-----------------------------------------------------------------------------------------------
// FUNÇÃO DESENVOLVIDA SOMENTE PARA O SELETOR
// list --> id da lista atual
// listItem --> id do item atual da lista
// textBox --> id de um campo textFild de um formulário
// reDir --> se diferente de 0 redireciona a página (URL)
// inEvent --> escolher de acordo com o evento "over, click ou out"
function seletor (list, listItem, textBox, reDir, inEvent, eventObj) {
	//if (list && listItem && textBox && reDir) {
		if (inEvent == 'over') {
			showPopup ('altText', eventObj);
			putObjText (listItem, 'altText');
			bgChangeHover (listItem, '#999999');
		} else if (inEvent == 'click') {
			putValueTxt (listItem, textBox);
			putValueTxt ("value_"+listItem, "value_"+textBox);
			showHideOut (list);
			if (reDir != 0) {
				redirect (reDir);
			}
		} else if (inEvent == 'out') {
			hideCurrentPopup();
			bgChangeHover (listItem, '#CCCCCC');
		}// else if
	//} else {
	//	return false;
	//}// else
}// function seletor
//-----------------------------------------------------------------------------------------------
// FUNÇÃO CHECK BOX
//
function checkbox(obj,objdisplay){
	
	var box = getThis(obj).style;
	var objtarget = getThis(objdisplay).style;
	if (box.display == 'block') {
		box.display = 'none';
		objtarget.display = 'block';
		if(objdisplay == 'check'){
			putTexto('ok','valuecheck');
		} else {
			putTexto(' ','valuecheck');
		}
		
	}
}
//---------------------------------------------------------------------------------------------
// ADICIONA UM INNERHTML 
// NÃO DEXAR ESPAÇOS ENTRE AS TAGS HTML

function innerCod (pagina) {
	var objTarget = getThis('conteudoSuspenso');

/////////////////////////DICAS///////////////////////////////////////////////

	if(pagina == 'cadastra'){
		var cod = '';
       
    }          	
	
	
	
	if (pagina != 'fechar') {
		objTarget.innerHTML = cod;
		objTarget.style.display = 'block';
	}
	if (pagina == 'fechar') {
		objTarget.innerHTML = '	';
		objTarget.style.display = 'none';
	}
}

          
//---------------------------------------------------------------------------------------------
//chama lightbox  pelo flash
   

function SWFDelegate(url,width,height,caption) {
   var objLink = document.createElement('a');
   objLink.setAttribute('href',url);
   objLink.setAttribute('rel','lightbox');
   objLink.setAttribute('title',caption);
   if(typeof width != 'undefined') {
      objLink.setAttribute('width',width);
   }
   if(typeof height != 'undefined') {
      objLink.setAttribute('height',height);
   }
   Lightbox.prototype.start(objLink);
}

//---------------------------------------------------------------------------------------------
//máscara em campos de formulário
//Uma solução simples e crossbrowser com expressões regulares

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function telefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function cpf(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function cep(v){
    v=v.replace(/D/g,"")                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}

function cnpj(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}

function romanos(v){
    v=v.toUpperCase()             //Maiúsculas
    v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que não for I, V, X, L, C, D ou M
    //Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
    while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
        v=v.replace(/.$/,"")
    return v
}

function site(v){
    //Esse sem comentarios para que você entenda sozinho ;-)
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
        caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}

//-------------------------------------------------------------------------------------------------------------
//COMPARA SENHA e verifica demais dados

function compara(){
	if( document.formCadastra.senha.value != document.formCadastra.senharep.value){
		
		alert("Senha incorreta!!! Favor confirme a senha novamente");
		formCadastra.senharep.focus();
		return false;
		
		}
	if( isNaN(document.formCadastra.tel.value) ){
		
		alert("Somente números em telefone !!!");
		document.formCadastra.tel.value="";
		formCadastra.tel.focus();
		return false;
		
		}		

return true;		
}


//-------------------------------------------------------------------------------------------------------------
//VERIFICA DADOS EM CONTATO

function verificaCont(){

	if( isNaN(document.formCont.telefone.value) ){
		
		alert("Somente números em telefone !!!");
		formCont.telefone.focus();
		return false;
		
		}
	if( document.formCadastra.senha.value != document.formCadastra.senharep.value){
		
		alert("Senha incorreta!!! Favor confirme a senha novamente");
		formCadastra.senharep.focus();
		return false;
		
		}

return true;		
}


//-------------------------------------------------------------------------------------------------------------
//VERIFICA DADOS EM CADASTRO SUSPENSO

function verCadAcompanha(){

	if( document.formSuspCadastra.senha.value != document.formSuspCadastra.senharep.value){
		
		alert("Senha incorreta!!! Favor confirme a senha novamente");
		formSuspCadastra.senharep.focus();
		return false;
		
		}

return true;		
}

//--------------------------------------------------------------------------------------------------------------
//WEBMAIL.JS DO DIAL HOST

function form_onsubmit() {
  // Está variavel contem o nome do formulário que será "webmail"
  var f = document.webmail;
  // Aqui iremos perguntar se o campo com o nome "email" é igual a branco
  if (f.email.value == '') {
    alert("O campo de email não pode estar em branco!");
    f.email.focus();
    return false;
  }
  if (window.RegExp) {
    // Aqui fazemos uma verificação se é um email valido
    var reg = /^[a-z0-9]+([_.-][a-z0-9]+)*\@[a-z0-9]+([.-][a-z0-9]+)*([.]([a-z0-9]{2,4}|[0-9]{1,3}))+$/i;
    if (!reg.test(f.email.value)) {
      alert("Email invalido! Digite o email completo.");
      return false;
    }
  }
  // Aqui iremos perguntar se o campo com o nome "password" é igual a branco
  if (f.password.value == '') {
    alert("O campo de senha não pode estar em branco!");
    f.password.focus();
    return false;
  }
  // Se tudo ocorrer certo o script retorna true (verdadeiro) para o formulário html
  return true;
} 
