var ns4=document.layers;
var ie4=document.all;
var ns6=document.getElementById&&!document.all;
var acao = '';
var trs = new Array();
var unicos    = new Array();
var multi = new Array();
var total = 0;
var div_atual = '';
var base_href;

function iniciar(assinatura)
{
  ob = document.getElementsByTagName('base');
  base_href = ob[0].href;
  overlay_init();
 
}
 function comando_exec(classe, metodo, adados) 
 {
  //acao_historico(classe, metodo, adados);
  //alert('c:'+classe+' m:'+metodo);
   cmd.exec(classe,metodo,adados);  
 }

function acao_historico(classe, metodo, parametros)
{
	var complexObject = new Object();
    complexObject.classe = classe;
    complexObject.metodo = metodo;
    complexObject.parametros  = parametros;  
	acao = "acao"+parametros[1][1];
   dhtmlHistory.add("acao"+parametros[1][1], complexObject);
	

}
function historyChange(newLocation,  historyData) {
  /*debug("A history change has occurred: "
        + "newLocation="+newLocation
        + ", classe="+historyData.classe, 
        false);*/
   if (!dhtmlHistory.isFirstLoad()) 
   {

     cmd.exec(historyData.classe,historyData.metodo,historyData.parametros);  
   }
}


  function debug(msg, clear) {
        var dbg = document.getElementById("debug_area");
		if(dbg)
		{
          if (clear == true)
            dbg.innerHTML = "<p>" + msg + "</p>";
          else 
		  {
            dbg.innerHTML =  "<p>" + msg + "</p>" + dbg.innerHTML;
          }
		}
      }


function erro_validacao(campo)
{
  obcampo =document.getElementById('t_'+campo);
  if(obcampo.className.indexOf('_erro') < 0)
  {						   
    obcampo.className = obcampo.className + '_erro';
  }
}
function restaurar_erro_validacao(campo)
{
  obcampo =document.getElementById('t_'+campo);
  if(obcampo)
  {
    if(obcampo.className.indexOf('_erro') > 0)
    {						   
      obcampo.className = obcampo.className.replace('_erro', ''); ;
    }
  }
}

function preparar_form(nome)
 {
   f= document.forms[nome];
   c = 0;
   var tfrm = new Array();
	for (var i=0;i<f.elements.length;i++) 
	{
	 
	  if(f.elements[i].type == 'checkbox' || f.elements[i].type == 'radio')
	  { //alert(f.elements[i].checked);
		 if(f.elements[i].checked) 
		 {
			 tfrm[c]    = new Array();
	         tfrm[c][0] = f.elements[i].name;
	         tfrm[c][1] = f.elements[i].value;
			 c++;
		 }
	  }
	  else
	  {
	    tfrm[c]    = new Array();
	    tfrm[c][0] = f.elements[i].name;
	    tfrm[c][1] = f.elements[i].value;
		c++;
	  }
	}
	return tfrm;
 }


function overlay_init()
{
	var objBody = document.getElementsByTagName("body").item(0);
	// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.onclick = function () {hideLightbox(); return false;}
	objOverlay.style.display = 'none';
	objOverlay.style.position = 'absolute';
	objOverlay.style.top = '0';
	objOverlay.style.left = '0';
	objOverlay.style.zIndex = '90';
 	objOverlay.style.width = '100%';
	objBody.insertBefore(objOverlay, objBody.firstChild);
	
	// create lightbox div, same note about styles as above
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','alerta');
	objLightbox.style.display = 'none';
	objLightbox.style.position = 'absolute';
	objLightbox.style.zIndex = '100';	
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);	
    objLightbox.innerHTML = "<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td><table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td width='8' class='jn_TL_ss'>&nbsp;</td>                <td   class='jn_T mao' >ALERTA</td>				<td width='19' align='center'  class='jn_T mao' ><img src='/templates/padrao_sc/images/botao_fechar.gif' width='18' height='18' class='mao' onClick='hideLightbox()'></td><td width='8' class='jn_TR_ss'>&nbsp;</td></tr></table></td></tr><tr><td align='center' bgcolor='#FFFFFF' class='jn_M_ss'><table width='100%'  border='0' cellspacing='0' cellpadding='0'><tr><td><div id='alerta_area'></div></td></tr>   <tr><td align='center'><div id='alerta_icone'></div></td></tr>   <tr><td><div id='alerta_input'></div></td></tr>  <tr><td><div id='alerta_botoes'></div></td></tr> </table></td></tr><tr><td><table width='100%'  border='0' cellspacing='0' cellpadding='0'><tr><td class='jn_BL_ss'>&nbsp;</td><td class='jn_B_ss'>&nbsp;</td><td class='jn_BR_ss'>&nbsp;</td></tr></table></td></tr></table>";

