
// Avisa antes de sair de um cadastro aberto
function confirma(tipo,url){
	var del = 'Tem certeza de que deseja excluir este ítem?\n\nPS: Não pode-se reverter o processo!';
	var add = 'Deseja sair deste cadastro atual e iniciar um novo?\n\nPS: Os dados não salvos serão perdidos!';
	if(tipo && window.confirm(eval(tipo))) location.href = url;
}

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(achor){
	achor = achor!=undefined ? achor : '';
	if (location.href.indexOf('#')!=-1){
		location.href = location.href.split("#")[0]+'#'+achor;		
	}else{
		location.href = location.href+'#'+achor;
	}
}

function Refresh_Frame(frame){
	document.getElementById(frame).src = document.getElementById(frame).src;
}

function isInt(x) {
	var y=parseInt(x);
	if (isNaN(y)) return false;
	return x==y && x.toString()==y.toString();
}

// 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;
}

// Valida se variável esta definida ex: isdefined('myvar')
function isdefined(o){
	return (o != undefined && o != null);
};

function enviar_news(ids){
	if(document.getElementById("enviar_news_todos").checked) ids = '';

	var input = prompt('Informe o #ID da Newsletter ou a URL que deve ser enviada','???');
	if(input && (isInt(input) || input.indexOf('http://')==0)){
		if (input > 0 && input.indexOf('http://')==-1){
			url  = 'news='+ input;
			conf = '>> usando a News #ID '+ input;
		}else{
			url  = 'url='+escape(input);
			conf = '>> usando URL "'+ input +'" ';
		}
		para = '>> para '+ (ids=='' ? 'TODOS os clientes' : 'apenas os clientes SELECIONADOS');
		var resposta = window.confirm('Tem certeza de que deseja enviar a News\n\n '+conf+' \n '+para+'?\n\nPS: Não pode-se reverter o processo!');
		if (resposta){document.getElementById("frm_enviar_news").src = 'email_news_envia.php?'+ url +'&ids='+ ids}
	}
};


var bg_old
function MouseOut(src){
	src.style.cursor='default';
	if(bg_old!=''){
		src.style.background=bg_old;
	}else{
		src.style.background='#FFFFFF';		
	}
}

function MouseOver(src){
	src.style.cursor='pointer';
	bg_old = src.style.background;		
	src.style.background='#D9ECFF';
}
// 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);};
		}
	}
}
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['Icert'+janela].location.href= url;
}

function zoom(imagem,path){
	path = path ? path : '/' ;
	// Abre janela
	abre(path+'zoom.php?imagem='+imagem, 'zoom', 150, 150, 0, 0);
	// Grava Analitycs
	if(isdefined('pageTracker')) pageTracker._trackPageview(imagem);
}

function scrollPage(sID){
	var objElement = document.getElementById(sID);
	if (objElement != null){
		objElement.scrollIntoView();
	}
}

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;
	
	if (whichCode == 13)
	return true;
	
	key = String.fromCharCode(whichCode);
	
	if (strCheck.indexOf(key) == -1)
	return false;
	
	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 maximizeWin() {
	if (window.screen) {
		var	width 	= screen.availWidth;
		var height	= screen.availHeight;
		window.moveTo(0, 0);
		window.resizeTo(width, height);
	}
}


function apenas_numeros(esp){
	//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;
	}
}


