// JavaScript Document
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}


function ajaxInit () {

	var xmlhttp;

	try {
		xmlhttp = new XMLHttpRequest ();
	} catch (ee) {
		try {
			xmlhttp = new ActiveXObject ("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp = false;
			}
		}
	}

	return xmlhttp ;
}




function AjaxCon () {

  this.xmlhttp

  try {
	this.xmlhttp = new XMLHttpRequest ()
  } catch (ee) {
	try {
      this.xmlhttp = new ActiveXObject ("Msxml2.XMLHTTP")
	} catch (e) {
	  try {
		this.xmlhttp = new ActiveXObject ("Microsoft.XMLHTTP")
	  } catch (E) {
		  this.xmlhttp = false;
      }
    }
  }
}





function addEvent(o, evType, func, useCapture)
{
  if(o.addEventListener)
    o.addEventListener(evType, func, useCapture);
	else if(o.attachEvent)
    o.attachEvent("on" + evType, func);
	else
	  alert("Handler could not be attached");
}



function removeEvent(o, evType, func)
{
  if(o.detachEvent){
    o.detachEvent('on'+evType,func);
  }
  else if (o.removeEventListener){
    o.removeEventListener(evType,func,false);
  }
  else alert("Handler could not be removed");
}



 function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1)
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }
	

function retira_acentos(txt)
{
  txt = txt.toLowerCase()
  
	var estranha = "áéíóúàèìòùâêîôûäëïöüãõç"

  var correta = "aeiouaeiouaeiouaeiouaoc"

  var retorno = ""
  
	for(i=0; i<estranha.length; i++)
  {
    for(j=0; j<txt.length; j++)
    {
      retorno = txt.replace(estranha.substr(i,1),correta.substr(i,1))
      retorno = retorno.replace("_","")
      txt = retorno
    }
  }
	
	return (txt)
}



function jumpto(obj)
{
	if (obj.value.length == obj.maxLength)
	{
		for (var i = 0; i < obj.form.length; i++)
		{
			if (obj.form[(i-1)] == obj)
			{
				obj.form[i].focus()
				break;
			}
		}
	}
}



function validaAcao() {
	var DivPreloader = 'preloader';
	var DivErro = 'error';
}




/*
 PARAMS:
 # action
 # parametros
*/
function prepara_ajax_post(act, param) {
	Ajax = ajaxInit()

	if (Ajax)
	{
		Ajax.open('POST', act, true)
		Ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
		Ajax.setRequestHeader("Content-length", param.length)
		Ajax.setRequestHeader('Content-Type', "application/x-www-form-urlencoded; charset=iso-8859-1")
		Ajax.send(param)

		return true
	}
	else return false
}



/*
 PARAMS:
 # formulario
 # action
 # parametros
 # array para readystage
 # array para manipular erros
*/
function submitPost(frm, act, param, readystage, falha, operacaocompletada) {
	Ajax = ajaxInit()

	if (Ajax) {
		Ajax.open('POST', act, true)
		Ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
		Ajax.setRequestHeader("Content-length", param.length)
		Ajax.setRequestHeader('Content-Type', "application/x-www-form-urlencoded; charset=iso-8859-1")
		Ajax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
		Ajax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");  
		Ajax.setRequestHeader("Pragma", "no-cache"); 
		Ajax.send(param)

		Ajax.onreadystatechange = function() {
		    /*
			  # 1 (a carregar)
			  # 2 (carregado)
			  # 3 (interactivo)
			  # 4 (completo)
			*/

			if (readystage[Ajax.readyState]) setTimeout(readystage[Ajax.readyState], 0)

			if (Ajax.readyState == 4) {
				if (Ajax.status == 200) {
					if (Ajax.responseText == '')
					{
						setTimeout(operacaocompletada, 0)
						return true
					}
					else
					{
						setTimeout(falha, 0)
						return Ajax.responseText
					}
				}
				else
					setTimeout(falha, 0)
			}
		}
	}
}





function createElement(pai, elem, id, Name, text)
{
	var filho = document.createElement(elem);

	if (id)   filho.setAttribute('id', id);
	if (Name) filho.setAttribute('name', Name);
	if (text) filho.innerHTML = text

	pai.appendChild(filho);
	
	return true
}



function deleteElement(pai)
{
     var elem = pai.childNodes[pai.childNodes.length-1];
     pai.removeNode(elem);
}



function removeTag(tag)
{
	tag.parentNode.removeChild(tag)
}



function removeconteudo(tag){
	while (tag.firstChild)
	{
	  tag.removeChild(tag.firstChild);
	}
}


function clonarNode(n) {

	if (!n)
		return alert (n+' não encontrado no documento.')

	var clone = n.cloneNode(true)
	n.parentNode.appendChild(clone)
	
	return clone
}


