// Valida se variável é valida ex: isset('myvar')
function isset(variable_name){
	try{
		if (typeof(eval(variable_name)) != 'undefined')
		if (eval(variable_name) != null)
		return true;
	}catch(e){ }
	return false;
}



<!-- // Em caso de erro em script não ocorre nada
function stopError() {
    //alert ('Ops...\nTalvez estamos com problemas em nossos códigos JavaScripts.\nTente novamente, mas caso o problema persistir contate o Webmaster.\nAgradecemos sua compreenção.');
    return true;
    }
//window.onerror = stopError;
 // -->

name = navigator.appName;
ver = parseInt(navigator.appVersion);
if (name == "Netscape" && ver >= 3) { Navigator = 1; }
  else if (name == "Microsoft Internet Explorer" && ver >= 4) { Navigator = 2; }
	else { Navigator = 0 }

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

function VerImagem(campo,img) { 
    document.getElementById(img).src = campo.value;
}

function Go(url){
	location.href = url;
}

function GoTop(){
	if (location.href.indexOf('#')!=-1){
		location.href = location.href;		
	}else{
		location.href = location.href+'#';
	}
}


function valida_busca(){
	if(form_busca.busca.value.length >= 2){
		return true;
	}else{
		alert('Mínimo de 2 letras na palavra de busca.');
		return false;
	}
}

function Refresh_Frame(frame){
	document.getElementById(frame).src = document.getElementById(frame).src;
}

var bg_old
function MouseOut(src){
	src.style.cursor='default';
	if(bg_old!=''){
		if(src.style.background) src.style.background=bg_old;
	}else{
		if(src.style.background) src.style.background='#FFFFFF';		
	}
}

function MouseOver(src){
	src.style.cursor='pointer';
	bg_old = src.style.background;		
	src.style.background='#FFF9F9';
}
// Adiciona eventos
function addEvent(obj, evType, fn){
    if (obj.addEventListener){
       obj.addEventListener(evType, fn, false);
       return true;
    }else if (obj.attachEvent){
       var r = obj.attachEvent("on"+evType, fn);
       return r;
    }else{
		 return false;
    }
}


function randomNumber(limit){
  return Math.floor(Math.random()*limit)+1;
}


//Adiciona a cor para fazer mudar de cor ao entrar / sair de um campo de formulário
function findimg(){
	var objs = ['input', 'textarea','select'];
	
	for(ii in objs){
		obj=document.getElementsByTagName(objs[ii]);
		for(i in obj){
			obj[i].onfocus=function(){this.select();MouseOver(this);};
			obj[i].onblur=function(){MouseOut(this);};
		}
	}
	//obj=document.getElementsByName('bt_img');
	//for(i in obj){
		//obj[i].style.cursor='pointer';
		//obj[i].style.filter='Alpha(Opacity=50) Gray';
		//obj[i].onmouseover=function(){this.style.filter='none';};
		//obj[i].onmouseout=function(){this.style.filter='Alpha(Opacity=50) Gray';};
	//}
}
addEvent(window, 'load', findimg);




function showcollapse(what){
	a=document.getElementById(what);
	if (a.style.display=='' || !a.style.display){
		a.style.display='none';
	} else {
		a.style.display='';
	}
}


function abre(url, janela, width, height, Scroll, stat, menu){
	var left   = (screen.width/2) - width/2;
	var top    = ((screen.height/2) - height/2)-20;
	janela = window.open(url,'Icert'+janela, 'top='+top+',left='+left+',width='+width+',height='+height+',toolbar=no,location=no,resizable=yes,fullscreen=0,status='+stat+',menubar='+menu+',scrollbars='+Scroll+'');
}


function abreFrame(url, janela){
	parent['CristhalIcert'+janela].location.href= url;
}

function framePrint(whichFrame){
	parent[whichFrame].focus();
	parent[whichFrame].print();
}

