var hh = 01;
var mm = 00;
var ss = 01;

function sair_sistema(){
	alert("Sua sesso expirou!\nVolte a tela de login e entre novamente no sistema.")
	window.location.href = "login.asp";
}

function tempo_sessao(){
	sessao = setTimeout("sair_sistema()", 3540000);
}

function relogio(){
	if (ss <= 00){
		ss = 60;
		mm = mm - 1;
		if (mm < 00){
			mm = 59;
			hh = hh - 1;
			if (hh >= 24){
				hh = 00;
			}
		}
	}
	ss = ss - 1;
	if (hh <= 9){
		xhh = "0" + hh;
	} else {
		xhh = hh;
	}
	if (mm <= 9){
		xmm = "0" + mm;
	} else {
		xmm = mm;
	}
	if (ss <= 9){
		xss = "0" + ss;
	} else {
		xss = ss;
	}
	document.all("span_relogio").innerHTML = xhh + ":" + xmm + ":" + xss;
	lrelogio = setTimeout("relogio()", 1000);
}


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 MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layeRw.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layeRw.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayeRw.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function limpa_campo(campo,form) {
	for (var i = document.forms(form).item(campo).options.length ; i > 0 ; i-- ) {
		document.forms(form).item(campo).options[i-1] = null;
	}
	document.forms(form).item(campo).options[0]=new Option('---------------------------------','');
}

function preenche_campo(campo,form,valor,texto,selecionado) {
	var i = document.forms(form).item(campo).options.length;
	document.forms(form).item(campo).options[i]=new Option(texto,valor);
	if (selecionado) {
		document.forms(form).item(campo).options[i].selected = true;
	}
}

function limiteSemana(valorCampo, DiaHoje, DiaLimite)
{
	var arrVal = valorCampo.split("-");
	
	if (DiaLimite >= arrVal[0])
		return true;
	else
	{
		alert('Selecione uma semana anterior a esta!');
		return false;
	}
	
	//if ((arrVal[0] >= ))
	
}


function SemanasdoMes(valor,form,campoauxiliar,valormarcado,dialimite)
{	
	var DiasdaSemana = 7; // "constant" para o numero de dias na semana
	// valor é a data que vem do selectbox principal(select cotendo a data no formato americano)

	var mess = valor.substr(5,2)
	var mes = mess!="10"? parseInt(mess.replace("0",""))-1 : parseInt(mess)-1;
	var ano =  parseInt(valor.substr(0,4));
	// cria um objeto de data
	var data = new Date(ano,mes,1);
	var dia
	var mn=['January','February','March','April','May','June','July','August','September','October','November','December'];
	var smn=['Domingo','Segunda','Terca','Quarta','Quinta','Sexta','Sabado'];

	var fdia = new Array();
	var idia = new Array();
	
	var DiasdoMes=[31,0,31,30,31,30,31,31,30,31,30,31];
	DiasdoMes[1]=(((data.getFullYear()%100!=0)&&(data.getFullYear()%4==0))||(data.getFullYear()%400==0))?29:28;
	
	year = data.getYear(); // Retorna o ano
	month = data.getMonth(); // Retorna mes (0-11)
	today = data.getDate(); // Retorna dias (1-31)
	weekday = data.getDay(); // Retorna o dia da semana (Domingo 0, segunda 1, terça 2, etc)
	
	if (valor!=""){
		aux = 0;
		idia[0] = today;

		for(i=parseInt(weekday);i<=DiasdoMes[month]+parseInt(weekday);i++,dia++)
		{	if(i%7==0 && i != today)
			{
				if(i-parseInt(weekday)==0)
				{
					fdia[aux] = today;
					aux++;
					idia[aux] = i-parseInt(weekday)+2;
				} 
				else 
				{
					fdia[aux] = i-parseInt(weekday)+1;
					aux++;
					idia[aux] = i-parseInt(weekday)+2;
				}
			}
		}
		
		limpa_campo(campoauxiliar,form);
		if (typeof(document.total_getal_mensal)!="undefined"){
			document.location.href=eval("'carregavendas.asp?meses=' + valor+''")
			document.total_getal_mensal.comp_mensal.value="Aguarde ... buscando informacao de vendas....";
			document.total_getal_mensal.comp_mensal.disabled=true;
		}
		
		for(i=0;i<=idia.length;i++){
			if(typeof idia[i] != "undefined" && idia[i]<=DiasdoMes[month]){
				if(typeof fdia[i] != "undefined"){
					 fd = fdia[i]>DiasdoMes[month]?DiasdoMes[month]:fdia[i];
					 mark = valormarcado==idia[i]+'-'+fd?true:false;
					 
//					 if ((dialimite > 0) && (fd > dialimite))
//						fd = dialimite;
					 
//					 if ((dialimite == 0) || (dialimite >= idia[i]))
						 preenche_campo(campoauxiliar,form,idia[i]+'-'+fd,'Dia '+ idia[i]+" até o dia "+fd,mark)
				}else{
					mark = valormarcado==idia[i]+'-'+DiasdoMes[month]?true:false;
//					 if ((dialimite == 0) || (dialimite >= idia[i]))
						preenche_campo(campoauxiliar,form,idia[i]+'-'+DiasdoMes[month],'Dia '+ idia[i]+" até o dia "+DiasdoMes[month],mark)
				}
			}
		}
	}
}

	function Tecla(e)
	{
/*		if (document.all)
			var tecla = event.keyCode;
		else if(document.layers)
			var tecla = e.which;
		
		if ( ( tecla > 47 && tecla < 58 ) )
				return true;
		else
		{
			if (tecla != 8)
				event.keyCode = 0;
			else
				return true;
		}*/
	}
	