/*
	var objdebugbox = document.createElement("div");
	objdebugbox.setAttribute('id','debug');
	objdebugbox.style.display  = 'block';
	objdebugbox.style.position = 'absolute';
	objdebugbox.style.zIndex   = '100';		
	objdebugbox.style.width    = '300px';

    objdebugbox.innerHTML = "<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td><table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td width='8' class='jn_TL_ss'>&nbsp;</td>                <td width='265'  class='jn_T mao' >DEBUG</td>				<td width='19' align='center'  class='jn_T mao' ><img src='/templates/padrao_sc/images/botao_fechar.gif' width='18' height='18' class='mao' onClick='hideLightbox()'></td><td width='8' class='jn_TR_ss'>&nbsp;</td></tr></table></td></tr><tr><td align='center' bgcolor='#FFFFFF' class='jn_M_ss'><table width='100%'  border='0' cellspacing='0' cellpadding='0'><tr><td><div id='debug_area'></div></td></tr></table></td></tr><tr><td><table width='100%'  border='0' cellspacing='0' cellpadding='0'><tr><td class='jn_BL_ss'>&nbsp;</td><td class='jn_B_ss'>&nbsp;</td><td class='jn_BR_ss'>&nbsp;</td></tr></table></td></tr></table>";
    objBody.insertBefore(objdebugbox, objOverlay.nextSibling);	
	*/
// var objLightbox = document.getElementById('lightbox');  
   
   //objBody.insertBefore(objLightbox, objOverlay.nextSibling);


}

function botao_alerta(label,classe,funcao,id)
{
	
  objbt = document.getElementById('alerta_botoes');

  bt_html = '<input type="button" name="Button" value="'+label+'"';
  if(classe)
   bt_html += 'class="'+classe+'"';
  if(funcao)
   bt_html += 'onClick="'+funcao+';"';
  if(id)
    bt_html += 'id="'+id+'"';

   bt_html += '>&nbsp;';
   objbt.innerHTML += bt_html;


}
/********************/
function input_alerta(label,classe,funcao,id)
{
 // "<input name='titulo_documento' type='text' class='text' id='titulo_documento' value='{$dados->titulo_documento}'>
  objbt = document.getElementById('alerta_input');

  bt_html = '<input type="text" name="'+id+'" value="'+label+'"';
  if(classe)
   bt_html += 'class="'+classe+'"';
  if(funcao)
   bt_html += 'onChange="'+funcao+';"';
  if(id)
    bt_html += 'id="'+id+'"';

   bt_html += '>&nbsp;';
   objbt.innerHTML += bt_html;


}
/********************/
function icone_alerta(icone)
{
 objbt = document.getElementById('alerta_icone');
  bt_html = '<img src="/icones/'+icone+'" >';  
  objbt.innerHTML = bt_html;
}

function esconder_alerta()
{
	hideLightbox();
}
function hideLightbox()
{
	// get objects
	objOverlay = document.getElementById('overlay');
	objLightbox = document.getElementById('alerta');  

	// hide lightbox and overlay
	objOverlay.style.display = 'none';
	objLightbox.style.display = 'none';

	// make select boxes visible
	selects = document.getElementsByTagName("select");
    for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}

	// disable keypress listener
	document.onkeypress = '';
}


function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function mostrar_alerta(msg)
{
	// prep objects
	document.getElementById('alerta_area').innerHTML = msg;  
	document.getElementById('alerta_botoes').innerHTML = '';  
	document.getElementById('alerta_input').innerHTML = '';  
	document.getElementById('alerta_icone').innerHTML = '';  

	var objOverlay = document.getElementById('overlay');
	var objLightbox = document.getElementById('alerta');  
	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
/*
	// center loadingImage if it exists
	if (objLoadingImage) {
		objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
		objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
		objLoadingImage.style.display = 'block';
	}*/

	// set height of Overlay to take up whole page and show
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';
    var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 150 ) / 2);
	var lightboxLeft = ((arrayPageSize[0] ) / 2 - 200);
		
	objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
	objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
    objLightbox.style.display = 'block';
		objLightbox.style.width = '400px';

   
	selects = document.getElementsByTagName("select");
        for (i = 0; i != selects.length; i++) {
                selects[i].style.visibility = "hidden";
        }
}

