function overlay(n)
{
	if (n == 1)
		$.blockUI();
	else
		$.unblockUI();
}
//função redimensiona

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 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 - 18;
	} 
	else 
	{
		pageWidth = xScroll;
	}
	
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}


var Window =
{
	
	'_open': function(id) 
	{
		loadAjax('load-video.php?ID='+id,'divVideo');
		document.getElementById('divVideo').style.display = 'block';
		
		//if (document.all)
		//var pos = evt.clientY;
		//else
		// var pos = window.pageYOffset;
		
		var pageSize = getPageSize();
		
		var objScroll = getPageScroll();
		//alert(objScroll[1]);
		
		var winW = pageSize[0];
		var winY = pageSize[1];
		
		//menos a largura da div
		var w = (winW - 500) / 2;
		 //menos a altura da div
		//var y = (winY - 500) / 2;
		
		var y = objScroll[1];
		//alert(w);
		//alert(y);
		
		document.getElementById('divVideo').style.left = w + 'px';
		document.getElementById('divVideo').style.top = y + 'px';
		
	},
	
	'_close': function()
	{
		document.getElementById('divVideo').style.display='none';	
		document.getElementById('divVideo').innerHTML = "";
	},
	
	'_open2': function(div,divW,divH) 
	{
		
		
		//if (document.all)
		//var pos = evt.clientY;
		//else
		// var pos = window.pageYOffset;
		
		var pageSize = getPageSize();
		
		var objScroll = getPageScroll();
		//alert(objScroll[1]);
		
		var winW = pageSize[0];
		var winY = pageSize[1];
		
		//menos a largura da div
		var w = (winW - divW) / 2;
		 //menos a altura da div
		//var y = (winY - 500) / 2;
		
		var y = objScroll[1] + 20;
		//alert(w);
		//alert(y);
		
		document.getElementById(div).style.left = w + 'px';
		document.getElementById(div).style.top = y + 'px';
		document.getElementById(div).style.display = 'block';
	},
	
	'_close2': function(div)
	{
		document.getElementById(div).style.display='none';
	}	
}






function isCpf(CPF)
{
	if(CPF.length<14)
		return false;
	
	//retira os '.' e o '-' da string do cpf (ex. '123.123.123-45' => '12312312345') para compatibilizar com a função isCPF
	CPF = CPF.substr(0,3) + CPF.substr(4,3) + CPF.substr(8,3) + CPF.substr(12,2);
	
	var i;
	var c = CPF.substr(0,9);
	var dv = CPF.substr(9,2);
	var d1 = 0;
	
	for (i = 0; i < 9; i++)
		d1 += c.charAt(i)*(10-i);

	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 < 9; i++)
	d1 += c.charAt(i)*(11-i);
	 
	d1 = 11 - (d1 % 11);
	 
	if (d1 > 9)
		d1 = 0;
	 
	if (dv.charAt(1) != d1)
		return false; 
	 
	return true; 
} //isCpf

function isCnpj(CNPJ)
{
	erro = new String;
	if (CNPJ.length < 18) return false;

	//substituir os caracteres que não são números
	if(document.layers && parseInt(navigator.appVersion) == 4){
		x = CNPJ.substring(0,2);
		x += CNPJ. substring (3,6);
		x += CNPJ. substring (7,10);
		x += CNPJ. substring (11,15);
		x += CNPJ. substring (16,18);
		CNPJ = x;
	} 
	else
	{
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace ("-","");
		CNPJ = CNPJ. replace ("/","");
	}
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)) return false;
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++)
	{
		a[i] = CNPJ.charAt(i);
		b += a[i] * c[i+1];
	}
	
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
	b = 0;
	
	for (y=0; y<13; y++) 
		   b += (a[y] * c[y]);
		   
	if ((x = b % 11) < 2)
		a[13] = 0;
	else
		a[13] = 11-x;
		
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13]))
	{
		  return false;
	}
	if (erro.length > 0)
	{
		   alert(erro);
		   return false;
	} 
	return true;
} //isCnpj

/*
function document.getElementById(id)
{
	return document.getElementById(id);
}*/