function Limpar(valor, validos) 
{
	// retira caracteres invalidos da string
	var result = "";
	var aux;
	 for (var i=0; i < valor.length; i++) 
	{
		aux = validos.indexOf(valor.substring(i, i+1));
		 if (aux>=0) 
		{
			result += aux;
		}
	}
		return result;
}

	function Formata(campo,tammax,teclapres,decimal) 
	{ 
		var tecla = teclapres.keyCode; 
		vr = Limpar(campo.value,"0123456789.-"); 

		tam = vr.length; 
		dec=decimal 

		if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; } 

		if (tecla == 8 ) 
		{ tam = tam - 1 ; } 

		if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ) 
		{ 
			// DESABILITA CAMPOS
			document.frmVendas.compro.disabled=true;
			document.frmVendas.comp_mensal.disabled=true;

			// HABILITA CAMPOS
			document.frmVendas.enviar.disabled=false;
			document.frmVendas.total_geral.disabled=false;
			
			
			if ( tam <= dec ) { 
				campo.value = vr ; 
			} else if ( (tam > dec) && (tam <= 5) ){ 
				campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; 
			} else if ( (tam >= 6) && (tam <= 8) ){ 
				campo.value = vr.substr( 0, tam - 5 ) + "" + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
			} else if ( (tam >= 9) && (tam <= 11) ){ 
				campo.value = vr.substr( 0, tam - 8 ) + "" + vr.substr( tam - 8, 3 ) + "" + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
			} else if ( (tam >= 12) && (tam <= 14) ){ 
				campo.value = vr.substr( 0, tam - 11 ) + "" + vr.substr( tam - 11, 3 ) + "" + vr.substr( tam - 8, 3 ) + "" + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
			} else if ( (tam >= 15) && (tam <= 17) ){ 
				campo.value = vr.substr( 0, tam - 14 ) + "" + vr.substr( tam - 14, 3 ) + "" + vr.substr( tam - 11, 3 ) + "" + vr.substr( tam - 8, 3 ) + "" + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;
			} 
		} 

	}


	 //ARREDONDA CASAS DECIMAIS PARA FORMATO MOEDA
	 function Arredonda( valor , casas )
	 {
	    var novo = Math.round( valor * Math.pow( 10 , casas ) ) / Math.pow( 10 , casas );
	    return( novo );
	 }


function valida_mail(valor) {
	prim = valor.indexOf("@")
	if(prim < 1) return false;
	if(valor.indexOf("@",prim + 1) != -1) return false
	if(valor.indexOf(".") < 1) return false;
	if(valor.indexOf("zipmeil.com") > 0) return false;
	if(valor.indexOf("hotmeil.com") > 0) return false;
	if(valor.indexOf(".@") > 0) return false;
	if(valor.indexOf("@.") > 0) return false;
	if(valor.indexOf(".com.br.") > 0) return false;
	if(valor.indexOf("/") > 0) return false;
	if(valor.indexOf("[") > 0) return false;
	if(valor.indexOf("]") > 0) return false;
	if(valor.indexOf("(") > 0) return false;
	if(valor.indexOf(")") > 0) return false;
	if(valor.indexOf("..") > 0) return false;
	if(valor.indexOf(",") > 0) return false;
	return true;

}