function Print(targ) {
	if (!document.all.factory){
		targ.insertAdjacentHTML("afterEnd","<object id=factory style='display:none' classid='clsid:1663ed61-23eb-11d2-b92f-008048fdd814' viewastext codebase='ScriptX.cab#Version=5,60,0,375'></object>");
		Print(targ);
	}else{
		factory = document.all.factory;
		// Record settings
		var header 	 	= factory.printing.header;
		var footer       = factory.printing.footer;
		var portrait     = factory.printing.portrait;
		var leftMargin   = factory.printing.leftMargin;
		var topMargin    = factory.printing.topMargin;
		var rightMargin  = factory.printing.rightMargin;
		var bottomMargin = factory.printing.bottomMargin;
		
		// Set settings
		factory.printing.header       = "";
		factory.printing.footer       = "";
		factory.printing.portrait     = true;
		factory.printing.leftMargin   = 5;
		factory.printing.topMargin    = 5;
		factory.printing.rightMargin  = 5;
		factory.printing.bottomMargin = 5;

		targ.style.display='none';
		// Imprime
		this.focus();
		this.print();
		//factory.printing.Print(false); // no prompt

		targ.style.display='';
		
		// Restore settings
		factory.printing.header       = header;
		factory.printing.footer       = footer;
		factory.printing.portrait     = portrait;
		factory.printing.leftMargin   = leftMargin;
		factory.printing.topMargin    = topMargin;
		factory.printing.rightMargin  = rightMargin;
		factory.printing.bottomMargin = bottomMargin;
	}
}

function PageSetup() {
	factory.printing.PageSetup()
}
function Preview() {
	this.focus();
	document.all.factory.printing.Preview();
}


function zoom(imagem,path){
	path = path ? path : '' ;
	abre(path+'zoom.php?imagem='+imagem, 'zoom', 150, 150, 0, 0)
}

function validaDinheiro(fld,e){
	var milSep = ".";
	var decSep = ",";
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	len = fld.value.length;
	
	if (whichCode==13 || whichCode==8 || whichCode==0) return true;
	
	key = String.fromCharCode(whichCode);

	if (strCheck.indexOf(key) == -1)	return false;

	for (i = 0; i < len; i++)
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep))
	break;
	
	aux = '';
	
	for (; i < len; i++)
	if (strCheck.indexOf(fld.value.charAt(i))!=-1)
	aux += fld.value.charAt(i);
	
	aux += key;
	len = aux.length;
	
	if (len == 0)
	fld.value = '';
	
	if (len == 1)
	fld.value = '0'+ decSep + '0' + aux;
	
	if (len == 2)
	fld.value = '0'+ decSep + aux;
	
	if (len > 2)
	{
	aux2 = '';
	
	for (j = 0, i = len - 3; i >= 0; i--)
	{
	if (j == 3)
	{
	aux2 += milSep;
	j = 0;
	}
	aux2 += aux.charAt(i);
	j++;
	}
	
	fld.value = '';
	len2 = aux2.length;
	
	for (i = len2 - 1; i >= 0; i--)
	fld.value += aux2.charAt(i);
	fld.value += decSep + aux.substr(len - 2, len);
	}
	
	return false;
}


function maximizeWin() {
	if (window.screen) {
		var	width 	= screen.availWidth;
		var height	= screen.availHeight;
		window.moveTo(0, 0);
		window.resizeTo(width, height);
	}
}

var refAtual = 0;
function BuscaDescricao(obj,iframe,target){
	ref = obj.value
	if(ref != refAtual && ref != ''){
	    eval(iframe).location.href='response.asp?Tipo=Retorna_Descrição&Colecao='+target+'&ID='+ ref;
		refAtual = ref;
	}
}

function apenas_numeros(e){
	var whichCode = (window.Event) ? e.which : e.keyCode;
	var strCheck = '0123456789';
	var key = String.fromCharCode(whichCode);
	if (strCheck.indexOf(key) == -1)	return false;
}
//alert(event.keyCode);
/*	if(window.event){
		if (event.keyCode == esp){event.returnValue = true} else
		if (event.keyCode < 47 || event.keyCode > 57) event.returnValue = false;
		if (event.keyCode == 47) event.returnValue = false;
	}else{
		//var whichCode = (window.Event) ? e.which : e.keyCode;
		//if (whichCode < 47 || whichCode > 57 || whichCode == 47) return false;

	}	
*/