function $v(id)
{
	return document.getElementById(id).value;
}

//OPEN
function MM_displayStatusMsg(msgStr) { //v1.0
  status=msgStr;
  document.MM_returnValue = true;
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}


//CENTRALIZADA
function openPop(url, name, w, h, scroll) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
//	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable';
	winprop = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll;
	
	win = window.open(url, name, winprop)
	if(parseInt(navigator.appVersion) >= 4) {
		win.window.focus(); 
	}
}

//REDIRECIONAMENTOS
function Redirect(url) {
	document.location = url;
}

function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function goURL(url) {
	document.location = url;
}


//ABRE POP
function Pop(url,name,caract) {
  window.open(url,name,caract);
}


//MÁSCARAS
function mascaraCep(objeto){
	if (objeto.value.indexOf("-") == -1 && objeto.value.length > 5){ objeto.value = ""; }
	if (objeto.value.length == 5){
		objeto.value += "-";
	}
}

<!-- Begin
var n;
var p;
var p1;
function ValidatePhone(){
p=p1.value
if(p.length==2){
	//d10=p.indexOf('(')
	pp=p;
	d4=p.indexOf('(')
	d5=p.indexOf(')')
	if(d4==-1){
		pp="("+pp;
	}
	if(d5==-1){
		pp=pp+")";
	}
	//pp="("+pp+")";
	document.form1.telefone.value="";
	document.form1.telefone.value=pp;
}
if(p.length>2){
	d1=p.indexOf('(')
	d2=p.indexOf(')')
	if (d2==-1){
		l30=p.length;
		p30=p.substring(0,4);
		//alert(p30);
		p30=p30+")"
		p31=p.substring(4,l30);
		pp=p30+p31;
		//alert(p31);
		document.form1.telefone.value="";
		document.form1.telefone.value=pp;
	}
	}
if(p.length>5){
	p11=p.substring(d1+1,d2);
	if(p11.length>3){
	p12=p11;
	l12=p12.length;
	l15=p.length
	//l12=l12-3
	p13=p11.substring(0,3);
	p14=p11.substring(3,l12);
	p15=p.substring(d2+1,l15);
	document.form1.telefone.value="";
	pp="("+p13+")"+p14+p15;
	document.form1.telefone.value=pp;
	//obj1.value="";
	//obj1.value=pp;
	}
	l16=p.length;
	p16=p.substring(d2+1,l16);
	l17=p16.length;
	if(l17>3&&p16.indexOf('-')==-1){
		p17=p.substring(d2+1,d2+5);
		p18=p.substring(d2+5,l16);
		p19=p.substring(0,d2+1);
		//alert(p19);
	pp=p19+p17+"-"+p18;
	document.form1.telefone.value="";
	document.form1.telefone.value=pp;
	//obj1.value="";
	//obj1.value=pp;
	}
}
//}
setTimeout(ValidatePhone,100)
}
function getIt(m){
n=m.name;
//p1=document.forms[0].elements[n]
p1=m
ValidatePhone()
}
function testphone(obj1){
p=obj1.value
//alert(p)
p=p.replace("(","")
p=p.replace(")","")
p=p.replace("-","")
p=p.replace("-","")
//alert(isNaN(p))
if (isNaN(p)==true){
alert("Check phone");
return false;
}
}
//como aplicar onclick="javascript:getIt(this)"
//  End -->

/* Formatação para qualquer mascara */

function formatar(src, mask) 
{
  var i = src.value.length;
  var saida = mask.substring(0,1);
  var texto = mask.substring(i)
if (texto.substring(0,1) != saida) 
  {
	src.value += texto.substring(0,1);
  }
}

/* 
Exemplos:
CEP
OnKeyPress="formatar(this, '#####-###')"
CPF
OnKeyPress="formatar(this, '###.###.###-##')"
DATA
OnKeyPress="formatar(this, '##/##/####')"
*/

//DW
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_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}