function popup(URL,name,w,h) {
	largura = w	 ;
	altura = h ;
	X = (screen.availWidth - largura) / 2;
	Y = (screen.availHeight - altura) / 2;
		window.open(URL,name,'width=' + largura + ',height=' + altura + ',top=' + Y + ',left=' + X + ',screenX=' + X + ',screenY=' + Y+',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0');
}

function ValidaInteiro(valor) {
	var strNumeros = '0123456789';

	for (i = 0; i < valor.length; i++)
		if ((strNumeros.indexOf(valor.substr(i, 1)) == -1) && !((i == 0) && (valor.substr(i, 1) == '-')))
	{
				return false;
	}
	return true;}

function FormataInteiro(campo, event) {
	var strNumeros = '0123456789';

	for (i = 0; i < campo.value.length; i++)
		if ((strNumeros.indexOf(campo.value.substr(i, 1)) == -1) && !((i == 0) && (campo.value.substr(i, 1) == '-'))) {
			campo.value = campo.value.substr(0, i);
			return false;
		}}

function msg(mensagem){
	alert(mensagem);
}

var strColumns_Current = '235, *';

function EscondeMenu() {
	strColumns_Current = top.mainframeset.cols

	top.mainframeset.cols = "0,*";
	top.main.document.all("abreMenu").style.display = "block";
	top.main.document.all("fechaMenu").style.display = "none";
}


function AbreMenu() {
	top.mainframeset.cols = strColumns_Current;
	document.all("abreMenu").style.display = "none";
	document.all("fechaMenu").style.display = "block";
}

function VerificaMenu() {
	if (top.mainframeset.cols == "0,*") {
		document.all("abreMenu").style.display = "block";
		document.all("fechaMenu").style.display = "none";
	}
}

function atualiza_top(id,chavestrang,chave,nivel){
	window.top.topframe.location.href="top.asp?id="+id+"&chavestrang="+chavestrang+"&chave="+chave+"&nivel="+nivel;
}

function desabilita_campos(campo){
	if (campo.name!="total_geral"){
// DESABILITA CAMPOS
		if (typeof(document.frmVendas.compro)=="object")
		{
			document.frmVendas.compro.disabled=true;
		}
// HABILITA CAMPOS
	document.frmVendas.enviar.disabled=false;
	}

}

function FormataFloat(campo, event) {
	var strNumeros = '0123456789';
	var flgVirgula = false;
	for (i = 0; i < campo.value.length; i++){
		if ((strNumeros.indexOf(campo.value.substr(i, 1)) == -1) && !((i == 0) && (campo.value.substr(i, 1) == '-'))) {
			desabilita_campos(campo);
			if ((((i > 0) && (campo.value.substr(i - 1, 1) != '-')) || (i > 1)) && (campo.value.substr(i, 1) == ',') && !flgVirgula){
				flgVirgula = true;
			}else if ((((i > 0) && (campo.value.substr(i - 1, 1) != '-')) || (i > 1)) && (campo.value.substr(i, 1) == '.') && !flgVirgula) {
				//campo.value = campo.value.replace('.', ',');
				flgVirgula = true;
			} else {
				campo.value = campo.value.substr(0, i);
				return false;
			}
		}
	}
}

function altera_senha(form){
	if (form.senha_atual.value==""){
		alert("Por favor, digite sua senha atual.");
		form.senha_atual.focus();
		return false;
	}
	if (form.senha_nova.value==""){
		alert("Por favor, digite sua senha nova.");
		form.senha_nova.focus();
		return false;
	}
	if (form.confirma_senha_nova.value==""){
		alert("Por favor, digite a confirmação da sua nova senha.");
		form.confirma_senha_nova.focus();
		return false;
	}
	if (!(form.senha_nova.value==form.confirma_senha_nova.value)){
		alert("Por favor, a confirmação da sua nova senha deve ser igual a nova senha digitada.");
		form.confirma_senha_nova.select();
		return false;
	}
	return true;
	
}