function calc_total(qtd,vunit,vtotal){
   valor = eval(qtd).value * eval(vunit).value.replace(',','.'); 
   eval(vtotal).value = printf(valor,2,',')
}


function MudaFoco(e){
		var keynum = (window.Event) ? e.which : e.keyCode;
      if (keynum == 13){window.event.keyCode = 9;} 
}

function Mascara (e,formato, objeto){ 
	var campo = eval (objeto);

	if (formato=='Data'){ //'10/11/2006'
		separador1 = '/'; 
		if (campo.value.length == 2){ campo.value = campo.value + separador1; } 
		if (campo.value.length == 5){ campo.value = campo.value + separador1; } 
	}else 
	if (formato=='CEP'){ //'95.900-000'
		separador1 = '.'; 
		separador2 = '-'; 
		if (campo.value.length == 2){ campo.value = campo.value + separador1; } 
		if (campo.value.length == 6){ campo.value = campo.value + separador2; } 
	}
	if (formato=='PLACA'){ //'AAA-9999'
		separador1 = '-'; 
		if (campo.value.length == 3){ campo.value = campo.value + separador1; } 
	} 	
	if (formato=='FONE'){ //'(51) 3748-7571'
		separador1 = '('; 
		separador2 = ') '; 
		separador3 = '-';
		if (campo.value.length == 1){ campo.value = separador1 + campo.value} 
		if (campo.value.length == 3){ campo.value = campo.value + separador2; } 
		if (campo.value.length == 9){ campo.value = campo.value + separador3; } 
	} 
	if (formato=='CNPJ'){ //91.474.478/0001-09'
		separador1 = '.'; 
		separador2 = '/'; 
		separador3 = '-'; 
		if (campo.value.length == 2){ campo.value = campo.value + separador1; } 
		if (campo.value.length == 6){ campo.value = campo.value + separador1; } 
		if (campo.value.length == 10){ campo.value = campo.value + separador2; } 
		if (campo.value.length == 15){ campo.value = campo.value + separador3; } 
	}
	
}

function printf(valor,casas,pont) {
	var toStr=valor.toString()+'00';
	if(toStr.indexOf(".") == -1) {
		return valor+pont+'00';
	}else {
	    var div=toStr.split(".");
	    var fcent=div[1].substring(0,casas);
	    return div[0]+pont+fcent;
	}
}

function FormataReais(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) return true;
	key = String.fromCharCode(whichCode);  // Valor para o código da Chave
	if (strCheck.indexOf(key) == -1) return false;  // Chave inválida
	len = fld.value.length;
	for(i = 0; i < len; i++)
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
	aux2 = '';
	for (j = 0, i = len - 3; i >= 0; i--) {
	if (j == 3) {
	aux2 += milSep;
	j = 0;
	}
	aux2 += aux.charAt(i);
	j++;
	}
	fld.value = '';
	len2 = aux2.length;
	for (i = len2 - 1; i >= 0; i--)
	fld.value += aux2.charAt(i);
	fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}


function validaemail(email){
	if (email.length == 0){	return true}
	if (window.RegExp) {
		var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
		var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$";
		var reg1 = new RegExp(reg1str);
		var reg2 = new RegExp(reg2str);
		if (!reg1.test(email) && reg2.test(email)){	return true  }
											  else{ return false }
	} else {
		if(str.indexOf("@") >= 0) return true;
		return false;
	} 		 
}