function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

function efeito_menu_on(menu) {	
	  menu.className = 'menu_on';	
}
function efeito_menu_off(menu) {	
	  menu.className = 'menu_off';	
}
function init_tabset(a_tabs) 
{
  t = new Bs_TabSet('tabset'); 
  for (var n_key in a_tabs)   
  {		
		
		t.addTab(a_tabs[n_key], document.getElementById(n_key));
  }
  	t.draw();	
	return t;
}

function seleciona(id)
{
	//alert(document.getElementById('item_'+id).id);
	//alert(document.forms['gerenciamento'].elements["itens[]"].length);
	document.getElementById('item_'+id).checked = !document.getElementById('item_'+id).checked;
	marcar_linha(id);
}

function marcar_linha(id)
{
	
	if(trs[id])
	{
	   document.getElementById('tr_'+id).className = trs[id];
	   trs[id] = '';
	   document.getElementById('item_'+id).checked = false;
	}
	else
	{
		trs[id] = document.getElementById('tr_'+id).className;		
		document.getElementById('tr_'+id).className = 'selecionado';
		document.getElementById('item_'+id).checked = true;
	}
	
	//calculando o total
	marcados = document.forms['gerenciamento'].elements["itens[]"];
    total = 0;
	
    if(marcados.length)
	{
	 for (i=0;i<marcados.length;i++)
     {
      
	   if(marcados[i].checked==true)
       {
         total++;
         atual = marcados[i].value;
       }
     }
	}
	else
	{
		total = 1;
        atual = marcados.value;
	}
	
	//tratando as opcoes unicas
	//for (var n_key in unicos) 
	
    for (i=0;i<unicos.length;i++)
    {
     
	  if(total == 1)
        habilitar_opcao(unicos[i]);
      else
	    desabilitar_opcao(unicos[i]);	
    }
 
    //tratando as opcoes multiplas
    for (i=0;i<multi.length;i++)
   {
     if(total != 0)
       habilitar_opcao(multi[i]);
     else
	   desabilitar_opcao(multi[i]);	
   }
}

/********************************************************************************/

function habilitar_opcao(botao)
{
	tipo_acao = acoes[botao];
	switch(tipo_acao)
	{
		case 'e': per = acoes_permitidas.substring(1,2); break;
		case 's': per = acoes_permitidas.substring(2,3); break;
		case 'a': per = acoes_permitidas.substring(3,4); break;
		default: per = '1'; break;
	}
	if(per == 1)
	{
		bitem =document.getElementById(botao);
		eval("bitem.onclick = f_"+botao+";");
		bitem.className = 'mao';
		bitem.src = bitem.src.replace('_off', '_on');
	}
}

function desabilitar_opcao(botao)
{	 
 bitem =document.getElementById(botao);
 eval("bitem.onclick = null;");
 bitem.className = '';
 bitem.src = bitem.src.replace('_on', '_off');
}

function valor(id)
{
  return document.getElementById(id).value;
}

function mudar_pagina(pg)
{
    document.forms['filtros'].elements['pg'].value = pg; 
    document.forms['filtros'].submit();
}
function mudar_letra(letra)
{
    document.forms['filtros'].elements['letra'].value = letra; 
    document.forms['filtros'].submit();
}
function mudar_filtro(onde,valor)
{
    document.forms['filtros'].elements[onde].value = valor; 
    document.forms['filtros'].submit();
}
function mudar_direcao(valor)
{
    document.forms['filtros'].elements['ordem'].value = valor; 
    document.forms['filtros'].elements['direcao'].value =  document.forms['filtros'].elements['nova_direcao'].value
    document.forms['filtros'].submit();
}

	function get_radio(rb)
	{
		var L=rb.length;
		var ret="";
        if(L >1)
        {
          for (var i = 0 ; i< L ; i++)
          { 
		    if(rb[i].checked) 
		    { 
		      ret=rb[i].value; 
			  break; 
		    } 
		   }
         }
       else
         ret=rb.value; 
       return(ret);
	}