function valida_entrada_grid(form){
	if (form.mes.value==""){
		alert("Por favor, selecione o mês de referência.");
		form.mes.focus();
		return false;
	}
	if (form.semanas.value==""){
		alert("Por favor, a semana para efeuar o lançamento de vendas.");
		form.semanas.focus();
		return false;
	}

//	if (form.idia.value==""){
//		alert("Por favor, selecione o dia inicial de preenchimento");
//		form.idia.focus();
//		return false;
//	}
//	if (form.fdia.value==""){
//		alert("Por favor, selecione o dia final de preenchimento.");
///		form.fdia.focus();
//		return false;
//	}
//	if (parseInt(form.fdia.value) < parseInt(form.idia.value)){
//		alert("Por favor, preencha corretamente, o dia final de preenchimento deve ser maior ou igual ao dia inicial.");
//		form.fdia.focus();
//		return false;
//	}
}


var janela = null;

function focarJanela()
{
	if (janela != null) 
	{
		janela.focus();
		janela = null;
		return;
	}

	setTimeout("focarJanela()", 1000);
}

function abrePopupLocal(url, nome, largura, altura, esquerda, topo, barrasRolagem, redimensionavel)
{
	var propriedades = '';
	
	propriedades += 'scrollbars=' + (barrasRolagem ? 1 : 0) + ', fullscreen=0, toolbar=0, statusbar=0, directories=0, fullscreen=0, ';
	propriedades += 'resizable=' + (redimensionavel ? 1 : 0) + ', location=0, menubar=0, width=' + largura + ',';
	propriedades += 'height=' + altura + ', top=' + topo + ', left=' + esquerda;
	
	
	if (window.showModalDialog) {
		var novaJanela = window.showModalDialog(url, nome, propriedades);
		alert(novaJanela);
		//var novaJanela = window.open(url, nome, propriedades);
		
	} else {
		try {
			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
			//var novaJanela = window.showModalDialog(url, nome, propriedades);
			var novaJanela = window.open(url, "wndModal", propriedades + ",modal=yes");
			//return true;
		}
		catch (e) {
			alert("Script não confiável, não é possível abrir janela modal.");
			return false;
		}
	}
	novaJanela.resizeTo( largura, altura );
	novaJanela.moveTo( esquerda, topo );
	
	janela = novaJanela;
	
	setTimeout("focarJanela()", 10);

	return (novaJanela);
}

function abrePopupMouse(url, nome, largura, altura, barrasRolagem, redimensionavel, NomeJanela)
{
	var esquerda = event.screenX;
	var topo = event.screenY;

	openModal(url, largura, altura, NomeJanela);
	return true;
//	return abrePopupLocal(url, nome, largura, altura, esquerda, topo, barrasRolagem, redimensionavel);
}

function abrePopupCentro(url, nome, largura, altura, barrasRolagem, redimensionavel, NomeJanela)
{
	var esquerda = (screen.availWidth - largura) / 2;
	var topo = (screen.availHeight - altura) / 2;
	
	openModal(url, largura, altura, NomeJanela);
	return true;
//	return abrePopupLocal(url, nome, largura, altura, esquerda, topo, barrasRolagem, redimensionavel);
}

function popup(URL,name,w,h) {
	largura = w	 ;
	altura = h ;
	X = (screen.availWidth - largura) / 2;
	Y = (screen.availHeight - altura) / 2;
	popup =window.open(URL,name,'width=' + largura + ',height=' + altura + ',top=' + Y + ',left=' + X + ',screenX=' + X + ',screenY=' + Y+',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0');
	return popup;
}

function confere_popup(pagina,msg_erro,nome,largura,altura,barrasRolagem, redimensionavel, NomeJanela){
	
	if (!abrePopupCentro(pagina, nome, largura, altura, barrasRolagem, redimensionavel, NomeJanela)){
		alert(msg_erro);
	}
}

