var divblockbarra=0;
var heightdadiv = 217;
var heightdadivtitulo = 61;
var bloqueadorimagem=0;
var divimgbackup={};

function img(elemento,iddiv){
 var html;
 var top;
 
  if(elemento != 'fecha'){
    //document.getElementById("divfloat2").style.top = elemento.screenY;
    document.getElementById("divfloat").style.indexOf = 0;
    document.getElementById("divfloat2").style.indexOf = 0;
    if(document.height){
      document.getElementById("divfloat").style.height = document.height;
    }else{ 
      document.getElementById("divfloat").style.height  = document.body.scrollHeight;
    }
    html = '<div style="margin:10px 10px 10px 10px;">'+
	      '<div style="display:block; text-align:right; margin-bottom:5px">'+
		  '<a onclick="img(\'fecha\')">'+
		      '<img src="/sistema-gestao-erp/images/closelabel.gif">'+
		  '</a>'+
              '</div>'+
	      '<div>'+
		  document.getElementById(iddiv).innerHTML + 
	      '</div>'+
          '</div>';
    document.getElementById("divfloat2").innerHTML = html;
    var rolY = parseInt(document.body.scrollTop); // armazenando os valores de rolagem vertical da página
    var pgY = parseInt(document.body.clientHeight); // armazenando a altura da página
    if(((pgY - $('divfloat2').getHeight())/2) >= 0){
      top = rolY + (pgY - $('divfloat2').getHeight())/2;
    }else{
      top = rolY;
    }
    document.getElementById("divfloat2").style.top = top;
    Effect.toggle('divfloat', 'appear' , {to: 0.45, duration: 0.5});
    Effect.toggle('divfloat2', 'appear', {duration: 0.5});

  }else{
    Effect.toggle('divfloat', 'appear', {duration: 0.5});
    Effect.toggle('divfloat2', 'appear', {duration: 0.5});
  }
} 