function verificarCPF(c)
{
  var i; 
  s = c.replace('.','');
  s = s.replace('.','');
  s = s.replace('-','');
  var c = s.substr(0,9); 
  var dv = s.substr(9,2); 
  var d1 = 0; 
  var v = false;
  if(c == '111111111' || c == '222222222' || c == '333333333' || c == '444444444' || c == '555555555' || c == '666666666' || c == '777777777'|| c == '888888888' || c == '999999999' || c == '000000000')
  {
	 v = true; 
     return false; 
  }
  for (i = 0; i < 9; i++) 
  { 
    d1 += c.charAt(i)*(10-i); 
  } 
  if (d1 == 0)
  { 
     //alert("CPF Inválido")
     v = true; 
     return false; 
   } 
    d1 = 11 - (d1 % 11); 
    if (d1 > 9) d1 = 0; 
    if (dv.charAt(0) != d1) 
    { 
    //   alert("CPF Inválido") 
       v = true;
       return false; 
    } 

    d1 *= 2; 
    for (i = 0; i < 9; i++) 
    { 
      d1 += c.charAt(i)*(11-i); 
    } 
    d1 = 11 - (d1 % 11); 
    if (d1 > 9) d1 = 0; 
    if (dv.charAt(1) != d1) 
    { 
      //alert("CPF Inválido") 
      v = true;
      return false; 
    } 
    if (!v) 
	{
      //alert(c + "\nCPF Válido") 
	  return true;
    }
}

function verificarCNPJ(c)
{
    var b = [6,5,4,3,2,9,8,7,6,5,4,3,2];
   /* s = c.replace('.','');
    s = s.replace('.','');
    s = s.replace('-','');
    s = s.replace('/','');
	c = s;*/
    if((c = c.replace(/[^\d]/g,"").split("")).length != 14)
	{return false;}
    for(var i = 0, n = 0; i < 12; n += c[i] * b[++i]);
    if(c[12] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    for(var i = 0, n = 0; i <= 12; n += c[i] * b[i++]);
    if(c[13] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
    return true;
};

var Loader=new Object();

Loader.IsLoading=false;
Loader.Queue=new Array();
Loader.AddScript=function(scriptPath)
{
	Loader.Queue[Loader.Queue.length]=scriptPath;
	if (!this.IsLoading) 
	  this.CheckQueue();
};

Loader.CheckQueue=function()
{
	if (this.Queue.length>0)
	{
		this.IsLoading=true;
		var sScriptPath=this.Queue[0];
		var oTempArray=new Array();
		for (i=1;i<this.Queue.length;i++) 
		  oTempArray[i-1]=this.Queue[i];
		this.Queue=oTempArray;
		var e;
		if (sScriptPath.lastIndexOf('.css')>0)
		{
			e=document.createElement('LINK');
			e.rel='stylesheet';
			e.type='text/css';
		}
		else
		{
			e=document.createElement("script");
			e.type="text/javascript";
		};
		document.getElementsByTagName("head")[0].appendChild(e);
		var oEvent=function()
		{
			if (this.tagName=='LINK'||!this.readyState||this.readyState=='loaded') 
			Loader.CheckQueue();
		};
		if (e.tagName=='LINK')
		{
			if (sAgent.indexOf("msie") != -1) 
			  e.onload=oEvent;
			else 
			  Loader.CheckQueue();
			e.href=sScriptPath;
			
		}
		else
		{
			e.onload=e.onreadystatechange=oEvent;
			e.src=sScriptPath;
		};
	}
	else
	{
		this.IsLoading=false;
		if (this.OnEmpty) 
		  this.OnEmpty();
	};
}

function abrir_no(id)
{
	//alert(id);
	l = document.getElementById('f_'+id);
	i = document.getElementById('i_'+id);
	if(l.style.display == 'block')
	{
		l.style.display = 'none';
		if(i.src)
		i.src = 'templates/padrao_sc/images/tree_closed.gif';
	}
	else
	{
		l.style.display = 'block';
		if(i.src)
		i.src = 'templates/padrao_sc/images/tree_open.gif';
	}
}

function replace_all( str, from, to ) { 
    var idx = str.indexOf( from ); 
    while ( idx > -1 ) { 
        str = str.replace( from, to ); 
        idx = str.indexOf( from ); 
    } 
    return str; 
} 