function FormataReais(fld, milSep, decSep, e,form) { 
	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; 
    var alt=window.event.altKey;      // Para Controle da Tecla ALT 
    var ctrl=window.event.ctrlKey;    //  Para Controle da Tecla CTRL
	
	if (whichCode>=96 && whichCode<=105)whichCode = whichCode-48;
	if (whichCode == 27) return true; 
	if (whichCode == 46) return true; 
	if ((whichCode == 17 && ctrl) || (whichCode == 82 && ctrl)) return true; 
	if (whichCode == 18 && alt) return true; 
	if (whichCode == 116) return true; 
	if (whichCode == 9 || whichCode == 9 && whichCode == 16) return true; 
	if (whichCode == 8) return true; 
	if (fld.value.length>15) return false;

	key = String.fromCharCode(whichCode);// Valor para o código da Chave 
	if (strCheck.indexOf(key) == -1) return false; // Chave inválida 

	desabilita_campos(fld);

	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 login(e){
	var whichCode = (window.Event) ? e.which : e.keyCode; 
    var alt=window.event.altKey;      // Para Controle da Tecla ALT 
    var ctrl=window.event.ctrlKey;    //  Para Controle da Tecla CTRL
//	alert(whichCode);
	if (alt) return false;
	if (ctrl) return false;
	if (whichCode==91) return false;
	if (whichCode==18 && whichCode==9) return false;
}

function enviarform(){
	form = document.frmVendas;
	for (i=0; i<form.length; i++){
		if (typeof eval("form.elements["+ i +"]") == 'object' && form.elements[i].type=="text"){
			if (form.elements[i].name.substr(0,6)=="VENDAS" || form.elements[i].name.substr(0,5)=="PRAZO" || form.elements[i].name.substr(0,5)=="DESCO"){
				form.elements[i].disabled=false;
			}
		}
	}
	form.submit();
}

/*

		if (typeof eval("form.elements["+ i +"]") == 'object' && form.elements[i].type=="text"){
			if (form.elements[i].name.substr(0,6)=="VENDAS" || form.elements[i].name.substr(0,5)=="PRAZO" || form.elements[i].name.substr(0,5)=="DESCO"){
				alert(form.elements[i].name);
				form.elements[i].disabled=false;
			}
		}


<script>function fcnAlphaNum() {
 var caract = new RegExp(/^[0-9a-zA-Z]+$/i);
 var caract = caract.test(String.fromCharCode(event.keyCode));

 if(!caract){
   event.keyCode=0;
   return;
 }
}</script>

<input type="text" name="login" onKeyPress="fcnAlphaNum()"
*/

/**
* Javascript prototypes - String.pad() and Number.format()
* Carlos Reche (carlosreche@yahoo.com)
*/
String.PAD_LEFT  = 0;
String.PAD_RIGHT = 1;
String.PAD_BOTH  = 2;

String.prototype.pad = function(size, pad, side) {
  var str = this, append = "", size = (size - str.length);
  var pad = ((pad != null) ? pad : " ");
  if ((typeof size != "number") || ((typeof pad != "string") || (pad == ""))) {
    throw new Error("Wrong parameters for String.pad() method.");
  }
  if (side == String.PAD_BOTH) {
    str = str.pad((Math.floor(size / 2) + str.length), pad, String.PAD_LEFT);
    return str.pad((Math.ceil(size / 2) + str.length), pad, String.PAD_RIGHT);
  }
  while ((size -= pad.length) > 0) {
    append += pad;
  }
  append += pad.substr(0, (size + pad.length));
  return ((side == String.PAD_LEFT) ? append.concat(str) : str.concat(append));
}

Number.prototype.format = function(d_len, d_pt, t_pt) {
  var d_len = d_len || 0;
  var d_pt  = d_pt  || ",";
  var t_pt  = t_pt  || ".";
  
   if ((typeof d_len != "number") || (typeof d_pt != "string") || (typeof t_pt != "string")) 
  {
	  throw new Error("wrong parameters for method 'String.pad()'.");
  }
  var integer = "", decimal = "";
  var n = new String(this).split(/\./), i_len = n[0].length, i = 0;
  if (d_len > 0) {
    n[1] = (typeof n[1] != "undefined") ? n[1].substr(0, d_len) : "";
    decimal = d_pt.concat(n[1].pad(d_len, "0", String.PAD_RIGHT));
  }
  while (i_len > 0) {
    if ((++i % 3 == 1) && (i_len != n[0].length)) {
      integer = t_pt.concat(integer);
    }
    integer = n[0].substr(--i_len, 1).concat(integer);
  }
  return (integer + decimal);
}

function FormataValores(campo,tammax,teclapres,decimal) {
var tecla = teclapres.keyCode;
vr = Limpar(campo.value,"0123456789");
tam = vr.length;
dec=decimal

if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

if (tecla == 8 )
{ tam = tam - 1 ; }

if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
{

if ( tam <= dec )
{ campo.value = vr ; }

if ( (tam > dec) && (tam <= 5) ){
campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 6) && (tam <= 8) ){
campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; 
}
if ( (tam >= 9) && (tam <= 11) ){
campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 12) && (tam <= 14) ){
campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ; }
if ( (tam >= 15) && (tam <= 17) ){
campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;}
} 

}