//MUDA A COR DA LINHA
function mOvr(src,clrOver) { 
if (!src.contains(event.fromElement)) { 
src.style.cursor = 'pointer'; 
src.bgColor = clrOver; 
} 
} 
function mOut(src,clrIn) { 
if (!src.contains(event.toElement)) { 
src.style.cursor = 'default'; 
src.bgColor = clrIn; 
} 
} 
function mClk(src) { 
if(event.srcElement.tagName=='TD') 
src.children.tags('A')[0].click(); 
} 


//VALIDAÇÕES DE FORMULÁRIO

function validaProduto(){
	if(form1.nome_produto.value == ""){
	alert("O preenchimento do 'nome do produto' é obrigatório ! ");
	form1.nome_produto.focus();
	return false;
	}
	if(form1.descricao.value == ""){
	alert("O preenchimento do campo 'descrição' é obrigatório ! ");
	form1.descricao.focus();
	return false;
	}
	if(form1.grupo.value == 0){
	alert("Atenção, você precisa escolher um 'grupo' ! ");
	form1.grupo.focus();
	return false;
	}
	if(form1.categoria.value == 0){
	alert("Atenção, você precisa escolher um 'fabricante' ! ");
	form1.categoria.focus();
	return false;
	}
	if(form1.subcategoria.value == 0){
	alert("Atenção, você precisa escolher uma 'linha de produto' ! ");
	form1.subcategoria.focus();
	return false;
	}
}
function validaCategoria(){
	if(form1.grupo.value == 0){
	alert("Atenção, você precisa escolher um 'grupo' ! ");
	form1.grupo.focus();
	return false;
	}
	if(form1.nome_categoria.value == 0){
	alert("Atenção, você precisa digitar um nome para a categoria ! ");
	form1.nome_categoria.focus();
	return false;
	}
}
function validaSubcategoria(){
	if(form1.categoria.value == 0){
	alert("Atenção, você precisa escolher uma 'categoria' ! ");
	form1.categoria.focus();
	return false;
	}
	if(form1.nome_subcategoria.value == 0){
	alert("Atenção, você precisa digitar um nome para a subcategoria ! ");
	form1.nome_subcategoria.focus();
	return false;
	}
}
function listMail(){
	if(form1.destinatario.value == ""){
	alert("O preenchimento do e-mail destinatário é obrigatório !");
	form1.destinatario.focus();
	return false;
	}
    if (form1.destinatario.value.indexOf('@', 0) == -1){
	alert("O E-mail é Invalido !!!");
	form1.destinatario.focus();
	return (false);
	}
	if(form1.assunto.value == ""){
	alert("O preenchimento do campo assunto é obrigatório !");
	form1.assunto.focus();
	return false;
	}
}

function validaOrcamento(){
	
	if(form1.nome.value == ""){
	alert("O preenchimento do campo nome é obrigatório !");
	form1.nome.focus();
	return false;
	}
	if(form1.e_mail.value == ""){
	alert("O preenchimento do campo e-mail é obrigatório !");
	form1.e_mail.focus();
	return false;
	}
    if (form1.e_mail.value.indexOf('@', 0) == -1){
	alert("O E-mail é invalido !!!\nPor favor digite uma conta válida. ");
	form1.e_mail.focus();
	return (false);
	}
	if(form1.ddd.value == ""){
	alert("O preenchimento do campo ddd é obrigatório !");
	form1.ddd.focus();
	return false;
	}
	if(form1.telefone.value == ""){
	alert("O preenchimento do campo telefone é obrigatório !");
	form1.telefone.focus();
	return false;
	}
	if(form1.id_categoria.value == 0){
	alert("O selecionamento do campo categoria é obrigatório !");
	form1.id_categoria.focus();
	return false;
	}

}

function mostraFoto(registro,altura,largura){
	window.open('produtos/ver_foto.php?ID='+registro,'pop'+registro,'width='+largura+' height='+altura+' top=100 left=100 leftmargin=0 margintop=0 rightmargin=0 scrollbars=no')
}