function divflutuante(tipo, img, multi){
var html;

  if(document.getElementById(tipo) != null){

    Effect.toggle(tipo, 'slide',{ duration: 0.3 });

  }
  if((img != '')&&(typeof img != 'undefined')){
  
    if(typeof multi == 'undefined'){
      if((typeof divimgbackup[img] == 'undefined') || (divimgbackup[img]['b'] != 3)){
      
	new Effect.Opacity(img, { from: 1, to: 0, duration: 0.2});
	
	if((typeof divimgbackup[img] == 'undefined')||(divimgbackup[img]['b'] == 0)){
	  divimgbackup[img] = {};
	  divimgbackup[img]['b'] = 3;
	  divimgbackup[img]['bkp'] = document.getElementById(img).innerHTML;
	  setTimeout("document.getElementById('"+img+"').innerHTML = document.getElementById('"+tipo+"DIV').innerHTML",300);
	  setTimeout("divimgbackup['"+img+"']['b']=1;",500);
	  
	}else{
	
	  divimgbackup[img]['b'] = 3;
	  html = divimgbackup[img]['bkp'];
	  html = html.replace(/\n/g,"");
	  html = html.replace(/\t/g,"");
	  html = html.replace(/\s\s/g,"");
	  html = html.replace(/'/g,"#");
	  html = html.replace(/"/g,"'");
	  html = html.replace(/#/g,"\"");
	  divimgbackup[img]['bkp'] = html;
	  //alert(eval(html));
	  //setTimeout(eval(html),200);
	  //alert("document.getElementById('"+img+"').innerHTML = \""+html+"\";");
	  //"document.getElementById('"+img+"').innerHTML = \""+divimgbackup+"\";"
	  setTimeout("setaconteudoold(divimgbackup,'"+img+"');",300);
	  setTimeout("divimgbackup['"+img+"']['b']=0;",500);
	}
	setTimeout("new Effect.Opacity('"+img+"', { from: 0, to: 1 })",200);
      }
    }else{
    // #############################
    // Modificação para poder colocar multiplas imagens para o mesmo item
    // #############################
      if((typeof divimgbackup[img] == 'undefined') || (typeof divimgbackup[img][multi] == 'undefined') || (divimgbackup[img][multi]['b'] != 3)){
	
	  new Effect.Opacity(img, { from: 1, to: 0, duration: 0.2});
	  
	  if((typeof divimgbackup[img] == 'undefined')|| (typeof divimgbackup[img][multi] == 'undefined') ||(divimgbackup[img][multi]['b'] == 0)){
	    if(typeof divimgbackup[img] == 'undefined'){
	      divimgbackup[img] = {};
	      divimgbackup[img]['bkp'] = document.getElementById(img).innerHTML;
	    }
	    if(typeof divimgbackup[img][multi] == 'undefined'){
	      divimgbackup[img][multi] = {};
	    }
	    divimgbackup[img][multi]['b'] = 3;
	    setTimeout("document.getElementById('"+img+"').innerHTML = document.getElementById('"+tipo+"DIV').innerHTML",300);
	    setTimeout("divimgbackup['"+img+"']['"+multi+"']['b']=1;",500);
	    
	  }else{
	  
	    divimgbackup[img][multi]['b'] = 3;
	    html = divimgbackup[img]['bkp'];
	    html = html.replace(/\n/g,"");
	    html = html.replace(/\t/g,"");
	    html = html.replace(/\s\s/g,"");
	    html = html.replace(/'/g,"#");
	    html = html.replace(/"/g,"'");
	    html = html.replace(/#/g,"\"");
	    divimgbackup[img]['bkp'] = html;
	    setTimeout("setaconteudoold(divimgbackup,'"+img+"');",300);
	    setTimeout("divimgbackup['"+img+"']['"+multi+"']['b']=0;",500);
	  }
	  setTimeout("new Effect.Opacity('"+img+"', { from: 0, to: 1 })",200);
	}
    }
  }
}

function SetaNovaImagem(tipo, img){
  var html;

  if(document.getElementById(tipo) != null){
    Effect.toggle(tipo, 'slide',{ duration: 0.3 });
  }

  if((img != '')&&(typeof img != 'undefined')){
      new Effect.Opacity(img, { from: 1, to: 0, duration: 0.2});

      setTimeout("document.getElementById('"+img+"').innerHTML = document.getElementById('"+tipo+"DIV').innerHTML",300);

  }
  setTimeout("new Effect.Opacity('"+img+"', { from: 0, to: 1 })",200);
}

function setaconteudoold(divimgbackup, img){
  document.getElementById(img).innerHTML = divimgbackup[img]['bkp'];
  
}

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

function openmenu(id){
  var url;
  var req = getXmlHttpRequest();
  var req2 = getXmlHttpRequest();

  Effect.SlideUp('barraazul',{duration: 0.5 });
  
  if(document.getElementById(id).innerHTML == ''){

      url = "/sistema-gestao-erp/tt/"+id+".tt";

      req.open("GET", url, true);
      req.onreadystatechange = function(){
	      if (req.readyState==4){
		      Effect.SlideDown('content',{duration: 0.5 });
		      document.getElementById(id).innerHTML 	   = req.responseText;
//		      document.getElementById("content").innerHTML = document.getElementById("menuerp").innerHTML;
//		      document.getElementById("content").innerHTML += req.responseText;
		      Element.update( document.getElementById("content"), document.getElementById("menuerp").innerHTML + req.responseText );
		      
	      }
      }
      req.send(null);
      url = "/sistema-gestao-erp/tt/"+id+"titulo.tt";

      req2.open("GET", url, true);
      req2.onreadystatechange = function(){
	      if (req2.readyState==4){
		      document.getElementById(id+"titulo").innerHTML	   = req2.responseText;
		      document.getElementById("barraazultitulo").innerHTML = req2.responseText;
		      Effect.SlideDown('barraazultitulo',{duration: 0.5 });
	      }
      }
      req2.send(null);
      
  }else{
    Effect.SlideDown('barraazultitulo',{duration: 0.5 });
    Effect.SlideDown('content',{duration: 0.5 });
    document.getElementById("barraazultitulo").innerHTML = document.getElementById(id+"titulo").innerHTML;
    document.getElementById("content").innerHTML = document.getElementById("menuerp").innerHTML;
    document.getElementById("content").innerHTML += document.getElementById(id).innerHTML;
  }

  document.title = "Sistêmica - Sistema de Gestão ERP "+id;
  divblockbarra = 1;
  bloqueadorimagem = 0;
}

/*function financeiro(){

  	Effect.SlideUp('barraazul',{duration: 0.5 });
	document.getElementById("barraazultitulo").innerHTML = document.getElementById("financeirotitulo").innerHTML;
  	Effect.SlideDown('barraazultitulo',{duration: 0.5 });
  	Effect.SlideDown('content',{duration: 0.5 });
	document.getElementById("content").innerHTML = document.getElementById("financeiro").innerHTML;
	document.title = "Sistêmica - ERP Financeiro";
	divblockbarra = 1;
}*/

function barraazul(){
  if (divblockbarra == 1){
    divblockbarra = 3;
    setTimeout("divblockbarra=2",800);
    document.getElementById("barraazultitulo").style.height = heightdadivtitulo;
    document.getElementById("barraazul").style.height = heightdadiv;
    Effect.SlideUp('barraazultitulo',{duration: 0.5 });
    Effect.SlideDown('barraazul',{duration: 0.5 });
    setTimeout("document.getElementById('barraazul').style.display = 'block';document.getElementById('barraazultitulo').style.height = heightdadivtitulo;document.getElementById('barraazul').style.height = heightdadiv;",600);
  }
}

function barraazulup(){
	if (divblockbarra == 2){
		divblockbarra = 3;
		setTimeout("divblockbarra=1",800);
		document.getElementById("barraazultitulo").style.height = heightdadivtitulo;
		document.getElementById("barraazul").style.height = heightdadiv;
		Effect.SlideUp('barraazul',{duration: 0.5 });
		Effect.SlideDown('barraazultitulo',{duration: 0.5 });
		setTimeout("document.getElementById('barraazultitulo').style.display = 'block';document.getElementById('barraazultitulo').style.height = heightdadivtitulo;document.getElementById('barraazul').style.height = heightdadiv;",600);
	}
	/*if(document.getElementById("barraazultitulo").style.display == 'block'){
		Effect.SlideUp('barraazul',{duration: 0.5 });
		Effect.SlideDown('barraazultitulo',{duration: 0.5 });
	}*/
}

function correcaodobug(valor){
  if (divblockbarra != 0){
    document.getElementById("barraazultitulo").style.height = heightdadivtitulo;
    document.getElementById("barraazul").style.height = heightdadiv;
    document.getElementById("barraazultitulo").style.display = 'block';
    document.getElementById("barraazul").style.display ='none';
    divblockbarra = valor;
  }
}

function inicial(){
var req = getXmlHttpRequest();
var url;

  if(document.getElementById("inicial").innerHTML == ""){

      url = "/sistema-gestao-erp/tt/home.tt";
      req.open("GET", url, true);
      req.onreadystatechange = function(){
	if (req.readyState==4){
	  document.getElementById("inicial").innerHTML = req.responseText;
	  document.getElementById("content").innerHTML = req.responseText;
	}
      }
      req.send(null);
	
    }else{
      document.getElementById("content").innerHTML = document.getElementById("inicial").innerHTML;
    }
   document.getElementById("imgcontent").innerHTML = '<img src="/sistema-gestao-erp/images/meio_03.png">';
   document.title = "Sistêmica - Sistema de Gestão ERP";
   document.getElementById("barraazultitulo").style.height = heightdadivtitulo;
   document.getElementById("barraazultitulo").style.display = 'none';
   document.getElementById("barraazul").style.display = 'block';
   document.getElementById("barraazul").style.height = heightdadiv;
   divblockbarra = 0;
   setTimeout("divblockbarra = 0;",500);
}

function validaform(){
  var valida='';
  var er = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
  
  if(document.EnviaEmail.from.value == ''){
    valida +='e-mail está nulo\n';
  }else{
    if(!er.test(document.EnviaEmail.from.value)){
      valida +='e-mail não é valido\n';
    }
  }
  if(document.EnviaEmail.demo.value != 1){
    if(document.EnviaEmail.subject.value == ''){
      valida +='Assunto está nulo\n';
    }

    if(document.EnviaEmail.msg.value == ''){
      valida +='Mensagem está nula\n';
    }
  }
  if(valida!=''){
    alert(valida);
  }else{
    document.EnviaEmail.submit();
  }
}




/*==================================================================
#  Validação do formulário -> ORÇAMENTO <-  												#
#   por Palmer Oliveira em 2009-05-04																					#
===================================================================*/

/*
:: Função para Validar CNJP, após ele passar pelo Mask;
:: Incluído em 2009-05-29
*/

function checkCNPJ (cValue) {
	cValue = cValue.replace(/\D/g, '');
	var i,c,dv,cont,d1;
	c = cValue.substr(0,12);
	dv = cValue.substr(12,2);

	cont = 0;
	d1 = 0;
	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+(i % 8));
	}

    if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);

	if (d1 > 9) d1 = 0;

	if (dv.charAt(0) != d1)
	{
		 return false;
	}

	d1 *= 2;
	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}


	d1 = 11 - (d1 % 11);


	if (d1 > 9) d1 = 0;

	if (dv.charAt(1) != d1)  return false;

		return true;
}


//
// Especifica mascara para o campo. Deve ser usada no evento onkeyup.
// NOVA FUNÇÃO DE MÁSCARA PARA O CAMPO: INCORPORADA PARA CARACTERES DO TIPO HEXADECIMAL
//
// Exemplo:
// Mask( this, "(99) 9999-9999", event ); /* Mascara para número de telefone */
// Mask( this, "AAA-9999", event ); /* Mascara para placa de carro */
// Mask( this, "#####-#####-#####-#####-#####", event ); /* Mascara para número serial */
// Mask( this, "%%.%%.%%.%%.%%.%%", event ); /* Mascara para tipo de dado addr */
//
// Onde:
// A = Somente letras [a-zA-Z]
// 9 = Somente números [0-9]
// # = Caracteres alfanumericos em geral
// % = Caracteres hexadecimais \w
//
// Função alterada em 14/04/2009 por Felipe Muller:
// Criada a variavel "ValueFormated", agora a função primeiro formata os valores,
// logo após ela remonta os valores apenas com os valores conforme a Mask
//
function Mask(Field, Mask, e) {

			// Declaração do valor do input sem caracteres especiais, caso haja caracteres especiais, ele vai apagar
			var Value = Field.value.replace( /\W/gi, "" ),i;

			// For que percorre cara caractere do valor do input, e formata seguindo a mascara passada pelo usuario
			for (i = 0; i < Value.length; i ++) {
				 if (!/[#A9%]/.test(Mask.charAt(i))) {
				  Value = Value.splice(i, 1, Mask.charAt(i) + Value.charAt(i));
				 }
			}

			var ValueFormated = ''; //declaração da do Valor formatado

			//For que percorre novamente o valor, mas dessa vez já formatado. Removendo o que não pertence à mascara
			for (i = 0; i < Value.length; i ++) {
				//Faz uma verificação da Expressão regular, para ver se o valor digitado é compativel com a mascara
			  if (
					 (Mask.charAt(i) == "A" && /[a-z]/i.test(Value.charAt(i))) ||
				   (Mask.charAt(i) == "9" && /[0-9]/.test(Value.charAt(i))) ||
				   (Mask.charAt(i) == "%" && /[0-9a-fA-F]/.test(Value.charAt(i))) ||
				   (Mask.charAt(i) == "#" && /\w/.test(Value.charAt(i)))
					) {

					ValueFormated += Value.charAt(i);

			 //Verifica se o valor da mascara é igual ao valor( Usado quando o usuário digita um "-" por exemplo)
			 }else if (Mask.charAt(i) == Value.charAt(i)){
			   ValueFormated += Value.charAt(i);
			 }
			}

			if (ValueFormated.replace( /\W/gi, "" ) == ''){
			  ValueFormated = '';
			}

			Field.value = ValueFormated;
}

String.prototype.splice = function (i, offset, str) {
	if (i < 0)
	i= this.length + i;

	return this.substr(0, i) + (str || "") + this.substr(i + offset, this.length)
}


//Função para marcar as ckeckbox
function marcar(el){
				if($(el).previous().checked){
				  $(el).previous().checked = false;
			   }else{
					$(el).previous().checked = true;
			   }
	}

//Função para habilitar o campo "Qual" dos campos Sistema e Banco. Se o select sistema for "sim" habilita, se o select "banco" for "outro" habilita
// v = this.value :: s = passo o nome do campo a ser habilitado. 


function habilita_sistema(oinput) {
	if($('sistema').value == 1) {
		$(oinput).disabled = false;
	}else{
		$(oinput).disabled = true;
	}	
}

function habilita_banco(oinput) {
	if($('banco').value == 'Outro') {
		$(oinput).disabled = false;
	}else{
		$(oinput).disabled = true;
	}	
}

	
function validaform_orc(){

			  var valida='';
              var nro = 0; //Nro de Inconsistencias encontradas


			  if($('razao').value==''){
				nro++;
				valida+=nro+'- Preencha a Razão\n';
				}
			  /*
			  if($('cnpj').value == '') {
					nro++;
					valida+=nro+'- Preencha o CNJP da empresa.\n';
			 }else if ( !(checkCNPJ($('cnpj').value)) ) {
					nro++;
					valida+=nro+'- CNJP Inválido! Favor preencher corretamente.\n';
				}*/
			  
			  if($('contato').value==''){
				nro++;
				valida+=nro+'- Preencha o Contato\n';
				}


			  var er = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;

			  if($('fone').value=='' && $('email').value==''){
					nro++;
					valida+=nro+'- Preencha o telefone ou o e-mail\n';
				}else if($('fone').value!= '' && $('email').value!=''){
						if ($('fone').value.length<14){
							nro++;
							valida += nro+ '- O Número do telefone está incompleto\n';
						}
						if(!er.test($('email').value)){
						  nro++;
						  valida += nro+ '- '+$('email').value+' não é um e-mail válido\n';
						}
				  }else if ($('fone').value!=''){
						        if ($('fone').value.length<14){
												nro++;
												valida += nro+ '- O Número do telefone está incompleto\n';
								}
				  }else if ($('email').value!=''){
						  		  if(!er.test($('email').value)){
								  nro++;
								  valida += nro+ '- '+$('email').value+' não é um e-mail válido\n';
								    }
         		}

            var check = new Array();
				check = $('checks').getElementsByClassName('checkbox');
				var cont = 0;
				for(var x=0; x < check.length; x++){
					if(check[x].checked==true){
						 cont++;
					}
				}

				if(cont == 0){  
					nro++;
					valida +=nro+'- Escolha pelo menos um módulo\n';
				}

			  if(valida!='') {
			        if(nro > 1){
						    alert('Foram encontradas '+nro+' inconsistências, segue:\n'+valida);
						}else{
      					 alert('Foi encontrada '+nro+' inconsistência, segue:\n'+valida);
						}
             }else{

					$('form1').submit();
				  }

   }

/*==================================================================
#  Validação do formulário -> ENVIE PARA UM AMIGO <-  												#
#   por Palmer Oliveira em 2009-05-14																				#
===================================================================*/

function validaform_indique(){

			  
			  var valida='';
              var nro = 0; //Nro de Inconsistencias encontradas


			  if($('nome').value==''){
				nro++;
				valida+=nro+'- Informe seu nome\n';
				}
			  if($('nome_amigo').value==''){
				nro++;
				valida+=nro+'- Informe o nome de seu amigo\n';
				}

			  var er = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;

			  if($('email').value != ''){
					if(!er.test($('email').value)){
						  nro++;
						  valida += nro+ '- '+$('email').value+' não é um e-mail válido\n';
					}
			}	
			  
			  
			  if($('email_amigo').value==''){
					nro++;
					valida+=nro+'- Informe o e-mail de seu amigo\n';
				}else if(!er.test($('email_amigo').value)){
						  nro++;
						  valida += nro+ '- '+$('email_amigo').value+' não é um e-mail válido\n';
				}
				  

			  if(valida!='') {
			        if(nro > 1){
						    alert('Foram encontradas '+nro+' inconsistências, segue:\n'+valida);
						}else{
      					 alert('Foi encontrada '+nro+' inconsistência, segue:\n'+valida);
						}
             }else{
					
					$('form1').submit();
				  }

   }