// ************** Formata valores

/**
* Javascript prototypes - String.pad() and Number.format()
* Carlos Reche (carlosreche@yahoo.com)
*/
String.PAD_LEFT  = 0;
String.PAD_RIGHT = 1;
String.PAD_BOTH  = 2;

String.prototype.pad = function(size, pad, side) {
  var str = this, append = "", size = (size - str.length);
  var pad = ((pad != null) ? pad : " ");
  if ((typeof size != "number") || ((typeof pad != "string") || (pad == ""))) {
    throw new Error("Wrong parameters for String.pad() method.");
  }
  if (side == String.PAD_BOTH) {
    str = str.pad((Math.floor(size / 2) + str.length), pad, String.PAD_LEFT);
    return str.pad((Math.ceil(size / 2) + str.length), pad, String.PAD_RIGHT);
  }
  while ((size -= pad.length) > 0) {
    append += pad;
  }
  append += pad.substr(0, (size + pad.length));
  return ((side == String.PAD_LEFT) ? append.concat(str) : str.concat(append));
}

Number.prototype.formatValor = function(cent, d_len) {
  var cent 	= cent  || 0;
  var d_len = d_len || 0;
  
   if ((typeof d_len != "number") || (typeof cent != "number")) 
  {
	  throw new Error("wrong parameters for method 'String.pad()'.");
  }
  
  var integer = "", decimal = "";
  
  var n = new String(this).split(/\./), i_len = n[0].length, i = 0;
  alert()
  if (d_len > 0) {
    n[1] = (typeof n[1] != "undefined") ? n[1].substr(0, d_len) : "";
    decimal = d_pt.concat(n[1].pad(d_len, "0", String.PAD_RIGHT));
  }
  while (i_len > 0) {
    if ((++i % 3 == 1) && (i_len != n[0].length)) {
      integer = t_pt.concat(integer);
    }
    integer = n[0].substr(--i_len, 1).concat(integer);
  }
  return (integer + decimal);
}

// ************** Fim Formata valores

 //Convert  valores para Float
 function formatFloat(valores) 
{
  var valores  = valores || 0;

    valores = valores.replace(/\./, '');
    valores = valores.replace('.','');
    valores = valores.replace(/\,/, '.');
	return valores;
}

 function formatValores(Valor) 
{
	var valor = new String(Valor) || "";
	var d_div = ","; 
	var c_div = "."; 
	var integer = ""; 
	var decimal = "";
	// Verifica se os parametros passados estão no formato correto
//	if ((typeof valor != "string")) 
//	  throw new Error("Parametro errado enviado'.");
	
	// Convert o valor em array
	valor = valor.split(/\./), i_len = valor[0].length, i = 0;
	// Pega os dois ultimos valores
	valor[1] = (typeof valor[1] != "undefined") ? valor[1].substr(0, 2) : "";
	// Pega as casas decimais e inclui o zero se necessário e concatena com a virgula
	decimal = d_div.concat(valor[1].pad(2, "0", String.PAD_RIGHT));
	
	 while (i_len > 0) 
	{
		 if ((++i % 3 == 1) && (i_len != valor[0].length)) 
		  integer = c_div.concat(integer);

		// Pega as casas inteiras e inclui o zero se necessário e concatena com a virgula
		 integer = valor[0].substr(--i_len, 1).concat(integer);
	}
	
	return (integer + decimal);
}