//MOSTRA TEXTAREA PARA RESPONDER ORÇAMENTO
function loadResposta(){
	var objDiv = document.getElementById('divEditor').style.display;
//	var objBtn = document.getElementById('btnResponde').style.display;
	
	if(objDiv == 'block'){
		document.getElementById('divEditor').style.display = 'none';
	}
	else {
		 document.getElementById('divEditor').style.display = 'block';
		 document.getElementById('btnResponde').style.display = 'none';
		 document.getElementById('btnEnvia').style.display = 'block';
	}
}


//AJAX ADMIN

//CONFIRMA EXCLUSÃO DE FOTO
function ConfirmaExclusao(id,field,file,dir)
{
    if( confirm("Você deseja mesmo excluir esse registro do sistema ?\nA exclusão é definitiva.") )
    {
	 loadAjax("produtos/registro.php?cmd=excluir&ID=" + id + "&campo=" + field + "&file=" + file + "&dir=" + dir, "div_opcao1");
    }
}

//CONFIRMA EXCLUSÃO DE REGISTRO
function excluiRegistro(id,categoria,limite)
{
    if( confirm("Você deseja mesmo excluir esse Produto do sistema ?\nA exclusão é definitiva.") )
    {
	 loadAjax("produtos/main.php?cmd=excluir&ID=" + id + "&limite=" + limite + "&categoria=" + categoria, "div_opcao1");
    }
}

function excluiCategoria(id){
    if( confirm("Você deseja mesmo excluir esse Fabricante do sistema ?\nA exclusão é definitiva.") ) {
		 loadAjax("categorias/main.php?cmd=excluir&ID=" + id, "div_opcao2");
    }
}

function excluiOrcamento(id){
    if( confirm("Você deseja mesmo excluir esse orçamento do sistema ?\nA exclusão é definitiva.") ) {
		 loadAjax("orcamentos/main.php?cmd=excluir&ID=" + id, "div_opcao4");
    }
}

function excluiSubcategoria(id){
    if( confirm("Você deseja mesmo excluir essa Linha de produto do sistema ?\nA exclusão é definitiva.") ) {
		 loadAjax("subcategorias/main.php?cmd=excluir&ID=" + id, "div_opcao3");
    }
}

function listaLimite(limite){
 loadAjax("produtos/main.php?limite=" + limite, "div_opcao1");
}

function liberaBusca(){
	var busca = document.getElementById('busca').disabled;
	if(busca == true)
		busca = document.getElementById('busca').disabled = false;
}

function listaCategoria(grupo){
	loadAjax("categorias/main.php?grupo=" + grupo, "div_opcao2");
}

function listaSubcategoria(categoria){
	loadAjax("subcategorias/main.php?categoria=" + categoria, "div_opcao3");
}

function listaProdutos(){
	var limite = document.getElementById('limite').value;
	var grupo = document.getElementById('grupo').value;
	var categoria = document.getElementById('categoria').value;
	var subcategoria = document.getElementById('subcategoria').value;
	if(limite == "")
		limite = 0;
	if(grupo == "")
		grupo = 0;
	if(categoria == "")
		categoria = 0;
		
loadAjax("produtos/main.php?limite=" + limite + "&grupo=" + grupo + "&categoria=" + categoria + "&subcategoria=" + subcategoria, "div_opcao1");
}

function loadCat(grupo){
 jah("produtos/load_categorias.php?grupo=" + grupo, "div_categoria");
}

function loadSub(categoria){
 jah("produtos/load_sub.php?categoria=" + categoria, "div_subcategoria");
}

//AJAX SITE
function mostraProdutoVenda(id,page){
 loadAjax("load_produtos_venda.php?linha=" + id + "&page=" + page, "divProduto");
}

function mostraProduto(id,page){
 loadAjax("load_produtos.php?linha=" + id + "&page=" + page, "divProduto");
}

function mostraProduto1(id,page){
 loadAjax("load_produtos1.php?linha=" + id + "&page=" + page, "divProduto");
}

function chkSub(categoria){
 jah("produtos/load_sub.php?categoria=" + categoria, "div_subcategoria");
}

function chkCat(grupo){
 jah("produtos/load_categorias_main.php?grupo=" + grupo, "div_categoria");
}