function Mascara (e,formato, objeto){ 
	campo = eval (objeto);
	if(window.event){
		// IE
		keynum = e.keyCode;
	}else if(e.which){
		// Netscape/Firefox/Opera
		keynum = e.which;
	}
	if(keynum != 8 && keynum != 46){
		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=='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 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 valida_busca(){
	if(form_busca.busca.value.length >= 3){
		return true;
	}else{
		alert('Mínimo de 3 letras na palavra de busca.');
		return false;
	}
}

function ValidaCadastro(){

  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_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 < 8 )
    {alert("O campo 'Fone' 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.PEDIT_QTD;
  if( !isInt(field.value) || parseInt(field.value) < 1)
    {alert("Informe a 'Quantidade' para este orçamento.");
     field.focus();
     field.select();
     return false;}     
     	

  var field=document.form.CLI_MARCADOR;
  if( !field[0].checked && !field[1].checked )
    {alert("Você deseja um Contato Telefônico\npara esclarecer alguma dúvida sobre este produto?\n\nMarque Sim ou Não no campo abaixo.");
     field[0].focus();
     field[0].select();
     return false;}	

  document.form.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 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 OnDocumentLoad(func){
	func = function(){ setTimeout(func,0); }
	if (document.addEventListener) { // Firefox
		 document.addEventListener("DOMContentLoaded",func, false);
	}else{ // IE
		document.onload = func;	
	}
}
function OnWindowClose(func){
	func = function(){ setTimeout(func,0); }
	if (document.addEventListener) { // Firefox
	    document.addEventListener("DOMWindowClose",func, false);
	}else{ // IE
		document.onunload = func;	
	}
}

function MM_MudaImagem(obj,img_m,img_g){
	document.getElementById('img_prin').src = img_m;
	document.getElementById('img_prin_link').href = img_g;
	MM_MarcaImagem(obj.id);
}
function MM_MarcaImagem(obj_id){ 
	for(i=0;i <= 3; i++){
		if(obj = document.getElementById('img_ico'+i)){
			obj.style.border = 'none';
		}
	}
	if(obj = document.getElementById(obj_id)){
		obj.style.border = '2px solid #CCCCCC';
	}	
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	 var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	 if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}		


function F_resize(){
	//direitadisplay:none;
	w = document.width;
	if(w > 780){
		document.getElementById('direita').style.display=''
	}else{
		document.getElementById('direita').style.display='none'		
	}
}

function F_Atalhos(e,tipo,dir){
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if(tipo=='adm'){
		/*F2*/ if(whichCode==113) location.href = ver_site;
	}else{
		/*F2*/  if(whichCode==113) location.href = '/adm/?'+editar_site;
		/*F4*/  if(whichCode==115 && prompt('Link para envio de newsletter. Copie e cole no sistema de envio.\nPressione [ok] para testar o link.',link_print)) location.href = link_print;	
		/*F10*/ if(whichCode==121 && location.href.indexOf('?tipo=orct')==-1) location.href = location.href+'?tipo=orct#investimento';	
		/*F12*/ if(whichCode==123 && confirm('Gerar PDF desta pagina?')) location.href = 'http://savepageaspdf.pdfonline.com/pdfonline/pdfoMaster.asp?cURL='+escape(location.href)+'&username=frankdors&page=0&top=0.5&bottom=0.5&left=0.5&right=0.5';	
	}
}

function verificaHora() {
	stamp = new Date();
	var sours;
	var time;
	hours = stamp.getHours();
	if (hours >= 18 && hours <24) {
		time = " Boa-Noite ";
	}else if (hours >= 12 && hours <18) {
		time = " Boa-Tarde ";
	}else if (hours >= 0 && hours <12) {
		time = " Bom-Dia ";
	}
	return time;
}


function deleteCookie(c_name){
 	var tmp = getCookie(c_name);
	if(tmp) setCookie(c_name,tmp,-9999);
}

function setCookie(c_name,value,expiredays){
	expiredays = (expiredays==null) ? 3650 : expiredays;
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie = c_name +"="+ escape(value) +";expires="+ exdate.toGMTString() +";path=/";
}

function getCookie(szName){
 	var szValue =	  null;
	if(document.cookie){
       	var arr =  document.cookie.split((escape(szName) + '=')); 
       	if(2 <= arr.length){
           	var arr2 = 	   arr[1].split(';');
       		szValue  = 	   unescape(arr2[0]);
       	}
	}
	return szValue;
}

function Wellcome(){
	nome = getCookie('CLI_NOME');
	if(nome) document.write('Olá '+ nome+', ');
	document.write( verificaHora() +'!!' );
}

// Chama ao inicializar o site
jQuery(function($){

	// Resolve problema com links com ancoras causado porque usa-se BaseUrl
	$("a[@href^=#]").each(function(i){	this.href = document.location.href.split("#")[0] + this.hash; })
	
});	