function SubmetCompetencias(Tipo, UltimoDia, VendaHoje)
{
	var data 	 = new Date();
	var diaAtual = data.getDate();
	var mesAtual = data.getMonth() + 1;
	
	if (Tipo == 0)
	{
		if (document.form1.mes.value != "")
			document.location.href = '?meses='+document.form1.mes.value;
		else
			document.location.href = '';
	}
	else
	{
		dataCompetencia = document.form1.mes.value.split("-");
		
		if (Tipo == 1)
		{			
			
			if ((document.form1.PerFim.value > diaAtual) && (document.form1.PerInicio.value > diaAtual) && (parseInt(dataCompetencia[1]) == parseInt(mesAtual)))
			{
				alert("O período não pode ser superior a data atual.");
				return false;
			}
		
			//Verifico se é para travar o dia atual ou não
			if (VendaHoje == "Sim")
			{			
				if ((document.form1.PerFim.value == diaAtual) && (parseInt(dataCompetencia[1]) == parseInt(mesAtual)))
				{
					alert("É necessário aguardar 24h para informar as vendas deste período!");
					return false;
				}
			
			}
			
			if (CheckPeriodo(UltimoDia)) 
			{
				document.form1.action = '';
				if (typeof(document.form1.PerInicio) == 'object' && typeof(document.form1.PerFim) == 'object') 
				{
					document.form1.semanas.value = document.form1.PerInicio.value+"-"+document.form1.PerFim.value;
				}
				document.form1.submit();
			}
		}
		else
		{
			arrSemana = document.form1.semanas.value.split("-");			
		
			if ((diaAtual < arrSemana[0]) && (parseInt(dataCompetencia[1]) == parseInt(mesAtual)))
			{
				alert("Esta semana não está disponível para informar venda.");
				return false;
			}
			else
			{
				document.form1.submit();
			}
		}
	}
	return true;	
}

 function CheckPeriodo(DiaFim)
 {
	var DiaFim = DiaFim
	 if (typeof(document.form1.PerInicio) == 'object' && typeof(document.form1.PerFim) == 'object')
	{
		 PerInicio = document.form1.PerInicio;
		 PerFim = document.form1.PerFim;

		 if (PerInicio.value == '')		
		{	
			alert("Por favor, informe o dia da data inicial!");
			PerInicio.value = "";
			PerInicio.focus();
			return false;
		}	

		 if (PerFim.value == '')		
		{	
			alert("Por favor, informe o dia da data final!");
			PerFim.value = "";
			PerFim.focus();
			return false;
		}	
	
		 if (Math.round(PerInicio.value) < 1 || Math.round(PerInicio.value) > Math.round(DiaFim))		
		{	
			alert("A data inicial do período deve estar entre 1 e "+Math.round(DiaFim)+"");
			PerInicio.value = "";
			PerInicio.focus();
			return false;
		}	

		 if (Math.round(PerFim.value) < 1 || Math.round(PerFim.value) > Math.round(DiaFim))		
		{	
			alert("A data final do período deve estar entre 1 e "+Math.round(DiaFim)+"");
			PerFim.value = "";
			PerFim.focus();
			return false;
		}	

	 if (Math.round(PerFim.value) < Math.round(PerInicio.value))
		{
			alert('A data final do período não pode ser maior que a data inicial.');
			return false;
		}

	 }	
		return true;
	}	
	
function Submeter(campo)
{
	var ElementoNull = '';

	if (document.getElementById("totalvalid").value != document.getElementById("valida_total").value)
	{
		alert("A soma dos valores informados por dia\nnão confere com o valor total informado.\n\n Total informado: "+document.getElementById("valida_total").value+"\n Valor digitado p/ dia: "+document.getElementById("totalvalid").value+"\n\nPor favor, confira o valores digitados.");
		return false;
	}		
	
	document.frmVendas.submit();
}

function validaVenda()
{
	for (i = 0; i < document.all.length; i++)
	{	
		oElemento = document.all[i];
		
		if (oElemento.type == 'text' && oElemento.name.substr(0,6) == 'VENDAS')
		{	
			if (oElemento.value == '') 
			{
				alert('Favor informar um valor maior ou igual a zero!');
				oElemento.focus();
				oElemento.select();
				return false;
			}
		}
	}
	return true;
}
	
 function LibCampos()
{
		for (i = 0; i < document.all.length; i++)
	 {
				oElemento = document.all[i];
			if (oElemento.type == 'text' && oElemento.disabled == true && oElemento.name.substr(0,6) == 'VENDAS')
			{						
				  if (document.getElementById("valida_total").value == "" || document.getElementById("valida_total").value == "0,00") {		
					
							if (oElemento.disabled == false) {
										oElemento.disabled = true; }
				  }
				   else {		

							if (oElemento.disabled == true) {
										oElemento.disabled = false; }
				  } 	
		   }
}

 }
 
 // Submete busca
 function submete_busca()
{
	if (document.busca.Loja.value == "" && document.busca.Contrato.value == "" && document.busca.NomeFantasia.value == "")
	{
		alert("Por favor, preencha ao menos um campo para efetuar a busca.");
		document.busca.Loja.focus();
		return false;
	}
	document.busca.submit();
//	BuscaConteudoVendas ('Loja='+document.getElementById('Loja').value+'&Contrato='+document.getElementById('Contrato').value+'&NomeFantasia='+document.getElementById('NomeFantasia').value, 'compartilhados/lib_busca_retorno.asp', 'retonoBusca', 'retonoBusca')

}