function ValidaCadastro(){

	var field=document.form.CLI_NOME;
  var dados=field.value.length;
  if( dados < 3 )
    {alert("O campo 'Nome' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}

  var field=document.form.CLI_EMAIL;
  var dados=field.value.length;
  if (!validaemail(field.value) || dados < 5)
	  {alert('Preencha com um e-mail válido.');
      field.focus();
      field.select();
      return false;} 

  var field=document.form.CLI_FONE;
  var dados=field.value.length;
  if( dados < 10 )
    {alert("O campo 'Fone' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}

  document.form.submit()		 
}

function ValidaProposta(){
	frm = document.form;

  var field=frm.CLI_NOME;
  var dados=field.value.length;
  if( dados < 3 )
    {alert("O campo 'Nome' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}

  var field=frm.CLI_EMAIL;
  var dados=field.value.length;
  if (!validaemail(field.value) || dados < 3)
	  {alert('Preencha com um e-mail válido.');
      field.focus();
      field.select();
      return false;} 

  var field=frm.CLI_FONE;
  var dados=field.value.length;
  if( dados < 10 )
    {alert("O campo 'Fone' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}

 /* var field=frm.VEIC_NOME;
  var dados=field.value.length;
  if( dados < 3 )
    {alert("O campo 'Veículo/Modelo' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}

  var field=frm.VEIC_ANO;
  var dados=field.value.length;
  if( dados < 4 )
    {alert("O campo 'Ano' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}
	  
  var field=frm.VEIC_COR;
  var dados=field.value.length;
  if( dados < 3 )
    {alert("O campo 'Cor' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}	  

  var field=frm.VEIC_COMB;
  var dados=field.value.length;
  if( dados < 3 )
    {alert("O campo 'Combustível' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}	 

  var field=frm.VEIC_PLACA;
  var dados=field.value.length;
  if( dados < 7 )
    {alert("O campo 'Placa' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}	

  var field=frm.VEIC_KM;
  var dados=field.value.length;
  if( dados < 4 )
    {alert("O campo 'KM' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}	

  var field=frm.VEIC_OPCIONAIS;
  var dados=field.value.length;
  if( dados < 4 )
    {alert("O campo 'Opcionais' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}

  var field=frm.VEIC_PORTAS;
  var dados=field.value.length;
  if( dados < 1 )
    {alert("O campo 'Portas' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}*/

  var field=frm.CLI_OBS;
  var dados=field.value.length;
  if( dados < 5 )
    {alert("O campo 'Faça sua Proposta' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}

  frm.ENVIAR.value='T';
  frm.submit();
}

function ValidarCadastroCompleto(){

  var field=document.form.CLI_EMPRESA;
  var dados=field.value.length;
  if( dados < 3 )
    {alert("O campo 'Empresa' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}

	var field=document.form.CLI_NOME;
  var dados=field.value.length;
  if( dados < 3 )
    {alert("O campo 'Contato' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}

  var field=document.form.CLI_CNPJ;
  var dados=field.value.length;
  if( dados < 10 )
    {alert("O campo 'CNPJ' deve ser preenchido corretamente!!");
     field.focus();
     field.select();
     return false;}

  var field=document.form.CLI_IE;
  var dados=field.value.length;
  if( dados < 3 )
    {alert("O campo 'Inscrição Estadual' deve ser preenchido corretamente!!");
     field.focus();
     field.select();
     return false;}

  var field=document.form.CLI_EMAIL;
  var dados=field.value.length;
  if (!validaemail(field.value) || dados < 5)
	  {alert('Preencha com um e-mail válido.');
      field.focus();
      field.select();
      return false;} 

  var field=document.form.CLI_FONE;
  var dados=field.value.length;
  if( dados < 10 )
    {alert("O campo 'Fone' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}

  var field=document.form.CLI_ENDERECO;
  var dados=field.value.length;
  if( dados < 3 )
    {alert("O campo 'Endereço' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}		

  var field=document.form.CLI_CIDADE;
  var dados=field.value.length;
  if( dados < 3 )
    {alert("O campo 'Cidade' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}	

  var field=document.form.CLI_UF;
  var dados=field.value.length;
  if( dados < 2 )
    {alert("O campo 'UF' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}	

  var field=document.form.CLI_CEP;
  var dados=field.value.length;
  if( dados < 8 )
    {alert("O campo 'CEP' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}	

  document.form.submit()		 
}


function ValidarRecado(){
  var field=document.form.REC_DE;
  var dados=field.value.length;
  if( dados < 3 )
    {alert("O campo 'De:' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}

  var field=document.form.REC_EMAIL;
  var dados=field.value.length;
  if (!validaemail(field.value) || dados < 5)
	  {alert('Preencha com um e-mail válido.');
      field.focus();
      field.select();
      return false;} 

  var field=document.form.REC_PARA;
  var dados=field.value.length;
  if( dados < 3 )
    {alert("O campo 'Para:' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}

  var field=document.form.REC_ASSUNTO;
  var dados=field.value.length;
  if( dados < 3 )
    {alert("O campo 'Assunto:' deve ser preenchido!!");
     field.focus();
     field.select();
     return false;}		
  document.form.submit()		 
}

function StatusBar(txt){
	window.defaultStatus = txt;
}
window.focus(); 

window.defaultStatus = document.title + "          by Icert"
var sorry =  document.title + '\n\nby  Icert Informática.\n\n All rights reserved.';

function sel()
{
	return(false);
}

var isNS = (document.layers) ? true : false;
var isNS6 = (document.getElementById && !document.all) ? true : false;
var isIE = (document.all) ? true : false;
var isIE5 = (isIE) ? ((navigator.userAgent.indexOf('MSIE 5') > 0) ? true : false) : false;

function tecla(e){
	key = event.keyCode
	//alert(key);
	if(key == 27 ){window.close();} //esc
	if(key == 107){form.btn_new.onclick()}// +
	if(key == 106){form.submit()}// *
	if(key == 13){window.event.keyCode = 9;} //enter	
/*
	if(isIE && (event.keyCode == 93 || event.keyCode == 17 || event.keyCode == 18  || event.keyCode == 22)){
		alert(sorry);
		return(false);
	}else if((isNS || isNS6) && !e.which)
		return(false);
*/
}
function click(e){
	if(isIE && (event.button == 2 || event.button == 3)){
		alert(sorry);
	return(false);
	}else	if((isNS || isNS6) && (e.which == 2 || e.which == 3)){
		alert(sorry);
	return(false);
	}
}

//if(isNS || isNS6)
//	document.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP | Event.MOUSEDOWN | //Event.KEYDOWN | Event.RESIZE);

function teclaflash(tecla){
	if(tecla == 93 || tecla == 17 || tecla == 18 || tecla == 22 || tecla == 9){
		alert(sorry);
	}
}


function OnDocumentLoad(func){
	func = function(){ setTimeout(func,0); }
	if (document.addEventListener) { // Firefox
		 document.addEventListener("DOMContentLoaded",func, false);
	}else{ // IE
		document.onload = func;	
	}
}
//document.onkeydown=MudaFoco;
//document.onkeydown=tecla;
//document.oncontextmenu=click;
//document.onmousedown=click;
//document.onselectstart=sel;
//document.ondragstart=sel;


$(function(){


	// Coloca atalho ao pressionar tecla
	// Verifica se esta no admin ou no site
	if(!isset('editar_site')){
		// Mostra site
		$.hotkeys.add('F2' ,function(){ Go(ver_site) });
	}else{
		$.hotkeys.add('F2' ,function(){ Go(base_url+'adm/?'+editar_site); });
		// Link print
		$.hotkeys.add('Ctrl+F4' ,function(){ if( prompt('Link para envio de newsletter. Copie e cole no sistema de envio.\nPressione [ok] para testar o link.',base_url +'index.php?modo=print&'+ link_print))
											Go(base_url +'index.php?modo=print&'+link_print); });
		// Limpa Cache
		$.hotkeys.add('Ctrl+F8' ,function(){ if( window.confirm('Tem certeza que deseja executar este procedimento?\n\n'+sorry)) 
											Go(base_url+'index.php?m=home&_cache=clear'); });
		// Acessa Web Mail
		$.hotkeys.add('Ctrl+F12',function(){ if( window.confirm('Deseja acessar o WebMail?\n\n'+sorry))
											Go(base_url+'email'); });
		
		$('.tip').tooltip({
			track: true, 
			delay: 3, 
			showURL: false, 
			showBody: " - ", 
			//opacity: 1.0//, 
			left: -20 
		});
		
		$('.tipimg').tooltip({
			track: true, 
			delay: 100,
			showURL: false,	
			bodyHandler: function() {
				return $("<img/>").attr("src", this.lowsrc);
			}
		});
	}

});