function loadCHK(id,valor){
 if(valor == true)
 	var chk = 1;
 else
 	var chk = 0;
 
loadSet("load_chk.php?ID=" + id + "&chk=" + chk, "divCHK_" + id);
}


function loadQTD(id,qtd){ 
loadSet("load_carrinho_qtd.php?ID=" + id + "&QTD="+ qtd,"atualizaQTD");
}

function loadCARRINHO(id){
	
var valor = document.getElementById('chk_carrinho_'+id).checked

 if(valor == true)
 	var chk = 1;
 else
 	var chk = 0;
 
loadSet("load_carrinho.php?ID=" + id + "&id_caracteristica="+ document.getElementById('id_caracteristica').value +"&chk=" + chk, "divCARRINHO_" + id);
}

var qtd_antiga = new Array;

function carrega_qtd(valor,id_produto){
//função usada no carrinho para buscar a quantidade do produto daquela linha, antes de ser digitado a nova qtd
//serve para ajudar na atualização do preço
	qtd_antiga[id_produto] = valor;
}

function Select(campo){
	alert(campo);
	document.form1.campo.select();
}

//AJAX
function loadSet(url,target, func) {
    // native XMLHttpRequest object
    document.getElementById(target).innerHTML = '';
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = function() {jahDone(target, func);};
        req.open("GET", url, true);
        req.send(null);
    // IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() {jahDone(target, func);};
            req.open("GET", url, true);
            req.send();
        }
    }
}    


function jah(url,target, func) {
    // native XMLHttpRequest object
    document.getElementById(target).innerHTML = '<img src="img/loading.gif" width="11" height="11" align="absmiddle">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Aguarde, carregando...';
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = function() {jahDone(target, func);};
        req.open("GET", url, true);
        req.send(null);
    // IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() {jahDone(target, func);};
            req.open("GET", url, true);
            req.send();
        }
    }
}    


function loadAjax(url,target, func) {
    // native XMLHttpRequest object
    document.getElementById(target).innerHTML = '<div style="margin:10px;"><img src="img/loading.gif" width="11" height="11" align="absmiddle">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Aguarde, carregando...</div>';
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = function() {jahDone(target, func);};
        req.open("GET", url, true);
        req.send(null);
    // IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() {jahDone(target, func);};
            req.open("GET", url, true);
            req.send();
        }
    }
}    
function jahDone(target, func) {
    // only if req is "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            results = req.responseText;
            o = document.getElementById(target);
			o.innerHTML = results;
			execJS(o);
			if (func)
				eval(func + "();");	
		} else {
            document.getElementById(target).innerHTML="jah erro:\n" +
                req.statusText;
        }
    }
}

var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
var bMoz = (navigator.appName == 'Netscape');

function execJS(node) 
{
  var st = node.getElementsByTagName('SCRIPT');
  var strExec;
  for(var i=0;i<st.length; i++) {
	if (bSaf) {
	  strExec = st[i].innerHTML;
	}
	else if (bMoz) {
	  strExec = st[i].textContent;
	}
	else {
	  strExec = st[i].text;
	}
	try {
	  eval(strExec);
	} catch(e) {
	  alert(strExec);
	  if (window.ActiveXObject)
		  alert(e.description);
	  else
	  	  alert(e);
	}
  }
}