function BuscaConteudoVendas (pstrParam, pstrURL, pstrDivResposta, pstrDivretorno)
{	
	var objAjax; 
	/** Criando o objeto Ajax **/ 
	objAjax = createXMLHTTP();	
	
	document.getElementById(pstrDivResposta).innerHTML 	= '<center><span class="bordaBairros" style="background:#FFFFFF;"><span style=" height:17px; padding-top:1px; text-align:center;">&nbsp;&nbsp;&nbsp;&nbsp; Aguarde... &nbsp;&nbsp;&nbsp;&nbsp;</span></span></center>';
	//Efetuando a abertura da requisição, Tipo, URL Requirida, Tipo de Conexão true - Assincrona e false sincrona 
	objAjax.open("Post", pstrURL+"?"+pstrParam, true);
	
	//Informando o tipo da página de requisição 
	objAjax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	//Informando o controle de cachê no caso abaixo informando para ignorar o cachê 
	objAjax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	objAjax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	objAjax.setRequestHeader("Pragma", "no-cache");

	objAjax.onreadystatechange=function()
		{		
			//Validando o status do retorno 
			if (objAjax.readyState==4)
			{				
				//Informando aonde o conteúdo deve ser posicionado 
				document.getElementById(pstrDivResposta).innerHTML = '';
				document.getElementById(pstrDivretorno).innerHTML = objAjax.responseText;
			}
		}

		//Perceba que a requesição deve ser feita abaixo da função onreadystatechange, Não esqueça de colocar null se não houver nenhum parâmetro senão não funciona nos outros navegadores. 
		objAjax.send(pstrParam);
	 
}

//Alterar a visibilidade de uma DIV.
function visibilidade(qualDiv, status)
{
	document.getElementById(qualDiv).style.display = status;
}

//Verifica se o cliente definiu o dia limite
function definiuDiaLimite(form)
{
	if (form.Periodo[0].checked)
	{
		if (form.NDiasVenda.value == "")
		{
			alert('Entre com o "Número de dia(s) para informação da venda."');
			form.NDiasVenda.focus();
			form.NDiasVenda.select();
			return false;
		}
	}
	else 
	{
		if (form.DiaSemanaLimite.value == "Null")
		{
			alert('Selecione o dia da semana.');
			form.DiaSemanaLimite.focus();
			return false;
		}		
	}
	return true;
}

function openModal(pUrl, pWidth, pHeight, NomeJanela) {
	
	if (window.showModalDialog)
	{
		return window.showModalDialog(pUrl, NomeJanela, "dialogWidth:" + pWidth + "px;dialogHeight:" + pHeight + "px");
	} 
	else 
	{
		try 
		{
			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");
			window.open(pUrl, NomeJanela, "width=" + pWidth + ",height=" + pHeight + ",resizable=no,modal=yes");
			return true;
		}
		catch (e) 
		{
			alert("Script não confiável, não é possível abrir janela modal.");
			return false;
		}
	}
}


	//**** FUNÇÃO..........: MenuExibi
	//**** PARAMETROS......: NomeDiv	
	//**** DESCRIÇÃO.......: Função que exibe os itens da página de administração de acordo com o menu selecionado
	//**** DATA............: 26/06/2009

	function MenuExibi(NomeDiv)
	{
		var i
		var ArrDivs = new Array("DivInformacaoVendas", "DivSegundaVia", "DivLogin", "DivImpressao", "DivBancoDados");
		
		for (i=0; i<ArrDivs.length; i++)
		{
			if (document.getElementById(ArrDivs[i]) == '[object]')
				document.getElementById(ArrDivs[i]).style.display = 'none';
		}
		
		document.getElementById(NomeDiv).style.display = 'block';
		document.getElementById("Tipo").value = NomeDiv;
	}
	
	
	function AtivaOpcoes(ativador, Div)
	{
		 if (document.getElementById("dadosAcesso").disabled == true)
		{
				document.getElementById("dadosAcesso").disabled = false;
		}
	 	 else
		{ 
				document.getElementById("dadosAcesso").disabled = true;
		}	
	}