function replace_for_himself(obj) {
	
	var clone = obj.cloneNode(true)
	obj.parentNode.replaceChild(clone, obj); 
}


function getCheckedValueRadio(radioObj) {
	if(!radioObj) return "";

	var radioLength = radioObj.length;

	if(radioLength == undefined)
	{
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	}

	for(var i = 0; i < radioLength; i++)
	{
		if(radioObj[i].checked)
			return radioObj[i].value;
	}
	return "";
}



/*
 PARAMS:
 # objeto select
*/
function getCheckedValueSelect(slct, ind)
{
    var indice = slct.selectedIndex

    return ind ? indice : slct.options[indice].value
}



/*
 PARAMS:
 # objeto check
*/
function getCheckedCheckbox(obj)
{
  if (!obj) return false
	
	var valores = new Array()

  if (typeof(obj.length) == 'undefined' && obj.checked) // só tem um checkbox
	  valores[0] = obj.value
	else
	{
	  for(i = 0; i < obj.length; i++)
	  {
		  if (obj[i].checked) {
			  valores.push(obj[i].value)
		  }
	  }
	}

	if (valores.length > 0)
	  return valores
	else
	  return false
}



function campo_value(c, foc)
{	
	var valor

	
	if (typeof(c) == 'string')
		valor = c
	
	else if (typeof(c) == 'object')
	{
		// input
		if (c.tagName.search(/^input$/i) != -1)
		{
			switch(c.type)
			{
				case 'text':
					valor = c.value
					break
				case 'hidden':
					valor = c.value
					break
				case 'radio':
					valor = getCheckedValueRadio(c)
					break
			}
		}
		//select
		else if (c.tagName.search(/^select$/i) != -1) 
			valor = getCheckedValueSelect(c)
		//textarea
		else if (c.tagName.search(/^textarea$/i) != -1) 
			valor = c.value

		if (valor == '' && foc)
			c.focus()
	}
	
	return valor
}


function checkAllChecks(obj)
{
	for(i = 0; i < obj.length; i++)
	{
		obj[i].checked = true
	}
}



function uncheckAllChecks(obj)
{
	for(i = 0; i < obj.length; i++)
	{
		obj[i].checked = false
	}
}



function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);

    if(typeof(mail) == "string")
	{
        if(er.test(mail)) return true
    }
	else if(typeof(mail) == "object")
	{
        if(er.test(mail.value)) return true
    }
	else return false;
}


function urlString(url) {
  var er = new RegExp(/[^\w_\-:\/\.\?\&=]+/);
	
	if(er.test(url)) return false
	
	return true
}


function soNumerais(campo){
	var digits="0123456789.,"
	var campo_temp
	for (var i=0;i<campo.value.length;i++){
	  campo_temp=campo.value.substring(i,i+1)
	  if (digits.indexOf(campo_temp)==-1){
		    campo.value = campo.value.substring(0,i);
		    break;
	  }
	}
}


function dropmenu(obj, hidden)
{
	var objUL = obj.getElementsByTagName('ul')[0]
	
	addEvent(objUL,  'mouseover', function(){objUL.className = 'over'}, false)

	if (hidden) objUL.className = 'out'
				 else objUL.className = 'over'
}



function QScatch (chv) {

	var url = document.location.toString()

	if (url.indexOf('?') == -1 || url.indexOf('=') == -1)
		return false


	var queries_captadas = new Array()

	var linhaquery = url.slice(url.indexOf("?")+1)


	if (linhaquery.search(/&/) != -1)
	{
		var queries = linhaquery.split('&')

		for (var i = 0; i < queries.length; i++) {
			
			var valores = queries[i].split('=')
			queries_captadas[valores[0]] = valores[1]
		}
	}
	else {
		var valores = queries[i].split('=')
		queries_captadas[valores[0]] = valores[1]
	}
	
	if (!queries_captadas[chv])
		return false

	return queries_captadas[chv]
}


function loading_ajax() {
	return '<img src="img/layout/2009/icons/ajax.gif">'
}


function ajax_simple_get(url)
{
  ajax = ajaxInit()

  if (ajax) {
    ajax.open ('GET', url, true)
	ajax.onreadystatechange = function() {
		if (ajax.readyState == 4) {
			if (ajax.status == 200)	{
				return ajax.responseText
			}
		}
	}
    ajax.send (null)
  }
}