var Carrinho = {
	
	'validar': function(){
	
		if($v('ref_transacao') == ""){
			alert('Você precisa digitar o CPF/CNPJ! ');
			document.getElementById('ref_transacao').focus();
			return false;
			
		}

		if(document.getElementById('f').checked==true && isCpf($v('ref_transacao')) == false)
		{
				alert('Você precisa digitar um CPF válido! ');
				document.getElementById('ref_transacao').focus();
				return false;
		}

		if(document.getElementById('j').checked==true && isCnpj($v('ref_transacao')) == false)
		{
			alert('Você precisa digitar um CNPJ válido! ');
			document.getElementById('ref_transacao').focus();
			return false;
		}

		if($v('cliente_cep') == ""){
			alert('Você precisa digitar o CEP!');
			document.getElementById('cliente_cep').focus();
			return false;
			
		}

		if($v('tipo_frete') == 0){
			alert('Você precisa escolher o tipo de frete! ');
			document.getElementById('tipo_frete').focus();
			return false;
			
		}
	
	},
	
	'escolheMascara': function(tipo){
		if (tipo=="f"){
			document.getElementById('ref_transacao').value="";
			document.getElementById('labelTipo').innerHTML = 'CPF:&nbsp;';
			document.getElementById('ref_transacao').maxLength=14;
			document.getElementById('ref_transacao').focus();
		}
		if (tipo=='j'){
			document.getElementById('ref_transacao').value="";
			document.getElementById('labelTipo').innerHTML = 'CNPJ:&nbsp;';
			document.getElementById('ref_transacao').maxLength=18;
			document.getElementById('ref_transacao').focus();
		}
	}

	
}


function formataMoeda(campo)
{
	str = campo;
	
	while(str.length<4)
		str = '0' + str;
	
	while(str.search(",") != -1)
		str = str.replace(",","");
	i = 0;
	
	while(i< str.length)
	{
		if(str.substr(i,1) == ".")
			str = str.replace(".","");
		i++;
	}
	
	part1 = str.substr(0,str.length - 2);

	while(part1.search(" ") != -1)
		part1 = part1.replace(" ","");
	
	part2 = str.substr(str.length - 2,2);
	res = "";
	i = part1.length;
	sob = i % 3;
	
	if((sob != 0) && (i > 2))
		res = part1.substr(0,sob) + ".";
	else
		res = part1.substr(0,sob);
		
	j = 1;
	part1 = part1.substr(sob);
	i = 0;
	
	while(i < part1.length)
	{
		if(j == 3)
		{
			if(i + 1 == part1.length)
				res = res + part1.substr(i-2,3);
			else 
				res = res + part1.substr(i-2,3) + ".";
		}
	
	i++;
	j = j<3?j+1:1;
	
	}
	return res + "," + part2;
}


	
function formataMoedaSimples(campo)
{
	str = campo;
	
	while(str.length<4)
		str = '0' + str;
	
	while(str.search(",") != -1)
		str = str.replace(",","");
	i = 0;
	
	while(i< str.length)
	{
		if(str.substr(i,1) == ".")
			str = str.replace(".","");
		i++;
	}
	
	part1 = str.substr(0,str.length - 2);

	while(part1.search(" ") != -1)
		part1 = part1.replace(" ","");
	
	part2 = str.substr(str.length - 2,2);
	res = "";
	i = part1.length;
	sob = i % 3;
	
	if((sob != 0) && (i > 2))
		res = part1.substr(0,sob) + ".";
	else
		res = part1.substr(0,sob);
		
	j = 1;
	part1 = part1.substr(sob);
	i = 0;
	
	while(i < part1.length)
	{
		if(j == 3)
		{
			if(i + 1 == part1.length)
				res = res + part1.substr(i-2,3);
			else 
				res = res + part1.substr(i-2,3) + ".";
		}
	
	i++;
	j = j<3?j+1:1;
	
	}
	return res + "," + part2;
}

function atualizaTotal()
{
	var total=0;
	for(var i=1;document.getElementById('item_valor_' + i ) != null; i++)
	{
		subtotal = (document.getElementById('item_valor_' + i ).value.replace(',','.'))*Math.round((document.getElementById('item_quant_' + i ).value));
		subtotal = Math.round(subtotal*100).toString();

		document.getElementById('valor_total_' + i ).innerHTML = 'R$ ' + formataMoeda(subtotal.substring(0,subtotal.length-2) + ',' + subtotal.substring(subtotal.length-2));
 
		total = total + (document.getElementById('item_valor_' + i ).value.replace(',','.'))*Math.round((document.getElementById('item_quant_' + i ).value));
	}
	
	total = Math.round(total*100);
	total = total.toString();

	document.getElementById('valor_final').innerHTML = 'R$ ' + formataMoeda(total.substring(0,total.length-2) + ',' + total.substring(total.length-2));
}