function callpage(url, divconteudo)
{
	Ajax = ajaxInit()

	if (Ajax)
	{
		//var DivLoading = document.getElementById(div)
		var Div = document.getElementById(divconteudo)

		Ajax.open('GET', url, true)
		
		Ajax.onreadystatechange = function()
		{
			if (Ajax.readyState == 4)
			{
				if (Ajax.status == 200)
				{
					var StringRetorno = Ajax.responseText
					// retira tag javascript
					if (Ajax.responseText.indexOf('</script>') > -1) {
					  // tag deve estar como 1º ou último elemento da página chamada via ajax
						var Ini   = StringRetorno.indexOf('<script>') == 0 ? (StringRetorno.indexOf('</script>') + 9) : 0
						var Final = StringRetorno.indexOf('<script>') == 0 ? StringRetorno.length - 1 : StringRetorno.indexOf('<script>')

						StringRetorno = StringRetorno.substr(Ini, Final)
						
						var Script = Ajax.responseText.substring((Ajax.responseText.indexOf('<script>') + 8), Ajax.responseText.indexOf('</script>'))
					}


					if (document.images.loading) removeTag(document.images.loading)

					// <--- Verificando se a página chamada contém funções javascripts ou estilos externas --->
					// script
					if (Script)
					{
  					 createElement (document.getElementsByTagName('head')[0], 'script')
             var TagScript = document.getElementsByTagName('script')[(document.getElementsByTagName('script').length - 1)]
					   TagScript.text = Script
          }
					// <--- FIM --->

					
					Div.innerHTML = StringRetorno
				}
			}
		}
		Ajax.send(null)
  }
}








function call_submenus(url, div, obj)
{
  removeconteudo(document.getElementById('contenttext'))
  clear_all_ext()

  add_loading(document.getElementById('contenttext'), 2)

  callpage(url, div)

  var objA = obj.parentNode.parentNode.getElementsByTagName('a')
	
	for (i = 0; i < objA.length; i++) {
	  if (objA[i] == obj) obj.className = 'ativo'
	 else objA[i].className = ''
	}
}



//------------------------------------------
//---- A D D  U M  L O A D E R  A J A X ----
//------------------------------------------
function add_loading(div, tipo) {
  if (!document.images.loading) {
	  createElement(div, 'img', 'loading', 'loading')
		document.images.loading.className = 'loading'
		
		//----- ESCOLHE A IMAGEM LOADER -------
		var Src = ''
		switch(tipo)
		{
		  case 0:
			Src = 'img/icons/ajax-loader.gif'
			break;
			case 1:
			Src = 'img/icons/ajax-loader-h5n1.gif'
			break;
			case 2:
			Src = 'img/icons/ajax-loader-pik-cinza-branco.gif'
			break;
			case 3:
			Src = 'img/icons/ajax-circle-balls.gif'
			break;
			default:
			Src = 'img/icons/ajax-loader.gif'
			break;
		}
		//------------ // ---------------

		document.images.loading.src = Src
	}
}


//----------------------------------------------------------------
//---- M E N S A G E M  G E R A L  P /  R E Q U I S I Ç Õ E S ----
//----------------------------------------------------------------
function msg_requisicao(msg, err, divparent) {
  var TagMsg = document.getElementById('msgrequisicao')
	
  if (!TagMsg)
	  creteElement(divparent, 'p', 'msgrequisicao')
	
	if (err) //se a for para exibir uma mensagem de erro
	  TagMsg.className = 'retornoerro'
  else
	  TagMsg.className = 'retornook'

  TagMsg.style.display = 'block'
	TagMsg.innerHTML = msg
}



//-------------------------------------------------------------------
//---- R E M O V E  A  M E N S A G E M  D E  R E Q U I S I Ç Ã O ----
//-------------------------------------------------------------------
function remove_msg_requisicao(tempo, exc) {
  var TagMsg = document.getElementById('msgrequisicao')

  var Esperar = tempo && parseInt(tempo) > 0 ? parseInt(tempo) : 0
	
	if (exc)
    window.setTimeout(function(){removeTag(TagMsg)}, Esperar)
	else
  	window.setTimeout(function(){TagMsg.style.display = 'none'}, Esperar)
}






//###########################################
//####### P L A N O S  D E  F U N D O #######
//###########################################
function planodefundo(obj, t) {
	if (!document.getElementById('planodefundo'))
	{
	  createElement(obj, 'div', 'planodefundo')
  
	  var DivClass = ''
	  switch(t)
		{
		  case 0:
			DivClass = 'planodefundowhite'
			break;
			default:	
			DivClass = 'planodefundowhite'
			break;
		}
		document.getElementById('planodefundo').className = DivClass
		document.getElementById('planodefundo').style.zIndex = document.getElementsByTagName('div').length
	}
}

// RETIRAR PLANO DE FUNDO
function hidplanodefundo() {
  removeTag(document.getElementById('planodefundo'))
}






function pureswf(url,width,height,wm){

	document.write("<object type='application/x-shockwave-flash' data='"+url+"' width='"+width+"' height='"+height+"'>");
	document.write("<param name='movie' value='"+url+"'>");
	document.write("<param name='quality' value='high'>");
	document.write("<param name='wmode' value='"+wm+"'>");
	document.write("<param name='SCALE' value='exactfit'>");
	document.write("<param name='menu' value='false'>");
	document.write("</object>");

}
