function replaceVars(htmlReplace) {
	var htmlTMP = htmlReplace;
	htmlTMP = replaceSubstring(htmlTMP,"{tplUrlFilesRoot}",tplUrlFilesRoot);
	htmlTMP = replaceSubstring(htmlTMP,"%7BtplUrlFilesRoot%7D",tplUrlFilesRoot);
	htmlTMP = replaceSubstring(htmlTMP,"{IMG_DIR}",IMG_DIR);
	return htmlTMP;
}	
	
var htmlTemplate = new Array();
function callOnAppend (){
	monta__BNRTPL__PRODUTOS();
	monta__BNRTPL__FORMCONTATO();
}

function contaOcorrencias(frase,sub) {
	var frase = frase+'';
	var sub = sub+'';
	var cont = 0;
	
	for(i = 0; i < (frase.length - sub.length + 1); i++){
		var res = frase.substring(i, (i + sub.length));
		if(res+''==sub+''){
			cont++;
		}
	}

	return cont;
}

function onerrorimg(ob) {
	var strSrc = $(ob).attr('src')+'';
	var totalOcorr = contaOcorrencias(strSrc,'http');
	var pos = strSrc.indexOf('http',totalOcorr);
	if(pos>1) {
		var srcNew = strSrc.substring(pos,strSrc.length);
		$(ob).attr('src',srcNew);
		$(ob).removeAttr('onerror');
		alert('no')
		$(ob).attr('onerror','$(this).remove()');
	}
}

var append = function(parent, child, onAppend) {
  //parent.appendChild(child);
  
  $(parent).append(child);
  $('img').each(function () {
	var img = $(this);
	$(this).attr('onerror','onerrorimg(this)');
  });
  
        // $('img').error(function () {
            // // notify the user that the image could not be loaded
			// alert('')
			// var strSrc = $(this).attr('src')+'';
			
			// var frase = "Programar em Java só é melhor que programar em Java e Java é bom demais";
			// var sub = "Java"; // ocorrências de "Java"
			// var cont = 0;
			// for(i = 0; i < (frase.length() - sub.length() + 1); i++){
				// var res = frase.substring(i, (i + sub.length()));
				// if(res.equals(sub)){
					// cont++;
				// }
			// }
    
			// alert("A frase contem " + cont + " ocorrencias de " + sub);

		// }).attr('src', '-');
		
  
  var htmlOriginal = $(parent).html();
  var htmlReplaced = replaceVars(htmlOriginal);
  $(parent).html(htmlReplaced);
  
  if (onAppend) onAppend(child);
  callOnAppend();
}

var after = function(parent, child, onAppend) {
  //parent.appendChild(child);
  $(parent).after(child);
  if (onAppend) onAppend(child);
  callOnAppend();
}


function getFotosHTML() {
	var arrImagesDIR = globals_arrDadosDB['arrImagesDIR'];
	var htmlPagFotos = '';
	var rnd = (new Date()).getTime()+'';
	
	if(arrImagesDIR['qtd_group']) {
		var Dsc_ConteudoFotos = '<div class="fotosdir_container">';
		for(idx in arrImagesDIR['images_group']) {
			var row = arrImagesDIR['images_group'][idx];
				
			var nm0 = row[0]['nm'];
			var path0 = row[0]['path'];
			var nm1 = row[1]['nm'];
			var path1 = row[1]['path'];
			
			
			Dsc_ConteudoFotos+='<div class="item">';
			Dsc_ConteudoFotos+='<a href="'+path1+'" class="highslide" title=" &nbsp; ">';
			Dsc_ConteudoFotos+='	<img src="'+path0+'" alt="&nbsp;" title=" &nbsp; " />';
			Dsc_ConteudoFotos+='</a>';
			Dsc_ConteudoFotos+='</div>';
			// Dsc_ConteudoFotos+='<div class="highslide-heading">';
			// Dsc_ConteudoFotos+='	{clsProduto->GetNome()}';
			// Dsc_ConteudoFotos+='</div>';
			
		}
		Dsc_ConteudoFotos+='</div>';
		htmlPagFotos='<div id="painel_'+rnd+'" class="painel painel_'+rnd+' fotosdir">'+Dsc_ConteudoFotos+'</div>';
		
	}
	return htmlPagFotos;
}

function getFabricanteUrlImageByID(id,cs) {
	
	var cs = !cs?'gnd':cs;
	var urlImage = '';
	var row = filterArray(globals_arrDadosDB['fabricantes'],id+'','idFabricante','=');
		if(row[0]) {
			$idAUX = str_repeat('0',9-strlen(id))+id;
			try{
				$urlFOLDER = ARQ_URL_FABRICANTES + "/"+$idAUX+"/"+$idAUX+"";
			} catch(e){
				$urlFOLDER = $idAUX+"/"+$idAUX+"";
			}
			
			var Dsc_ImagemPrincipalExtensao = row[0]['Dsc_ImagemPrincipalExtensao'];
			switch(cs+'') {
				case 'min' :
						urlImage = $urlFOLDER + '_0.' + Dsc_ImagemPrincipalExtensao;
					break;
				case 'peq' :
						urlImage = $urlFOLDER + '_1.' + Dsc_ImagemPrincipalExtensao;
					break;
				case 'gnd' :
						urlImage = $urlFOLDER + '_2.' + Dsc_ImagemPrincipalExtensao;
					break;
			}
			
		}
	return urlImage;
	
}

function loadChat() {
	$('.__BNRTPL_LIVECHAT').each(function(){
		eval('var objParam = '+$(this).attr('param')+';');
		var label = 'Atendimento';
		if(objParam) {
			label = objParam.label?objParam.label:label;
		}
		var invitee = MSNINVITEE;
		
		if(invitee+''!='') {
			$(this).removeClass('__BNRTPL_LIVECHAT');
			
			var html ='';
			html = '<a target="_blank" href="http://settings.messenger.live.com/Conversation/IMMe.aspx?invitee='+invitee+'@apps.messenger.live.com&mkt=pt-br"><img style="border-style: none;" src="http://messenger.services.live.com/users/'+invitee+'@apps.messenger.live.com/presenceimage?mkt=pt-br" width="16" height="16" />'+label+'</a>';
			$(this).append(html);
		} else {
			//$(this).remove();
		}
	});
}


$(function(){
	var objTPage = $('#tpl_page');
	var attrID = $(objTPage).attr('id')+'';
	var html = $(objTPage).text();
	
	
	
	
	var jTemplate = $(objTPage);
	try {
		var jElement = jTemplate.template(
								eval( "(" + jValues + ")" )
							);
		
		$(objTPage).before(jElement);
		$(objTPage).remove();
	} catch(e) {
		
	}
	

	
	
	
	$('.box_tplVARS').each(function(){
		$(this).find('.tpl').each(function(){
			var attrID = $(this).attr('id')+'';
			var html = $(this).text();

			
			
			var jTemplate = $(this);
			var boOk = $('.'+attrID).size();
			//if(jTemplate.is('div')) {
			if(boOk) {
				//alert(attrID + ' = ' + html)
				var jElement = jTemplate.template(
										eval( "(" + jValues + ")" )
									);
				
				var className = attrID;
				
				$('.'+className).before(jElement);
				$('.'+className).remove();
			}
			
			//htmlTemplate[attrID] = html;
		});
		
		$('.box_tplVARS').remove();
		

	});
	
	
		
	$('.logo a').focus(function(){
		$(this).blur();
	});
	

	$('.__BNRTPL__INDICACAO').each(function(){
			var strHTML = '';
			strHTML+='<div class="boxindicamail">';
			strHTML+='<form id="formindicacaoemail">';
			strHTML+='	<div class="boxindicamailcontent">';
			strHTML+='		<h4>Enviar e-mail para amigo</h4>';
			strHTML+='		<div class="corpo">';
			strHTML+='		<span class="msg"></span>';
			strHTML+='			<div class="item">';
			strHTML+='				<label>Para:</label>';
			strHTML+='				<span class="comment">(separe os e-mails por "," ou ";")</span>';
			strHTML+='				<textarea id="tx_email_para" name="tx_email_para"><'+'/'+'textarea>';
			strHTML+='			</div>';
			strHTML+='			<div class="item">';
			strHTML+='				<label>De:</label>';
			strHTML+='				<span class="comment">(endereço de e-mail)</span>';
			strHTML+='				<input type="text" class="input-text" value="" id="tx_email_de" name="tx_email_de" maxlength="255" />';
			strHTML+='			</div>';
			strHTML+='			<div class="item">';
			strHTML+='				<label>Nota:</label>';
			strHTML+='				<span class="comment">(opcional)</span>';
			strHTML+='				<textarea id="tx_email_nota" name="tx_email_nota"><'+'/'+'textarea>';
			strHTML+='				<small>Máximo de 255 caracteres</small>';
			strHTML+='			</div>';
			strHTML+='			<div class="item">';
			strHTML+='				<label>&nbsp;</label>';
			strHTML+='				<input type="submit" class="input-btn bt_enviar" value="Enviar" />';
			strHTML+='			</div>';
			strHTML+='		</div>';
			strHTML+='	</div>';
			strHTML+='</form>';
			strHTML+='</div>';
			
			$(this).append(strHTML);
			$(this).removeClass('__BNRTPL__INDICACAO');
			
			$('#formindicacaoemail').submit(function(){
					var objForm  = $(this);
					var objMsg = $(objForm).find('.msg:eq(0)');
					
					var obj_tx_email_para  = $('#tx_email_para');
					var obj_tx_email_de = $('#tx_email_de');
					var obj_tx_email_nota  = $('#tx_email_nota');
					
					var val1 = $(obj_tx_email_para).val()+'';
					var val2 = $(obj_tx_email_de).val()+'';
					var val3 = $(obj_tx_email_nota).val()+'';
					
					$(obj_tx_email_para).removeClass('erro');
					$(obj_tx_email_de).removeClass('erro');
					$(obj_tx_email_nota).removeClass('erro');
					$(objMsg).html('');
					
					if(val1+''=='') boOK = false;
					if(val2+''=='') boOK = false;
					
										
					var boOK = true;
					var emailFilter=/^.+@.+\..{2,}$/;
					var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/
					
					var valAux = replaceSubstring(val1,';',',');
					var arrVal = valAux.split(',');
					for(i in arrVal) {
						var v = arrVal[i];
						if(v+''=='' || !(emailFilter.test(v)) || v.match(illegalChars)){
							if(!$(obj_tx_email_para).is('.erro')) $(obj_tx_email_para).addClass('erro');
							boOK = false;
						}
					}
					
					var valAux = val2;
					//valAux = replaceSubstring(valAux,';','');
					//valAux = replaceSubstring(valAux,',','');
					var v = valAux;
					if(v+''=='' || !(emailFilter.test(v)) || v.match(illegalChars)){
						$(obj_tx_email_de).addClass('erro');
						boOK = false;
					}
					
					if(!boOK) { 
						$(objMsg).html('Digite endereços de e-mail válidos.');
						return false;
					}
					
					if(val3.length>255) {
						$(obj_tx_email_nota).addClass('erro');
						$(objMsg).html('Texto digitado excede 255 caracteres');
						return false;
					}
					
					
					var url = baseUrl + 'ajax.common/indicacao/';
					setAsync(true);
					var post = $(objForm).serialize();
					$.post(url,post,function(resp){
						if(resp+''=='ok') {
							jAlert('Obrigado pela indicação.<br />Enviado com sucesso!');
						} else {
							jAlert('Não foi possível enviar!');
						}
					});
					setAsync(false);
					
				return false;
			});
	});	
	
	$('.__BNRTPL__NAVIGATION').each(function(){
			var strHTML = display_secoes_sidebar(globals_arrDadosDB['secoes']);
			$(this).append(strHTML);
			$(this).removeClass('__BNRTPL__NAVIGATION');
	});	


	
	

	//populaCombo(obj_sel_secoes,globals_arrDadosDB['secoes'],'idSecao','Nom_Secao');
	
	
	if(!$('#column_right + .sidebar:not(:has(*))').size()) {
		//$('#column_right').remove();
	}
	
	

	
	$('.__BNRTPL__SECOES').each(function(){
		$(this).removeClass('__BNRTPL__SECOES');
		if($(this).is('[class*=mcdropdown]')) {
			var obj_searchFilter = $('.mcdropdown');
			//populaCombo(obj_sel_secoes,globals_arrDadosDB['secoes'],'idSecao','Nom_Secao');
			dropDownCategorias(this);
		} else if($(this).is('[class*=menubar]')) {
			var strHTML = display_secoes_sidebar(globals_arrDadosDB['secoes']);
			$(this).append(strHTML);
			// var objDIV = document.createElement('div');
			// var objUL = document.createElement('ul');
			
			// $(objUL).attr('id','manubar');
			
			// $(objDIV).append(strHTML);
			// $(objUL).append($(objDIV).find('ul:eq(0)').html());
			
			// $(this).append(objUL);
	
			//loadMenuBar(this,globals_arrDadosDB['secoes']);
		} else {
			var strHTML = display_secoes_sidebar(globals_arrDadosDB['secoes']);
			$(this).append(strHTML);
		}
	});
			function pageselectCallback(page_index, jq){
                // Get number of elements per pagionation page from form
                // var items_per_page = $('#items_per_page').val();
                // var max_elem = Math.min((page_index+1) * items_per_page, members.length);
                // var newcontent = '';

                
                // Prevent click eventpropagation
                return false;
            }

	
	
	monta__BNRTPL__PRODUTOS ();
	monta__BNRTPL__VIDEOS ();
	
	$('.__BNRTPL__FABRICANTE_IMAGE').each(function(){
		$(this).removeClass('__BNRTPL__FABRICANTE_IMAGE');
		eval('var objParam = '+$(this).attr('param')+';');
		if(objParam.id) {
			var row = filterArray(globals_arrDadosDB['fabricantes'],objParam.id+'','idFabricante','=');
			if(row[0]) {
				var idFabricante = row[0]['idFabricante'];
				var Nom_Fabricante = row[0]['Nom_Fabricante'];
				var urlImage = getFabricanteUrlImageByID(idFabricante,'peq');
				
				var html = '<a href="" param="prod__fabricante" rel="{id:'+idFabricante+',nome:\''+Nom_Fabricante+'\'}" ><img src="'+urlImage+'" onError=\'$(this).after("'+Nom_Fabricante+'");$(this).remove();\'   /></a>';
				//alert(Nom_Fabricante)
				$(this).append(html);
			}
		}
	});
	
	//<a href="" param="prod__fabricante" rel="{id:<?php echo $this->idfabricante;?>,nome:'<?php echo $this->nomefabricante;?>'}" ><img src="{clsProduto->GetFotoFabricante('gnd')}" title="<?php echo $this->nomefabricante;?>" onError='$(this).after("<?php echo $this->nomefabricante;?>");$(this).remove();' /></a>

	
	$('.__BNRTPL__FABRICANTES').each(function(){
		$(this).removeClass('__BNRTPL__FABRICANTES');
		eval('var objParam = '+$(this).attr('param')+';');
		var url = '';
		if(objParam) {
			url = objParam.url?objParam.url:'';
		}
		url = url?url:'produtos/lista/idfabricante/{id}/nomefabricante/{nome}';
		
		if($(this).is('select')) {
			populaCombo(this,globals_arrDadosDB['fabricantes'],'idFabricante','Nom_Fabricante');
			$(this).bind('change',function(){
				var id = $(this).val();
				if(id+''!='') {
					txtOption = $($(this).find('option').get(this.selectedIndex)).html();
					document.location.href = 'produtos/lista/idfabricante/'+id+'/nomefabricante/'+txtOption;
					//document.location.href = 'produtos/lista/nomefabricante/'+txtOption;
				}
			});
		} else if($(this).is('ul') || $(this).is('div')) {
			var html ='';
			for(i in globals_arrDadosDB['fabricantes']) {
				var total = globals_arrDadosDB['fabricantes'][i]['Total']?' <span class="tot">(' + globals_arrDadosDB['fabricantes'][i]['Total'] + ')</span>':'';
				var idFabricante = globals_arrDadosDB['fabricantes'][i]['idFabricante'];
				var Nom_Fabricante = globals_arrDadosDB['fabricantes'][i]['Nom_Fabricante'];
				
				var urlAux = url;
				var urlAux = replaceSubstring(urlAux,'{id}',idFabricante);
				var urlAux = replaceSubstring(urlAux,'{nome}',escape(Nom_Fabricante));
				
				
				html +='<li title="'+Nom_Fabricante+'"><a href="'+urlAux+'">'+ Nom_Fabricante + total +'</a></li>';
			}
			
			if($(this).is('div')) {
				html = '<ul>' + html + '</ul>';
			}

			$(this).append(html);
		}
	});
	
	$('.__BNRTPL__PAGINAS').each(function(){
		var obj = $(this);
		$(obj).removeClass('__BNRTPL__PAGINAS');
		var html = ''; 
		var objArr = globals_arrDadosDB['paginas'];
		var objUL = $(obj).is('ul')?obj:$(obj).find('ul').get(0);
		if(objUL) {
			var tree_paginas = new Tree(objArr,"idPagina,Nom_Pagina,idPaginaPai");
			tree_paginas.urlBase = baseUrlModule +'paginas/detalhe/';
			//tree_paginas.url = baseUrlModule +'paginas/detalhe/idpagina/[IDFILHO]';
			//tree_paginas.url = '';
			tree_paginas.getTree();
			var htmlMenuPag = tree_paginas.getHTML();
			$(objUL).append(htmlMenuPag); 
			
			/*
			for(i in objArr) {
				var idPagina = objArr[i]['idPagina'];
				var Nom_Pagina = objArr[i]['Nom_Pagina'];
				var url = baseUrlModule +'paginas/detalhe/idpagina/'+idPagina;
				html+='<li><a href="'+url +'">'+Nom_Pagina+'</a></li>'
			}
			$(objUL).append(html); 
			*/
			
		} else {
			var objDiv = $(obj).find('div').get(0);
			var objDivPgHome = $($(obj).find('div').get(0)).find('a[href=""]:eq(0)').get(0);
			var objClone = $(objDiv).clone();
			$(objClone).removeAttr('param');
			$(objClone).find('a:eq(0)').removeAttr('param');
			var htmlHome = '';
			var arrSubPaginas = new Array();
			for(i in objArr) {
				var idPagina = objArr[i]['idPagina'];
				var idPaginaPai = objArr[i]['idPaginaPai'];
				if(!idPaginaPai) {
					var Nom_Pagina = objArr[i]['Nom_Pagina'];
					var url = baseUrlModule +'paginas/detalhe/idpagina/'+idPagina;
					$(objClone).find('a:eq(0)').attr('href',url);
					$(objClone).find('a:eq(0)').html(Nom_Pagina);
					var html = $(objClone).outerHTML();
					if(objDivPgHome) {
						htmlHome +=html;
					} else {
						$(obj).append(html);
					}
				} else {
					arrSubPaginas['id_'+idPagina] = arrSubPaginas['id_'+idPagina]?arrSubPaginas['id_'+idPagina]:new Array();
					arrSubPaginas['id_'+idPaginaPai] = arrSubPaginas['id_'+idPaginaPai]?arrSubPaginas['id_'+idPaginaPai]:new Array();
					arrSubPaginas['id_'+idPagina].push(objArr[i]);
					arrSubPaginas['id_'+idPaginaPai].push(objArr[i]);
				}
			}
			if(htmlHome)$(objDivPgHome).after(htmlHome);
			
			var objPAG = $('#Paginas');
			if(objPAG) {
				var rqstIdPg = requestJSON['idpagina']+'';
				if(rqstIdPg) {
					var row = arrSubPaginas['id_'+rqstIdPg];
					if(row) {
						$(objPAG).prepend('<div class="box_menusubpag corner"><div class="box_menusubpag_container"></div></div>')
						var idPaginaPai = row[0]['idPaginaPai'];
						var rowPai = arrSubPaginas['id_'+idPaginaPai];
						var tree_paginas = new Tree(objArr,"idPagina,Nom_Pagina,idPaginaPai");
						tree_paginas.urlBase = baseUrlModule +'paginas/detalhe/';
						//tree_paginas.url = baseUrlModule +'paginas/detalhe/idpagina/[IDFILHO]';
						//tree_paginas.url = '';
						tree_paginas.getTree();
						var htmlMenuPag = tree_paginas.getHTML();
						$('#Paginas .box_menusubpag_container').append(htmlMenuPag);
						/*
						for(iR=0;iR<row.length;iR++) {
							var row2 = row[iR];
							var idPagina = row2['idPagina'];
							var Nom_Pagina = row2['Nom_Pagina'];
							var url = baseUrlModule +'paginas/detalhe/idpagina/'+idPagina;
							var htmlPag = '<a href="'+url+'">'+Nom_Pagina+'</a>';
							$('#Paginas').prepend(htmlPag);
						}
						*/
					}
				}
			}
			
		}
	});
	

	
	// $('.__BNRTPL__FOTOS').each(function(){
		// var htmlPagFotos = getFotosHTML();
		// $(this).append(htmlPagFotos);
		// $(this).removeClass('__BNRTPL__FOTOS');
	// });
	
	$('.__BNRTPL__MENUPAGINAS').each(function(){
		$(this).removeClass('__BNRTPL__MENUPAGINAS');
		var arrPaginas = globals_arrDadosDB['paginas'];
		var htmlMenuPagina = '';
		for(idx in arrPaginas) {
			var row = arrPaginas[idx];
			var idPagina = row['idPagina'];
			var Nom_Pagina = row['Nom_Pagina'];
			var idPaginaPai = row['idPaginaPai'];
			
			//htmlMenuPagina+='<li><a href="#pag_'+idPagina+'">'+Nom_Pagina+'</a></li>';
			htmlMenuPagina+='<li><a href="paginas/index/idpagina/'+idPagina+'" rel="#pag_'+idPagina+'">'+Nom_Pagina+'</a></li>';
		}
		var arrImagesDIR = globals_arrDadosDB['arrImagesDIR'];
		var htmlPagFotos = getFotosHTML();
		
		
		var count = 0;
		if(arrImagesDIR['qtd_group']) {
			htmlMenuPagina+='<li><a href="fotos/" rel="#fotosdir">Fotos</a></li>';
		}
		
		
		
		
		if(htmlMenuPagina+''!='') { 
			var objUL = $(this).find('ul').get(0);
			if($(objUL).is('ul')) {
				$(objUL).append(htmlMenuPagina); 
			} else {
				$(this).append('<ul>'+htmlMenuPagina+'</ul>'); 
			}
			
			
			//append($('.__BNRTPL__MENUPAGINAS'),'<ul>'+htmlMenuPagina+'</ul>');
		}
		
		
		
		var htmlPag = '';
		for(idx in arrPaginas) {
			var row = arrPaginas[idx];
			var idPagina = row['idPagina'];
			var Nom_Pagina = row['Nom_Pagina'];
			var idPaginaPai = row['idPaginaPai'];
			var Dsc_Conteudo = row['Dsc_Conteudo'];
			
			htmlPag+='<div id="painel_'+count+'" class="painel painel_'+count+' pag_'+idPagina+'">'+Dsc_Conteudo+'</div>';
			
			count++;
		}
		htmlPag+=htmlPagFotos;
		
		
		if($('#paginas').is('div')) {
			append($('#paginas'),htmlPag);
			painelHideAll();
			$('a').click(function(){
				var cs = $(this).attr('rel')+'';
				if(!cs) {
					cs = $(this).attr('href')+'';
					var arrC = cs.split('/');
					cs = arrC[arrC.length-1];
				}
				if(cs.indexOf('#')!=-1) {
					$('.painel').hide();
					painelHideAll();
					
					// var arrC = cs.split('/');
					// cs = arrC[arrC.length-1];
					var style = cs.replace('#','');
					
					//$('.'+style).animate({opacity:0.1},1000);
					//setTimeout("showTimeout('"+style+"')",0);
					//$('.'+style).animate({opacity:1},1000);
					//$('.'+style).animate({opacity:0},1);
					$('.'+style).show();
					$('.'+style).animate({opacity:1},1000);
					
					$('.painel').each(function(){
						if($(this).is(':visible')) {
							var idVisible = $(this).attr('id')+'';
							//$('.'+idVisible).animate({opacity:0},1000);
						}
					});
					
					
					return false;
					
				}
			});
		}
		
		var objA = $(this).find('a').get(0);
		$(objA).click();
		$(this).removeClass('__BNRTPL__MENUPAGINAS');
	});
	
		function painelHideAll() {
			$('.painel').each(function(){
				$(this).animate({opacity:0},1);
			});
		}
	
	
	
	
	
	
});

	function sizeof(arg) { var total=0;for(i in arg){total++;} return total; }
	function array(arg) { return new Array(); }
	function is_array(arg) { return (typeof arg == 'array' || typeof arg == 'object' ||  arg.constructor == Array); }
	function is_object(arg) { return ( typeof arg == 'object' ); }

	function isFunction(arg) { return (typeof arg == 'function'); }
	function unset(arg) { arg = null; }
	function str_repeat(str, i) { if (isNaN(i) || i <= 0) return ""; return str + str_repeat(str, i-1); }
	function strlen(arg) { var arg = arg+''; return arg.length; }
	function isset(arg) { return arg?true:false; }
	function explode(str,arg) { var arg = arg+''; return arg.split(str); }
	function isVisible(arg) { return ( !$(arg).is(':visible') || $(arg).is(':hidden') || $(arg).parents(':hidden').length); }
	function strtoupper(arg) { var arg = arg+''; return (arg.toUpperCase()); }
	
	function number_format(number,decimals,dec_point,thousands_sep){var n=number,prec=decimals;n=!isFinite(+n)?0:+n;prec=!isFinite(+prec)?0:Math.abs(prec);var sep=(typeof thousands_sep=="undefined")?',':thousands_sep;var dec=(typeof dec_point=="undefined")?'.':dec_point;var s=(prec>0)?n.toFixed(prec):Math.round(n).toFixed(prec);var abs=Math.abs(n).toFixed(prec);var _,i;if(abs>=1000){_=abs.split(/\D/);i=_[0].length%3||3;_[0]=s.slice(0,i+(n<0))+_[0].slice(i).replace(/(\d{3})/g,sep+'$1');s=_.join(dec);}else{s=s.replace('.',dec);}return s;}
	function strip_tags(str,allowed_tags){var key='',allowed=false;var matches=[];var allowed_array=[];var allowed_tag='';var i=0;var k='';var html='';var replacer=function(search,replace,str){return str.split(search).join(replace);};if(allowed_tags){allowed_array=allowed_tags.match(/([a-zA-Z]+)/gi);}str+='';matches=str.match(/(<\/?[\S][^>]*>)/gi);for(key in matches){if(isNaN(key)){continue;}html=matches[key].toString();allowed=false;for(k in allowed_array){allowed_tag=allowed_array[k];i=-1;if(i!=0){i=html.toLowerCase().indexOf('<'+allowed_tag+'>');}if(i!=0){i=html.toLowerCase().indexOf('<'+allowed_tag+' ');}if(i!=0){i=html.toLowerCase().indexOf('</'+allowed_tag);}if(i==0){allowed=true;break;}}if(!allowed){str=replacer(html,"",str);}}return str;}
	
	function get_html_translation_table(table,quote_style){var entities={},histogram={},decimal=0,symbol='';var constMappingTable={},constMappingQuoteStyle={};var useTable={},useQuoteStyle={};useTable=(table?table.toUpperCase():'HTML_SPECIALCHARS');useQuoteStyle=(quote_style?quote_style.toUpperCase():'ENT_COMPAT');constMappingTable[0]='HTML_SPECIALCHARS';constMappingTable[1]='HTML_ENTITIES';constMappingQuoteStyle[0]='ENT_NOQUOTES';constMappingQuoteStyle[2]='ENT_COMPAT';constMappingQuoteStyle[3]='ENT_QUOTES';if(!isNaN(useTable)){useTable=constMappingTable[useTable];}if(!isNaN(useQuoteStyle)){useQuoteStyle=constMappingQuoteStyle[useQuoteStyle];}if(useTable=='HTML_SPECIALCHARS'){entities['38']='&amp;';if(useQuoteStyle!='ENT_NOQUOTES'){entities['34']='&quot;';}if(useQuoteStyle=='ENT_QUOTES'){entities['39']='&#039;';}entities['60']='&lt;';entities['62']='&gt;';}else if(useTable=='HTML_ENTITIES'){entities['38']='&amp;';if(useQuoteStyle!='ENT_NOQUOTES'){entities['34']='&quot;';}if(useQuoteStyle=='ENT_QUOTES'){entities['39']='&#039;';}entities['60']='&lt;';entities['62']='&gt;';entities['160']='&nbsp;';entities['161']='&iexcl;';entities['162']='&cent;';entities['163']='&pound;';entities['164']='&curren;';entities['165']='&yen;';entities['166']='&brvbar;';entities['167']='&sect;';entities['168']='&uml;';entities['169']='&copy;';entities['170']='&ordf;';entities['171']='&laquo;';entities['172']='&not;';entities['173']='&shy;';entities['174']='&reg;';entities['175']='&macr;';entities['176']='&deg;';entities['177']='&plusmn;';entities['178']='&sup2;';entities['179']='&sup3;';entities['180']='&acute;';entities['181']='&micro;';entities['182']='&para;';entities['183']='&middot;';entities['184']='&cedil;';entities['185']='&sup1;';entities['186']='&ordm;';entities['187']='&raquo;';entities['188']='&frac14;';entities['189']='&frac12;';entities['190']='&frac34;';entities['191']='&iquest;';entities['192']='&Agrave;';entities['193']='&Aacute;';entities['194']='&Acirc;';entities['195']='&Atilde;';entities['196']='&Auml;';entities['197']='&Aring;';entities['198']='&AElig;';entities['199']='&Ccedil;';entities['200']='&Egrave;';entities['201']='&Eacute;';entities['202']='&Ecirc;';entities['203']='&Euml;';entities['204']='&Igrave;';entities['205']='&Iacute;';entities['206']='&Icirc;';entities['207']='&Iuml;';entities['208']='&ETH;';entities['209']='&Ntilde;';entities['210']='&Ograve;';entities['211']='&Oacute;';entities['212']='&Ocirc;';entities['213']='&Otilde;';entities['214']='&Ouml;';entities['215']='&times;';entities['216']='&Oslash;';entities['217']='&Ugrave;';entities['218']='&Uacute;';entities['219']='&Ucirc;';entities['220']='&Uuml;';entities['221']='&Yacute;';entities['222']='&THORN;';entities['223']='&szlig;';entities['224']='&agrave;';entities['225']='&aacute;';entities['226']='&acirc;';entities['227']='&atilde;';entities['228']='&auml;';entities['229']='&aring;';entities['230']='&aelig;';entities['231']='&ccedil;';entities['232']='&egrave;';entities['233']='&eacute;';entities['234']='&ecirc;';entities['235']='&euml;';entities['236']='&igrave;';entities['237']='&iacute;';entities['238']='&icirc;';entities['239']='&iuml;';entities['240']='&eth;';entities['241']='&ntilde;';entities['242']='&ograve;';entities['243']='&oacute;';entities['244']='&ocirc;';entities['245']='&otilde;';entities['246']='&ouml;';entities['247']='&divide;';entities['248']='&oslash;';entities['249']='&ugrave;';entities['250']='&uacute;';entities['251']='&ucirc;';entities['252']='&uuml;';entities['253']='&yacute;';entities['254']='&thorn;';entities['255']='&yuml;';}else{throw Error("Table: "+useTable+' not supported');return false;}for(decimal in entities){symbol=String.fromCharCode(decimal);histogram[symbol]=entities[decimal];}return histogram;}
	function htmlspecialchars(string,quote_style){ if(string==null) return '';var histogram={},symbol='',tmp_str='',entity='';tmp_str=string.toString();if(false===(histogram=get_html_translation_table('HTML_SPECIALCHARS',quote_style))){return false;}for(symbol in histogram){entity=histogram[symbol];tmp_str=tmp_str.split(symbol).join(entity);}return tmp_str;}
	
	function trataString(arg) { return replaceSubstring(arg,"\n",' ') }
	function ceil(value){return Math.ceil(value);}
	
	
	var AbstractVideo = function() {
		this.id = '';
		this.nome;
		this.foto = new Array();
		this.chamada;
		this.resumo;
		this.descricao;
		this.urlFoto;
		this.urlVideo;
		this.link_detalhe;
		
		this.arrDados = new Array();
		this.pub_arrParams = new Array();
		this.__construct = function() {
			this.foto['min'] = '';
			this.foto['pqn'] = '';
			this.foto['gnd'] = '';
			this.foto['big'] = '';
			
			this.pub_arrParams['bo_ativo'] = true;
			this.pub_arrParams['bo_imagemprincipal'] = false; 
		}
		
		this.setID = function($id) { this.id = $id; }
		this.GetID = function() { return this.id; }
			
		this.setNome = function($nome) { var $nome = !$nome?'':$nome; this.nome = $nome; }
		this.GetNome = function () { return this.nome; }

		this.setLinkDetalhe = function () { this.link_detalhe = 'videos/detalhe/idvideo/'+this.GetID(); }
		this.GetLinkDetalhe = function () { return this.link_detalhe; }
		
		
		
		this.setFoto = function () {
			this.pub_arrParams['bo_imagemprincipal'] = false; 
			if(this.arrDados['Dsc_ImagemPrincipalExtensao']+''!='') {
				this.pub_arrParams['bo_imagemprincipal'] = true; 
				
				$idAUX = str_repeat('0',9-strlen(this.id))+this.id;
				$urlFOLDER = ARQ_URL_PRODUTOS + "/"+$idAUX+"/"+$idAUX+"";
				
				this.foto['min'] = $urlFOLDER + '_0.jpg';
				this.foto['pqn'] = $urlFOLDER + '_1.jpg';
				this.foto['gnd'] = $urlFOLDER + '_2.jpg';
				this.foto['big'] = $urlFOLDER + '_3.jpg';
			}
		}
		
		this.GetFoto = function ($cs) {
			var $cs = !$cs?'':$cs;
			return this.foto[$cs];
		}
		
		this.setChamada = function ($chamada) { var $chamada = !$chamada?'':$chamada; this.chamada = $chamada; }
		this.GetChamada = function () { return this.chamada; }
		
		this.setDescricao = function ($descricao) { var $descricao = !$descricao?'':$descricao; this.descricao = $descricao; }
		this.GetDescricao = function () { return this.descricao; }
		
		this.setUrlVideo = function ($url) { var $url = !$url?'':$url; this.urlVideo = $url; }
		this.GetUrlVideo = function () { return this.urlVideo; }
		
		this.setUrlFoto = function ($url) { var $url = !$url?'':$url; this.urlFoto = $url; }
		this.GetUrlFoto = function () { return this.urlFoto; }
		
		this.setResumo = function ($resumo) { 
			var $resumo = !$resumo?'':$resumo;
			$resumo = $resumo+''=='' || $resumo+''=='null'?'':$resumo;
			if($resumo+''=='') {
				$resumo = this.arrDados['Dsc_Descricao']+'';
				$resumo = strlen($resumo)>500?substr(strip_tags($resumo),0,500)+'...':$resumo;
			}
			this.resumo = $resumo=='null'?'':$resumo;
			this.resumo = trataString(this.resumo);
		}
		this.GetResumo = function () { return this.resumo; }
		
		this.setFromArray = function ($arr) {
			this.arrDados = $arr;
			this.setID(this.arrDados['idVideo']);
			// this.setFoto();
			this.setNome(this.arrDados['Nom_Video']);
			this.setChamada(this.arrDados['Dsc_Chamada']);
			this.setResumo(this.arrDados['Dsc_Resumo']);
			this.setDescricao(this.arrDados['Dsc_Descricao']);
			this.setUrlFoto(this.arrDados['Dsc_UrlFoto']);
			this.setUrlVideo(this.arrDados['Dsc_UrlVideo']);
			this.setLinkDetalhe();
		}
		this.GetDados = function () { this.arrDados = $arr; }
		
		this.__construct();
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	var AbstractProduto = function() {
		this.id = '';
		this.nome;
		this.preco;
		this.ind_inativo;
		this.preco_min;
		this.preco_max;
		this.preco_pessoa;
		this.total_dominios;
		this.mode;
		this.foto = new Array();
		this.fotoFabricante = new Array();
		this.descricao;
		this.id_fabricante;
		this.nome_fabricante;
		this.disponibilidade;

		this.arrDados = new Array();

		this.pub_arrParams = new Array();

		this.__construct = function() {
			this.foto['min'] = '';
			this.foto['pqn'] = '';
			this.foto['gnd'] = '';
			this.foto['big'] = '';			
			
			this.fotoFabricante['min'] = '';
			this.fotoFabricante['pqn'] = '';
			this.fotoFabricante['gnd'] = '';
			
			this.pub_arrParams['bo_ativo'] = true;
			this.pub_arrParams['bo_comprar'] = true; 
			this.pub_arrParams['bo_imagemprincipal'] = false; 
		}
		
		this.setMode = function($mode){
			this.mode = !$mode?'':$mode;
		}

		this.setID = function($id) { this.id = $id; }
		this.GetID = function() { return this.id; }
		
		this.setIdFabricante = function ($id) { this.id_fabricante = $id; }
		this.GetIdFabricante = function () { var $idfabricante = !this.id_fabricante?'':this.id_fabricante; return $idfabricante; }
		
		this.setNomeFabricante = function ($nome) { this.nome_fabricante = htmlspecialchars($nome); }
		this.GetNomeFabricante = function () { return this.nome_fabricante; }
		

			
		this.setNome = function($nome) { var $nome = !$nome?'':$nome; this.nome = $nome; }
		this.GetNome = function () { return this.nome; }
		
		this.setProdutoInativo = function ($ind_inativo) { var $ind_inativo = !$ind_inativo?'0':$ind_inativo; this.ind_inativo = $ind_inativo; }
		this.setPreco = function ($preco) { var $preco = !$preco?'':$preco; this.preco = $preco; }
		this.setPrecoMin = function ($preco) { var $preco = !$preco?'':$preco; this.preco_min = $preco; }
		this.setPrecoMax = function ($preco) { var $preco = !$preco?'':$preco; this.preco_max = $preco; }
		this.setPrecoPessoa = function ($preco) { var $preco = !$preco?'':$preco; this.preco_pessoa = $preco; }
		
		this.setTotalDominios = function ($total) { var $total = !$total?'':$total; this.total_dominios = $total; }
		
		this.GetPodutoInativo = function () { return this.ind_inativo; }
		this.GetProdutoInativoFormated = function () { 
			if(this.ind_inativo+''=='1') {
				return '<font color="red">Sim</font>';
			} else {
				return '<font color="green">Não</font>';
			} 
		}
		
		this.boComprar = function() {
			var boC = this.arrDados['boComprar']+''=='0'?false:true;
			return boC;
		}
		
		this.GetPreco = function () { return this.preco; }
		this.GetPrecoFormated = function ($moeda,$cs) { 
			var $moeda = !$moeda?'':$moeda;
			var $cs = !$cs?'':$cs;
			switch($cs) {
				case 'min' :
						$preco = parseFloat(this.preco_min)>0?this.preco_min:'';
					break;
				case 'max' :
						$preco = parseFloat(this.preco_max)>0?this.preco_max:'';
					break;
				case 'pessoa' :
						$preco = parseFloat(this.preco_pessoa)>0?this.preco_pessoa:'';
					break;
				default :
						$preco = parseFloat(this.preco)>0?this.preco:'';
					break;
			}
			
			
			switch(this.mode) {
				case 'edit':
						if($preco+''=='') {
							return '';
						}
						if(!$preco) {
							return '0';
						}
						return number_format($preco,2,',','.');
					break;
				default :
						if(!$preco) {
							this.pub_arrParams['bo_comprar'] = false; 
							return 'sob consulta';
						} else {
							switch(strtoupper($moeda)+'') {
								case 'R$':
								default:
										return '<span class="simbolo">R$</span> ' + number_format($preco,2,',','.');
									break;
								case '$':
										return '<span class="simbolo">$</span> ' + number_format($preco,2,'.',',');
									break;
							}		
						}
					break;
			}

		}		
		this.GetPrecoMinFormated = function ($moeda) { 
			return this.GetPrecoFormated($moeda,'min');
		}
		this.GetPrecoMaxFormated = function ($moeda) { 
			return this.GetPrecoFormated($moeda,'max');
		}
		this.GetPrecoPessoaFormated = function ($moeda) { 
			return this.GetPrecoFormated($moeda,'pessoa');
		}
		this.GetPrecoMaxFormatedLabel = function ($moeda) { 
			if(this.preco_max+''=='' || this.preco_max+''==this.preco_min+'') return '';
			return '<small>até: </small>' + this.GetPrecoFormated($moeda,'max');
		}
		this.GetTotalDominios = function () { 
			return this.total_dominios;
		}
		this.setLinkDetalhe = function () { this.link_detalhe = 'produtos/detalhe/idproduto/'+this.GetID(); }
		this.GetLinkDetalhe = function () { return this.link_detalhe; }
		
		
		
		this.setFoto = function () {
			this.pub_arrParams['bo_imagemprincipal'] = false; 
			if(this.arrDados['Dsc_ImagemPrincipalExtensao']+''!='') {
				this.pub_arrParams['bo_imagemprincipal'] = true; 
				
				$idAUX = str_repeat('0',9-strlen(this.id))+this.id;
				try{
					$urlFOLDER = ARQ_URL_PRODUTOS + "/"+$idAUX+"/"+$idAUX+"";
				} catch(e){
					$urlFOLDER = $idAUX+"/"+$idAUX+"";
				}
				
				this.foto['min'] = $urlFOLDER + '_0.' + this.arrDados['Dsc_ImagemPrincipalExtensao'];
				this.foto['pqn'] = $urlFOLDER + '_1.' + this.arrDados['Dsc_ImagemPrincipalExtensao'];
				this.foto['gnd'] = $urlFOLDER + '_2.' + this.arrDados['Dsc_ImagemPrincipalExtensao'];
				this.foto['big'] = $urlFOLDER + '_3.' + this.arrDados['Dsc_ImagemPrincipalExtensao'];
			}
		}
		
		this.GetFoto = function ($cs) {
			var $cs = !$cs?'':$cs;
			return this.foto[$cs];
		}

		
		this.setFotoFabricante = function () {
			//if(this.arrDados['Dsc_ImagemPrincipalExtensao']+''!='') {
				this.fotoFabricante['min'] = getFabricanteUrlImageByID(this.id_fabricante,'min');
				this.fotoFabricante['pqn'] = getFabricanteUrlImageByID(this.id_fabricante,'pqn');
				this.fotoFabricante['gnd'] = getFabricanteUrlImageByID(this.id_fabricante,'gnd');
			//}
		}
		
		this.GetFotoFabricante = function ($cs) {
			var $cs = !$cs?'':$cs;
			return this.fotoFabricante[$cs];
		}
		
		
		this.setDescricao = function ($descricao) { var $descricao = !$descricao?'':$descricao; this.descricao = $descricao; }
		this.GetDescricao = function () { return this.descricao; }
		
		this.GetDisponibilidade = function () {
			$disponibilidade = !this.disponibilidade?'':this.disponibilidade;
			return $disponibilidade;
		}
		this.GetCodDisponibilidade = function () {
			return this.arrDados['codDisponibilidade']+'';
		}
		this.GetDisponibilidadeHTML = function () {
			var result = '';
			var $codDisponibilidade = this.arrDados['codDisponibilidade']+'';
			switch($codDisponibilidade) {
				case '0' :
				case '1' :
						result = '<span class="dipon_'+$codDisponibilidade+'">'+this.disponibilidade+'</span>';
					break;
				case '2' :
						result = '<span class="dipon_'+$codDisponibilidade+'"><a href="'+this.GetLinkDetalhe()+'">'+this.disponibilidade+', avise-me</a></span>';
					break;
			}
			
			return result;
		}
		
		this.GetVendedoresDados2 = function () {
			if(!globals_arrDadosDB['pessoas']) return '';
			var result = '';
			var arrDadosPessoas = globals_arrDadosDB['pessoas'];
			var arrDadosProdutosXPessoas = globals_arrDadosDB['produtos_pessoas'];
			var url = 'http://cotafesta.localhost/projetos/index.php/compare/produtos/prodpes/idproduto/'+this.GetID();
			var post = '';
			//setAsync(true);
			
			$.post(url,post,function(a,b){
				eval("var arrProdPes = " + a);
			});
			
			var strResult = '';
			strResult += '<table>';
			for(idPessoa in arrProdPes) {
				var Num_Preco = arrProdPes[idPessoa]['Num_Preco'];
				alert(Num_Preco)
				
				var arrPessoas = arrDadosPessoas[idPessoa];
				var Nom_Pessoa = arrPessoas['Nom_Pessoa'];
				var Dsc_Site = arrPessoas['Dsc_Site']+'';
				
				if(Dsc_Site) {
					Dsc_Site = Dsc_Site.toLowerCase();
					if(Dsc_Site.indexOf('http://')==-1) {
						Dsc_Site = 'http://'+Dsc_Site;
					}
				}
				
				strResult += ' <tr>';
				strResult += '  <td>'+ Nom_Pessoa +'</td>';
				strResult += '  <td><a href="'+Dsc_Site+'" target=_blank"">'+ Dsc_Site +'</a></td>';
				strResult += '  <td>R$ '+ Num_Preco +'</td>';
				strResult += '</tr>';
			}
			strResult += '</table>';
			
			return strResult;
		}
		
		this.GetVendedoresDados = function () {
			if(!globals_arrDadosDB['pessoas']) return '';
			var result = '';
			var arrDadosPessoas = globals_arrDadosDB['pessoas'];
			var arrDadosProdutosXPessoas = globals_arrDadosDB['produtos_pessoas'];
			var url = 'http://cotafesta.localhost/projetos/index.php/compare/produtos/prodpes/idproduto/'+this.GetID(); 
			var url = baseUrlModule + 'produtos/prodpes/idproduto/'+this.GetID(); 
			var post = '';
			//setAsync(true);
			var strResult = '';
			$.post(url,post,function(a,b){
				eval("var arrProdPes = " + a);
							
				strResult += '<table>';
				for(idPessoa in arrProdPes) {
					var Num_Preco = arrProdPes[idPessoa]['Num_Preco'];
					alert(Num_Preco)
					
					var arrPessoas = arrDadosPessoas[idPessoa];
					var Nom_Pessoa = arrPessoas['Nom_Pessoa'];
					var Dsc_Site = arrPessoas['Dsc_Site']+'';
					
					if(Dsc_Site) {
						Dsc_Site = Dsc_Site.toLowerCase();
						if(Dsc_Site.indexOf('http://')==-1) {
							Dsc_Site = 'http://'+Dsc_Site;
						}
					}
					
					strResult += ' <tr>';
					strResult += '  <td>'+ Nom_Pessoa +'</td>';
					strResult += '  <td><a href="'+Dsc_Site+'" target=_blank"">'+ Dsc_Site +'</a></td>';
					strResult += '  <td>R$ '+ Num_Preco +'</td>';
					strResult += '</tr>';
				}
				strResult += '</table>';
				
			})
			
			
			/*
			var arrProdPes = arrDadosProdutosXPessoas[this.GetID()];
						
			var strResult = '';
			strResult += '<table>';
			for(idPessoa in arrProdPes) {
				var Num_Preco = arrProdPes[idPessoa]['Num_Preco'];
				
				var arrPessoas = arrDadosPessoas[idPessoa];
				var Nom_Pessoa = arrPessoas['Nom_Pessoa'];
				var Dsc_Site = arrPessoas['Dsc_Site']+'';
				
				if(Dsc_Site) {
					Dsc_Site = Dsc_Site.toLowerCase();
					if(Dsc_Site.indexOf('http://')==-1) {
						Dsc_Site = 'http://'+Dsc_Site;
					}
				}
				
				strResult += ' <tr>';
				strResult += '  <td>'+ Nom_Pessoa +'</td>';
				strResult += '  <td><a href="'+Dsc_Site+'" target=_blank"">'+ Dsc_Site +'</a></td>';
				strResult += '  <td>R$ '+ Num_Preco +'</td>';
				strResult += '</tr>';
			}
			strResult += '</table>';
			*/
			return strResult; 
		}
		
		this.setResumo = function ($resumo) { 
			var $resumo = !$resumo?'':$resumo;
			$resumo = $resumo+''=='' || $resumo+''=='null'?'':$resumo;
			if($resumo+''=='') {
				$resumo = this.arrDados['Dsc_Descricao']+'';
				$resumo = strlen($resumo)>500?substr(strip_tags($resumo),0,500)+'...':$resumo;
			}
			this.resumo = $resumo=='null'?'':$resumo;
			this.resumo = trataString(this.resumo);
		}
		
		this.GetResumo = function () { return this.resumo; }
		
		
		this.setFromArray = function ($arr) {
			this.arrDados = $arr;
			if(this.arrDados) {
				this.setID(this.arrDados['idProduto']);
				this.setIdFabricante(this.arrDados['idFabricante']);
				this.setNomeFabricante(this.arrDados['Nom_Fabricante']);
				this.setNome(this.arrDados['Nom_Produto']);
				this.setPreco(this.arrDados['Num_Preco']);
				this.setPrecoMin(this.arrDados['minPreco']);
				this.setPrecoMax(this.arrDados['maxPreco']);
				this.setProdutoInativo(this.arrDados['Ind_Inativo']);
				this.setPrecoPessoa(this.arrDados['Num_PrecoPessoa']);
				this.setTotalDominios(this.arrDados['totalDominios']);
				this.setDescricao(this.arrDados['Dsc_Descricao']);
				this.setResumo(this.arrDados['Dsc_Resumo']);
				this.setLinkDetalhe();
				
				this.disponibilidade = this.arrDados['Disponibilidade'];
				
				this.setFoto();
				this.setFotoFabricante();
			}
			
		}
		this.GetDados = function () { this.arrDados = $arr; }
		
		this.__construct();
	}

	var arrInstance = new Array();
	pagingArrayData = function(objContainerPag,$arrPag) {
		this.paginaAtual = 1;
		this.arrDATA = $arrPag;
		this.idPaging = '';
		this.objAncora = '';
		this.bopaginationtop = true;
		this.bopaginationbottom = true;
		
		this.dataType = 'produtos';
		
		this.pagination = new Array();
		this.optInit = new Array();
		this.offset = 0;
		this.rowsPerPage = 15;
		this.maxPages = 10;
		this.rowCount = '';
		this.ocultaPag = 0;
		
		this.init = function() {
			var rnd = (new Date()).getTime();
			this.idPaging = "jqpaging_"+rnd;
			
			
			eval('var param = '+$(objContainerPag).attr('param')+';');
			var param = !param?'':param;
			
			if(param.rowsPerPage) 	this.rowsPerPage 	= param.rowsPerPage;
			if(param.maxPages) 		this.maxPages 		= param.maxPages;
			if(param.offset) 		this.offset 		= param.offset;
			if(param.rowCount) 		this.rowCount 		= param.rowCount;
			if(param.ocultaPag)		this.ocultaPag 		= param.ocultaPag;
			
			if(this.rowCount) {
				var arrAux = this.arrDATA['dados'];
				this.arrDATA['dados'] = new Array();
				var count = 1;
				for(i in arrAux) {
					var row = arrAux[i];
					this.arrDATA['dados'].push(row);
					if(count+''==this.rowCount+'') { 
						break;
					}
					count++;
				}
			}
			
			
		}
		
		this.setDataType = function($t) {
			this.dataType = $t;
		}		
		this.setVars = function() {
			//var size = this.rowCount?this.rowCount:sizeof(this.arrDATA['dados']);
			var size = this.getRowCount();
			this.maxPages = size/this.rowsPerPage;
			this.maxPages = this.maxPages<1?1:this.maxPages;
			this.getPagination();
		}
		
		this.paginador = function(page_index, jq, opts) {
				var page = parseInt(page_index) + 1;
				var str = '';
				for(i in arrInstance) {
					str+=i+' = '+arrInstance[i] + "\n";
				}
				//$(objContainerPag).fadeTo("quick", 0);
				//$(objContainerPag).toggle();

				var idPaging = opts['idpaging']+'';
				
				var objInstance = arrInstance[idPaging];
				//$(objInstance.objAncora).focus();
				objInstance.paginaAtual = page;
				objInstance.pagination['currentPage'] = page;
				
				objInstance.printPagination();
				
				
				var objTbEdit = $('#'+idPaging).find('.tbEdit');
				
				$(objTbEdit).removeClass('loaded');
				$(objTbEdit).find('.th_actions').remove();
				$(objTbEdit).find('.td_actions').remove();
				// $(objTbEdit).find('#formSave').remove();
				
				
				
				objInstance.showData('2');

			return false;
		}
		
		this.create = function() {
			this.setVars();
			$(objContainerPag).after('<div id="'+this.idPaging+'" class="box_all_paging"><div class="content" param="'+this.idPaging+'"></div></div>');
			//$(objContainerPag).remove();
			
			//$('.boxListProd').appendTo('#'+this.idPaging);
			//$('#'+this.idPaging).find('.content').append(html);
			$(objContainerPag).appendTo($('#'+this.idPaging).find('.content'));
			
			
			//$(objContainerPag).append('<div class="content" param="'+this.idPaging+'"></div>');
			$(objContainerPag).append('<div class="maincontent" param="'+this.idPaging+'"></div>');
			
			if(!this.ocultaPag) {
				if(this.bopaginationtop) $('#'+this.idPaging).find('.content').before('<div class="boxpag"><div class="paginationtop pagination"></div></div>');
				if(this.bopaginationbottom) {
					$('#'+this.idPaging).find('.content').after('<div class="boxpag"><div class="paginationbottom pagination"></div></div>');
				} else {
					$('#'+this.idPaging).find('.content').after('<div class="boxpag" style="display: none;"><div class="paginationbottom pagination"></div></div>');
				}
			}
			
			//$(objContainerPag).find('.content').before('<div class="boxpag"><div class="paginationtop pagination"></div></div>');
			//$(objContainerPag).find('.content').after('<div class="boxpag"><div class="paginationbottom pagination"></div></div>');
			
			
			var parentBox = $('#'+this.idPaging);
			
			$(parentBox).before('<a name="'+this.idPaging+'" style="width:1px;height:1px;position:absolute;left:-10000px;margin-top:-100px;"><input type="text"></a>');

			this.objAncora = $('a[name='+this.idPaging+'] input');
			arrInstance[this.idPaging] = this;
			
			
			
			//if(this.pagination['rowCount']>this.rowsPerPage) {
				//optInit["callback"]=pageselectCallback;
				this.optInit["callback"]=this.paginador;
				this.optInit["idpaging"]=this.idPaging;
				
				this.optInit["items_per_page"]=this.rowsPerPage;
				this.optInit["num_display_entries"]=10;
				this.optInit["num_edge_entries"]=3;
				this.optInit["prev_text"]='&laquo;';
				this.optInit["next_text"]='&raquo';
				//$('#'+this.idPaging).find('.paginationtop').pagination(sizeof(this.arrDATA['dados']), optInit);
				$('#'+this.idPaging).find('.paginationbottom').pagination(sizeof(this.arrDATA['dados']), this.optInit);
				
				
				$('#'+this.idPaging).find('.pagination a').each(function(){
					//$(this).attr('onClick',"");
				});
			//}
			
			//this.showData();
			$(parentBox).before('<a name="'+this.idPaging+'2" style="width:1px;height:1px;position:absolute;left:-10000px;top:0px;"><input type="text"></a>');
			$('a[name='+this.idPaging+'2] input').focus().remove();
			
		}
		this.filterData = function(arrFilter) {			
			this.arrDATA['dados'] = arrFilter;
			
			//alert(arrFilter)
			this.setVars();
			var objDivPagBottom = $('#'+this.idPaging).find('.paginationbottom').get(0);
			if(objDivPagBottom) {
				$(objDivPagBottom).html('');
				$(objDivPagBottom).pagination(sizeof(this.arrDATA['dados']), this.optInit);
				this.paginador(0,'',this.optInit);
			}
			
			
			this.showData();
			
			var objTbEdit = $('#'+this.idPaging).find('.tbEdit');
			$(objTbEdit).removeClass('loaded');
			$(objTbEdit).find('.th_actions').remove();
			$(objTbEdit).find('.td_actions').remove();
		}
		this.preparaArrayData = function(arrDATA) {
			var arrDATA_NEW = new Array();
			var count = 0;
			if(arrDATA) {
				if(!arrDATA[0] && $(arrDATA).size()) {
					for(iLoop in arrDATA) {
						arrDATA_NEW[count] = arrDATA[iLoop];
						count++;
					}
				} else {
					arrDATA_NEW = arrDATA;
				}
			}
			return arrDATA_NEW;
		}
		this.showData = function(cs) {
			var cs = cs?cs:'';
			//alert(this.paginaAtual);
			//alert(this.rowsPerPage);
			$(this.objAncora).focus();
			//$(objContainerPag).fadeTo("slow", 1);
			$(objContainerPag).find('.maincontent').html('');
			var item = 1;
			var startPage = 0;
			$limit = (this.rowsPerPage+''=='')?this.pagination['rowCount']:this.rowsPerPage;
			$start = ($limit*this.pagination['currentPage']) - $limit; // do not put $limit*(this.page - 1)
			this.arrDATA['dados'] = this.preparaArrayData(this.arrDATA['dados']); 
			
			if(this.pagination['rowCount']) {
					for($i=$start;$i<this.pagination['rowCount'];$i++) {
						var row = this.arrDATA['dados'][$i];
						this.arrDATA['dados']['loaded'] = true;
						
						
						if(this.arrDATA['dados'][$i]) {
								if(!this.arrDATA['dados'][$i]['loaded']) {
									var html = this.arrDATA['tpl'];
									if(isFunction(html)) {
										var arrArg = new Array();
										arrArg.push(item);
										arrArg.push(row);
										arrArg.push(this.idPaging);
										func = html;
										html = func.apply(null, arrArg);
									} else {
											html = replaceSubstring(html,"{tplUrlFilesRoot}",tplUrlFilesRoot);
											html = replaceSubstring(html,"{IMG_DIR}",IMG_DIR);
											html = replaceSubstring(html,"{TEMPLATES_DIR}",TEMPLATES_DIR);
											
											
											switch(this.dataType+'') {
												case 'video' :
														var clsVideo = new AbstractVideo();	
														clsVideo.setFromArray(row);
														
														html = replaceSubstring(html,"{clsVideo->GetID()}",clsVideo.GetID());
														html = replaceSubstring(html,"{clsVideo->GetNome()}",clsVideo.GetNome());
														html = replaceSubstring(html,"{clsVideo->GetFoto('pqn')}",clsVideo.GetFoto('pqn'));
														html = replaceSubstring(html,"{clsVideo->GetFoto('min')}",clsVideo.GetFoto('min'));
														html = replaceSubstring(html,"{clsVideo->GetFoto('gnd')}",clsVideo.GetFoto('gnd'));
														html = replaceSubstring(html,"{clsVideo->GetFoto('big')}",clsVideo.GetFoto('big'));
														html = replaceSubstring(html,"{clsVideo->GetChamada()}",clsVideo.GetChamada());
														html = replaceSubstring(html,"{clsVideo->GetResumo()}",clsVideo.GetResumo());
														html = replaceSubstring(html,"{clsVideo->GetLinkDetalhe()}",clsVideo.GetLinkDetalhe());
														html = replaceSubstring(html,"{clsVideo->GetDescricao()}",clsVideo.GetDescricao());
														html = replaceSubstring(html,"{clsVideo->GetUrlFoto()}",clsVideo.GetUrlFoto());
														html = replaceSubstring(html,"{clsVideo->GetUrlVideo()}",clsVideo.GetUrlVideo());
														
													break;
												default :
														var clsProduto = new AbstractProduto();
														clsProduto.setFromArray(row);
														
														html = replaceSubstring(html,"{clsProduto->GetID()}",clsProduto.GetID());
														html = replaceSubstring(html,"{clsProduto->GetNome()}",clsProduto.GetNome());
														html = replaceSubstring(html,"{clsProduto->GetFoto('pqn')}",clsProduto.GetFoto('pqn'));
														html = replaceSubstring(html,"{clsProduto->GetFoto('min')}",clsProduto.GetFoto('min'));
														html = replaceSubstring(html,"{clsProduto->GetFoto('gnd')}",clsProduto.GetFoto('gnd'));
														html = replaceSubstring(html,"{clsProduto->GetFoto('big')}",clsProduto.GetFoto('big'));
														
														html = replaceSubstring(html,"{clsProduto->GetFotoFabricante('pqn')}",clsProduto.GetFotoFabricante('pqn'));
														html = replaceSubstring(html,"{clsProduto->GetFotoFabricante('min')}",clsProduto.GetFotoFabricante('min'));
														html = replaceSubstring(html,"{clsProduto->GetFotoFabricante('gnd')}",clsProduto.GetFotoFabricante('gnd'));
														
														html = replaceSubstring(html,"{clsProduto->GetResumo()}",clsProduto.GetResumo());
														html = replaceSubstring(html,"{clsProduto->GetIdFabricante()}",clsProduto.GetIdFabricante());
														html = replaceSubstring(html,"{clsProduto->GetNomeFabricante()}",clsProduto.GetNomeFabricante());
														html = replaceSubstring(html,"{clsProduto->GetProdutoInativoFormated()}",clsProduto.GetProdutoInativoFormated());
														html = replaceSubstring(html,"{clsProduto->GetPrecoFormated()}",clsProduto.GetPrecoFormated());
														html = replaceSubstring(html,"{clsProduto->GetPrecoMinFormated()}",clsProduto.GetPrecoMinFormated());
														html = replaceSubstring(html,"{clsProduto->GetPrecoPessoaFormated()}",clsProduto.GetPrecoPessoaFormated());
														html = replaceSubstring(html,"{clsProduto->GetPrecoMaxFormated()}",clsProduto.GetPrecoMaxFormated());
														html = replaceSubstring(html,"{clsProduto->GetPrecoMaxFormatedLabel()}",clsProduto.GetPrecoMaxFormatedLabel());
														html = replaceSubstring(html,"{clsProduto->GetTotalDominios()}",clsProduto.GetTotalDominios());
														html = replaceSubstring(html,"{clsProduto->GetLinkDetalhe()}",clsProduto.GetLinkDetalhe());
														html = replaceSubstring(html,"{clsProduto->GetDescricao()}",clsProduto.GetDescricao());
														//html = replaceSubstring(html,"{clsProduto->GetVendedoresDados()}",clsProduto.GetVendedoresDados());
														html = replaceSubstring(html,"{clsProduto->GetDisponibilidade()}",clsProduto.GetDisponibilidade());
														html = replaceSubstring(html,"{clsProduto->GetDisponibilidadeHTML()}",clsProduto.GetDisponibilidadeHTML());
														html = replaceSubstring(html,"{clsProduto->GetCodDisponibilidade()}",clsProduto.GetCodDisponibilidade());
														
														//html = replaceSubstring(html,"{clsProduto->GetDescricao()}",clsProduto.GetDescricao());
														
														//alert(html);
													break;
											}
											$(objContainerPag).find('.maincontent').append(html);
											this.arrDATA['dados'][$i]['loaded'] = html;
									}
										
								} else {
									$(objContainerPag).find('.maincontent').append(this.arrDATA['dados'][$i]['loaded']);
								}
						}
						
						if(item>=this.rowsPerPage) break;
						item++;
					}
			} else {
						var html = this.arrDATA['tpl'];
						if(isFunction(html)) {
							var arrArg = new Array();
							arrArg.push(item);
							arrArg.push(row);
							func = html;
							html = func.apply(null, arrArg);
						} else {
							$(objContainerPag).find('.content').append('');
						}
			}
			loadSettings();
			
		}
		
		this.printPagination = function() {
			
			$startPage = 0;
			if(this.pagination['currentPage']>1) {
				$startPage = (this.pagination['currentPage']-1) * this.rowsPerPage;
			}
			/*
			$maxPagesHalf = ceil(this.maxPages / 2);
			if(this.pagination['numPages'] <= this.maxPages) {
				$startPage = 0;
				$endPage = this.pagination['numPages'];
			} else if (this.pagination['currentPage'] <= $maxPagesHalf) {
				$startPage = 0;
				$endPage = this.maxPages;
			} else if ((this.pagination['currentPage'] + $maxPagesHalf) > this.pagination['numPages']) {
				$endPage = this.pagination['numPages'];
				$startPage = $endPage - this.maxPages;
			} else {
				$startPage = this.pagination['currentPage'] - $maxPagesHalf - 1;
				$endPage = this.pagination['currentPage'] + $maxPagesHalf;
			}
			*/
			
			var result = '';
			
			//if(this.pagination['rowCount']>this.rowsPerPage) {
				var totalShow = (this.rowsPerPage*this.pagination['currentPage']);
				totalShow = totalShow>this.pagination['rowCount']?this.pagination['rowCount']:totalShow;
				var boOK = true;
				
				if(this.pagination['rowCount']) {
					if(this.pagination['rowCount']>1) {
						if(this.pagination['rowCount']<=this.rowsPerPage) {
							result += '<div class="pageListInfo">Mostrando <span>'+($startPage+1)+' - '+totalShow+'</span> de <span>'+this.pagination['rowCount']+'</span> distribuído(s) em <span>'+this.pagination['numPages']+' página</span></div>';
						} else {
							result += '<div class="pageListInfo">Mostrando <span>'+($startPage+1)+' - '+totalShow+'</span> de <span>'+this.pagination['rowCount']+'</span> distribuído(s) em <span>'+this.pagination['numPages']+' páginas</span></div>';
						}
					} else {
						//result += '<div class="pageListInfo" style="display:none;"></div>';
					}
				} else {
					result += '<div class="pageListInfo">Nenhum registro encontrado</div>';
					boOK = false;
				}
				
				var parentBox = $('#'+this.idPaging);
				$(parentBox).find('.pageListInfo').remove();

				if(boOK) {
					$(parentBox).find('.paginationtop').before(result);
				}
				$(parentBox).find('.paginationbottom').before(result);
				
				
				$($(parentBox).find('.paginationbottom')).wrap('<div class="paginadorcontainer"><div class="paginadorcontainer_container"></div></div>');
				
				
			//}
			

			

		}
		
		this.getRowCount = function () {
			//this.pagination['rowCount'] = this.rowCount+''!=''?this.rowCount:sizeof(this.arrDATA['dados']);
			this.pagination['rowCount'] = sizeof(this.arrDATA['dados']);
		}
		
		this.getPagination = function () {
			this.getRowCount();
			this.pagination['numPages'] = ceil(this.pagination['rowCount'] / this.rowsPerPage);
			this.pagination['currentPage'] = ceil(this.offset / this.rowsPerPage) + 1;
			if(this.offset == 0) {this.pagination['currentPage'] = 1;}
			this.pagination['firstRowOnPage'] = this.offset + 1;
			this.pagination['lastRowOnPage'] = (this.pagination['currentPage'] == this.pagination['numPages']) ? this.pagination['rowCount'] : this.offset + this.rowsPerPage;
			if(this.pagination['rowCount'] == 0) {
				this.pagination['firstRowOnPage'] = 0;
				this.pagination['lastRowOnPage'] = 0;
			}
		}
		
		
		this.init();
	}
	

	function get_carriers_html(resp) {
						var html = '';
						if(resp) {
							if(resp.endereco) {
								var rowEnd = resp.endereco;
								var arrFrete = resp.frete;
								if(rowEnd.resultado+''!='0') {
									var uf = rowEnd['uf'];
									var cidade = rowEnd['cidade'];
									var bairro = '';
									var tipo_logradouro = '';
									var logradouro = '';
									var logradouro_join = '';

									if(rowEnd.resultado+''=='1') {
										bairro = rowEnd['bairro'];
										tipo_logradouro = rowEnd['tipo_logradouro'];
										logradouro = rowEnd['logradouro'];
										logradouro_join = rowEnd['logradouro_join'];
									}
									
									var count = 0;
									if(arrFrete) {
										html+= '<label class="info">Valores de entrega para: <i>'+ cidade + ' - ' + uf  +'</i></label>';
										var vMin = 0;
										var boFirst = 1;
										var servicoMin = '';
										for(i in arrFrete) {
											var rowFrete = arrFrete[i];
											var servico = i;
											var frete = rowFrete['frete'];
											var freteUSA = replaceSubstring(frete,".",'');
											freteUSA = replaceSubstring(freteUSA,",",'.');
											freteUSA = parseFloat(freteUSA);
											
											if(boFirst || vMin > freteUSA) {
												vMin = freteUSA;
												servicoMin = servico;
												boFirst = 0;
											}
										}
										
										for(i in arrFrete) {
											var rowFrete = arrFrete[i];
											
											var servico = i;
											var frete = rowFrete['frete'];
											var prazo = rowFrete['prazo'];
											
											var strChecked = servicoMin+''==servico+''?' checked ':'';
											
											html+= '<label class="option option_'+count+' correios">';
											html+= '	<span class="name"><input '+strChecked+' type="radio" class="input-radio" name="opt_frete" value="'+servico+'" style="vertical-align: middle;" /> '+servico+'</span> ';
											html+= '	<span class="period">Prazo de entrega: <strong>'+prazo+'</strong></span> ';
											html+= '	<span class="value">R$ '+frete+'</span>';
											html+= '</label>';
											count++;
										}
										if(count+''=='0') {
											var txt = 'CEP inexistente ou inválido para cálculo do frete!';
											html+= '<font color="red">' + txt + '</font>';
											jAlert(txt);
										}
										
									} else {
										var txt = 'CEP inexistente ou inválido para cálculo do frete!';
										html+= '<font color="red">' + txt + '</font>';
										jAlert(txt);
									}
								} else {
									html= '<font color="red">' + rowEnd.resultado_txt + '</font>';
									jAlert(rowEnd.resultado_txt);
								}
							}
						}
						
						return html;
	}
	
	function bnrtpl_loadBoxCalcFrete() {
		$('.__BNRTPL__CALCULAFRETE').each(function(){
				var url = TEMPLATES_DIR + '/correiros-busca-cep.htm';
				
				eval('var objParam = '+$(this).attr('param')+';');
				var optval = '';
				if(objParam) {
					optval = objParam.optval?objParam.optval:'';
				}
				
				var strHTML = '';
				strHTML+= '<form method="get" action="" param="{mode:\'ajax\'}" id="form-product-carrier">';
				strHTML+= '	<fieldset class="zipcode">';
				strHTML+= '		<label class="info">Digite o CEP do endereço de entrega para <strong>calcular o valor do serviço de entrega:</strong></label>';
				strHTML+= '		<label class="legenda"><span>CEP</span></label>';
				strHTML+= '		<label class="zipcode"><input type="text" value="'+CEP_ENTREGA_DESTINO+'" class="input required input-text txt-zipcode" id="zipcode" name="zipcode" /></label>';
				strHTML+= '		<label class="button"><input type="submit" class="input input-button btn-calcular" value="Calcular Frete" title="Calcular o valor do serviço de entrega"></label>';
				strHTML+= '		<label class="zipcode-popup"><a title="Não  sabe o seu CEP? Consulte aqui" href="'+url+'" onclick="return hs.htmlExpand(this, { objectType:\'iframe\',objectWidth: 400, objectHeight: 350, allowSizeReduction: false} )" class="iframe">Não sabe o seu CEP?</a></label>';
				strHTML+= '	</fieldset>';
				strHTML+= '	<fieldset class="carriers"></fieldset>';
				strHTML+= '</form>';
				
		
				
				$(this).removeClass('__BNRTPL__CALCULAFRETE');
				$(this).append(strHTML);
				
				var objCEP = $('#form-product-carrier #zipcode').get(0);
				$(objCEP).mask("99999999");
				
				
				//try {
					if(CEP_DADOS) {
						var html = get_carriers_html(CEP_DADOS);
						$('.carriers').html(html);
					}
				//} catch(err) {
					
				//}

				if(optval) {
					$('.carriers').find('input').each(function(){
						if($(this).val()+''==optval+'') {
							$(this).attr('checked','checked');
						}
					});
				}
				$('.carriers').find('input').each(function(){
					$(this).mousedown(function(){					
						$('#aguarde').remove();
						$('.carriers').prepend('<div id="aguarde" style="position: absolute;padding: 2px 10px 2px 10px;background: red !important; color: #fff !important;">&nbsp;&nbsp;aguarde...&nbsp;&nbsp;</div>');
						var boOK = false;
						var val = $(this).val()+'';
						var url = baseUrlModule + 'actionpub/carrinho-de-compra/acao/carrier/tipo/'+val;
						$.post(url,'',function(result){
							try {
									eval('var resp = '+result+';');
									if(resp) {
										var totalgeral = resp.totalgeral;
										var valor_frete = resp.valor_frete;
										var tipo_frete = resp.tipo_frete;
										
										$('#Num_TotalGeral').html(totalgeral);
										
										boOK = true;
									} else {
											jAlert('Não foi possível alterar!');
										boOK = false;
									}

							} catch(err) {
								var html = "Ocorreu um erro";
								if(err.description) {
									html+= ": " + err.description ;
								}
								jAlert(html);
							}
						});
						$('#aguarde').remove();
						$(this).attr('checked',boOK);
						return boOK;
					});
				});
				
				$('#form-product-carrier:not(.calculando)').submit(function(){
						//$(this).block({message:'calculando...'});
						$(this).addClass('calculando');
						var html = '';
						var objtxtzipcode = $(this).find('.txt-zipcode').get(0);
						var valCEP = $(objtxtzipcode).val()+'';
						var url = baseUrlModule + 'actionpub/getcep/cep/'+valCEP;
						
						if(valCEP+''=='') {
								jAlert('Você deve informar o CEP do local de entrega!');
								objtxtzipcode.focus();
								return false;
						} else {
								$('.carriers').html('<div style="background:#ffffff;color:red;"><b>&nbsp;&nbsp;&nbsp;calculando...&nbsp;&nbsp;&nbsp;</b></div>');
								eval('var objParam = '+$(this).attr('param')+';'); 
								timeoutCEP();
								switch(objParam.mode) {
									case 'post' :
											$(this).attr('method','post');
											$(this).attr('action',url);
										break;
									default :
											var strUrlLocation = (document.location.href+'').toLowerCase();
											if(strUrlLocation.indexOf('detalhe/idproduto/')!=-1) {
												var arrP = strUrlLocation.split('detalhe/idproduto/');
												var idP = arrP[1]+'';
												arrP = idP.split('/');
												idP = arrP[0]+'';
												url += '/idproduto/' + idP;
											}
											/*
											$.ajax({
												type:"post",
												url:url,
												data: '',
												dataType: "json",
												timeout: 1000, // in milliseconds
												success:function(result) {
														try {
																eval('var resp = '+result+';');
																var html = get_carriers_html(resp);

														} catch(err) {
															
															html = "<font color='red'>Ocorreu um erro ao calcular";
															if(err.description) {
																html+= ": " + err.description ;
															}
															html+= "</font>";
														}
												},
												error: function(result, status, err) {
														html = "<font color='red'>Ocorreu um erro ao calcular";
														html+= "</font>";
														jAlert('Problemas na conexão! Não foi possivel calcular o frete!');
												}
											});
											*/
											

											
											
											$.post(url,'',function(result){
												try {
														eval('var resp = '+result+';');
														var html = get_carriers_html(resp);

												} catch(err) {
													
													html = "<font color='red'>Ocorreu um erro ao calcular";
													if(err.description) {
														html+= ": " + err.description ;
													}
													html+= "</font>";
												}
												$('.carriers').html(html);
												clearInterval(intervalCEP);
												
											});
											
											
											return false;
										break;
								}
								//$(this).unblock();
								
						}
						$(this).removeClass('calculando');
					return true;
				});

				if(CEP_ENTREGA_DESTINO) {
					if($('.carriers').is(':empty')) {
						//$('#form-product-carrier').submit();
					}
				}
		});	
	}

	var loadSettings = function() {
		monta__BNRTPL__FORMCONTATO();
		
		$('table.list:not(.loaded)').each(function(){
			$(this).addClass('loaded');
			
			$(this).find('tr:nth-child(even)').each(function(i){
				//var m = mod(i,2);
				m = 1;
				$(this).addClass('position_'+m);
			});
			
			$(this).find('tr:nth-child(odd)').each(function(i){
				//var m = mod(i,2);
				m = 0;
				$(this).addClass('position_'+m);
			});
		});
		

		$('.__BNRTPL__USERINFO').each(function(){
				$(this).removeClass('__BNRTPL__USERINFO');
				
				var cliNOME = CLIENTE_NOME.split(' ');
				cliNOME = cliNOME[0]+''==''?'Visitante':cliNOME[0];
				
				var html='';
				html+='<div id="userInfo" class="userInfo">';
				html+='		<div class="userInfo_container">';
				//html+='					<a href="'+baseUrlModule+'cart/dados.cadastrais/" class="mySubBox"></a>';
				html+='					<p id="hello" class="hello">'+getSaldacao()+' , '+cliNOME+'</p>';
				if(!CLIENTE_LOGADO) {
					html+='					<p class="login">(Faça o <a href="'+baseUrlModule+'cart/login.mostra/">login</a>)</p>';
				} else {
					html+='					<p class="logout">( <a href="'+baseUrlModule+'cart/logout">não é você?</a> | <a href="'+baseUrlModule+'cart/logout">sair</a>)</p>';
				}
				html+='		</div>';
				html+='</div>';
				
				$(this).append(html);
		});
		$('.__BNRTPL__PRODLOADDATA').each(function(){
			$(this).removeClass('__BNRTPL__PRODLOADDATA');
			var param = $(this).attr('param');
			eval('var objParam = ' + param + ';');
			if(objParam) {
				switch(objParam.type) {
					case 'image' :
							var imagesize = !objParam.imagesize?'min':objParam.imagesize;
							var imageext = !objParam.imageext?'min':objParam.imageext;
							idAUX = str_repeat('0',9-strlen(objParam.idproduto))+objParam.idproduto;
							var urlFOLDER = ARQ_URL_PRODUTOS + "/"+idAUX+"/";
							var url = urlFOLDER;
							switch(objParam.imagesize) {
								case 'min' :
										url = url + idAUX + '_0.'+imageext;
										
									break;
								case 'peq' :
								default :
										url = url + idAUX + '_1.'+imageext;
									break;
								case 'gnd' :
										url = url + idAUX + '_2.'+imageext;
									break;
							}
							
							var strImage = '<img src="'+url+'" />';
							$(this).append(strImage);
							loadScreenshot();
						break;
				}
			}
		});
		
		
		$('a[param=transacao_visanet],a[param=comprar],a[param=produto],a[param=home],a[param=loja_virtual],a[param=destaques],a[param=lancamentos],a[param=promocoes],a[param=produtos_todos],a[param=contato],a[param=faq],a[param=pedidos],a[param=cadastro],a[param=carrinho],a[param=prod__fabricante],a[param=prod__link_detalhe],a[param=senha_esqueceu]').each(function(){  
			var param = $(this).attr('param');
			switch(param) {
				case 'transacao_visanet' :
						$(this).click(function(){
								var msg = '';
								msg +='<center><img src="https://comercio.locaweb.com.br/visavbv/images/card_visa.gif"><BR>';
								msg +='<p><b><font color="#000099">&nbsp;';
								msg +='Aguarde, transa&ccedil;&atilde;o em andamento...<br>';
								msg +='N&atilde;o feche a janela at&eacute; que a transa&ccedil;&atilde;o seja finalizada.';
								msg +='</font></b></p>';
								$('body').block({message:msg});
								
								var idPedido = $(this).attr('rel'); 
								var url = 'http://lojaagendamix.localhost/projetos/index.php/shop/action-pub/cbpvisanet/idpedido/' + idPedido; 
								var url = 'http://lojaagendamix.localhost/projetos/index.php/shop/action-pub/cbpvisanet/idpedido/' + idPedido; 
								var url = baseUrlModule + 'cart/pagamento-recebe/idpedido/' + idPedido;
								$.post(url,'',function(resp){
									var objForm = $('form[name=frmMPG]');
									$(objForm).remove();
									
									var strForm = resp;
									$('body').append(strForm);
									var objForm = $('form[name=frmMPG]');
									
									MPGpopup=window.open('','MPGpopup','toolbar=1,location=0,directories=0,dependent=0,status=1,scrollbars=0,resizable=1');
									//window.document.frmMPG.submit();

									$(objForm).submit();
									//$(objForm).remove();
								});
								
							return false;
						});
					break;
				case 'carrinho' :
						$(this).attr('href','cart/');
					break;
				case 'comprar' :
						var url = '';
						var href = $(this).attr('href'); 
						var rel = $(this).attr('rel'); 
						eval('var objRel = ' + rel + ';');
						
						if(objRel.idproduto) {
							var qtdParam = $('qtd['+objRel.idproduto+']/1').serialize();
							url = baseUrlModule + 'cart/add/idprod/'+objRel.idproduto+'/'+qtdParam;
							//url = baseUrlModule + 'cart/';
						}
						
						if(url+''!='') {
							$(this).attr('href',url);
						}
					break;
				case 'produto' :
						var url = '';
						var href = $(this).attr('href'); 
						var rel = $(this).attr('rel'); 
						eval('var objRel = ' + rel + ';');
						
						if(objRel.idproduto) {
							url = 'produtos/detalhe/idproduto/'+objRel.idproduto+'';
						}
						if(objRel.nome) {
							url = 'produtos/?nomeproduto='+objRel.nome+'';
						}
						if(objRel.keyword) {
							url = 'produtos/?keyword='+objRel.keyword+'';
						}
						
						if(url+''!='') {
							$(this).attr('href',url);
						}
					break;
				case 'home' :
						$(this).attr('href','');
					break;
				case 'loja_virtual' :
						var href = $(this).attr('href'); 
						var rel = $(this).attr('rel'); 
						eval('var objRel = ' + rel + ';');
						if(objRel.dominio) {
							var url = SYSTEM_ROOT;
							url = url.replace(DOMINIO,objRel.dominio);
							url = url + baseUrl + 'shop/';
							$(this).attr('href',url); 
						} else {
							$(this).attr('href',baseUrl + 'shop/'); 
						}
						$(this).attr('target','_blank'); 
					break;
				case 'destaques' :
						$(this).attr('href','produtos/lista/destaques/1');
					break;
				case 'lancamentos' :
						$(this).attr('href','produtos/lista/lancamentos/1');
					break;
				case 'promocoes' :
						$(this).attr('href','produtos/lista/promocoes/1');
					break;
				case 'produtos_todos' :
						$(this).attr('href','produtos/');
					break;
				case 'contato' :
						$(this).attr('href','contato/');
					break;
				case 'faq' :
						$(this).attr('href','paginas/faq');
					break;
				case 'pedidos' :
						$(this).attr('href','cart/pedidos');
					break;
				case 'cadastro' :
						$(this).attr('href','cart/cadastro');
					break;
				case 'prod__fabricante' :
						var href = $(this).attr('href'); 
						var rel = $(this).attr('rel'); 
						try {
							eval('var objRel = ' + rel + ';');
							if(objRel.id) {
								var idFabricante = objRel.id;
								var txtOption = objRel.nome;
								var url = 'produtos/lista/idfabricante/'+idFabricante+'/nomefabricante/'+txtOption;
								$(this).attr('href',url); 
							}
						} catch(err) {
							
						}
					break;				
				case 'prod__link_detalhe' :
						var href = $(this).attr('href'); 
						var rel = $(this).attr('rel'); 
						eval('var objRel = ' + rel + ';');
						if(objRel.id) {
							var idProduto = objRel.id;
							var txtOption = objRel.nome;
							var url = 'produtos/detalhe/idproduto/'+idProduto;
							url += !txtOption?'':'/nomeproduto/'+txtOption;
							$(this).attr('href',url); 
						}
					break;				
				case 'senha_esqueceu' :
							$(this).attr('href',baseUrlModule + 'senha.esqueceu'); 
					break;
			}
			
			$(this).addClass(param);
			$(this).removeAttr('param');
		});
	
		if($('.media').size()){
			$('.media').each(function(){
					var rel = $(this).attr('rel');
					var href = $(this).attr('href')+'';
					
					if(href.indexOf('youtube')!=-1) {
						var hrefAux = (href+'');
						var arr = hrefAux.split('watch?v=');
						if(arr[1]) {
							hrefAux = arr[1]+'';
							arr = hrefAux.split('&');
							hrefAux = 'http://youtube.com/v/' + arr[0]+'';
							hrefAux = 'http://www.youtube.com/v/'+arr[0]+'&fs=1&hl=pt-BR&enablejsapi=1';
							$(this).attr('href',hrefAux);
						}
					}
					
					$(this).removeClass('media');
					$(this).media();
					
			})
		}

		
	/*
					<fieldset class="carriers">
						<label class="info">Valores de entrega</label>
						<label class="option option_0 correios">
							<span class="name">Sedex</span> 
							<span class="period">Prazo de entrega: <strong>3 dias úteis</strong></span> 
							<span class="value">R$ 43,89</span>
						</label>
						<label class="option option_1 correios">
							<span class="name">PAC</span> 
							<span class="period">Prazo de entrega: <strong>7 dias úteis</strong></span> 
							<span class="value">R$ 18,45</span>
						</label>
					</fieldset>
	*/
	
	

		
		
		
		initCorners();
		
		if($('a.highslide').size() || $('a.highslide-gallery').size()){
			hs.anchors = null;
			//$.include([LIB_DIR + '/jquery/plugins/highslide/files/highslide-with-gallery.packed.js',LIB_DIR + '/jquery/plugins/highslide/files/highslide.css']);
			
			$('a.highslide:not(.loaded),a.highslide-gallery:not(.loaded)').each(function(){
				$(this).addClass('loaded');
				
				var objA = $(this);
				var objIMG = $(this).find('img:eq(0)');
				var src = $(objIMG).attr('src')+'';
				src = src.replace('_0.','_2.');
				src = src.replace('_1.','_2.');
				
				
				
				
				var objNewImg = new Image();
				objNewImg.src = src;
				objNewImg.onerror = function(){
					$(objA).removeClass('highslide');
					$(this).remove();
				}
				
					
				var title = $(objIMG).attr('title')+'';
				//alert($(this).attr('href'))
				//$(this).attr('href',src);
				//$(this).attr('onclick','return hs.expand(this)');
				
				if(!$(this).attr('onclick')) {
					//$(this).attr('onclick',"return hs.expand(this,{ align: 'center', outlineType: 'rounded-white', captionOverlay: { position: 'rightpanel'} })");
					this.onclick = function() {
						return hs.expand(this,{ align: 'center', outlineType: 'rounded-white', captionOverlay: { position: 'rightpanel'}});
					};
					//$(this).attr('onclick',"alert('')");
				}
				
				/*
				
				//$(this).after('<div class="highslide-caption"><div class="boxcaption"><div style="padding: 2px 10px 5px 10px;"><h4>'+title+'</h4>You can open more than one image at a time, and arrange them on your screen by dragging them around. The captions can be positioned anywhere relative to the image.</div></div></div>');
				
				//return hs.expand(this, 			{wrapperClassName: 'wide-border', captionOverlay: { position: 'rightpanel'}})
				
				
				$(this).removeClass('highslide');
				$(this).removeClass('highslide-gallery');
				*/
				
				
				
				
			});
			
			
		}
		
		$('.__BNRTPL__SECOES_TOPNAV').each(function(){
			$(this).removeClass('__BNRTPL__SECOES_TOPNAV');
			var strResult = '';
			eval('var objParam = '+$(this).attr('param')+';');
			
			if(objParam.idsecao) {
				var arrSecoesTree = tree_secoes.get_pais(objParam.idsecao);
				var html = '';
				for(i2 in arrSecoesTree) {
					var idSecao = arrSecoesTree[i2];
					var nom_secao = tree_secoes.arrTreeResult[idSecao+""]['Nom_Secao'];
					var idSecaoPai = tree_secoes.arrTreeResult[idSecao+""]['idSecaoPai'];
					var Link = baseUrlModule + "produtos/lista/idsecao/" + idSecao;
					if(idSecaoPai+""!="") {
						Link = Link + '/idsecaop/' + idSecaoPai;
					}
					html += '<li><a href="'+Link+'">'+nom_secao+'</a></li>';
					//alert(nom_secao)
					// //alert(idSecao);
				}
				$(this).append('<div class="secoes_topnav inline"><div class="secoes_topnav_container"><ul><li class="first"><a href="" param="home">Home</a></li>'+html+'</ul></div></div>');
			}
			if(objParam.idproduto) {
				$(this).append('<div class="secoes_topnav inline"><div class="secoes_topnav_container"><span class="prodcat" param="'+objParam.idproduto+'"><ul><li class="first"><a href="" param="home">Home</a></li></ul></span></div></div>');
				/*
				var arrSecoes = globals_arrDadosDB['produtos_secoes'][objParam.idproduto+''];
				if(arrSecoes) {
					if(arrSecoes[0]) {
						var idSecao = arrSecoes[0];
						var arrSEC = filterArray(globals_arrDadosDB['secoes'],idSecao,'idSecao','=');
						strResult = '<a href="" param="home">Home</a> / <a href="" param="secao">'+arrSEC[0]['Nom_Secao']+'</a>'
						alert(arrSEC[0]['Nom_Secao']);
					}
				}
				*/
				
			}
		});
		
		
		
		
		$('.prodcat:not(.loaded)').each(function(){
			$(this).addClass('loaded');
			var boOK = true;
			try {
				globals_arrDadosDB['produtos_secoes'] = globals_arrDadosDB['produtos_secoes'];
			} catch(e) {
				boOK = false;
			}
			if(boOK) {
					var att_idProduto = $(this).attr('param');
					
					// var tree_secoes = new Tree(globals_arrDadosDB['secoes'],"idSecao,Nom_Secao,idSecaoPai");
					//tree_secoes.url = "";
					// tree_secoes.getTree();
					// var strLink = '';
					var html = '';
					var arrSecoes = globals_arrDadosDB['produtos_secoes'][att_idProduto];
					if(arrSecoes) {
						html += '';
						for(i in arrSecoes) {
							var idSecao = arrSecoes[i];
							var arrSecoesTree = tree_secoes.get_pais(idSecao);
							var strSep = '';
							html += '<li>';
							
							for(i2 in arrSecoesTree) {
								var idSecao = arrSecoesTree[i2];
								var nom_secao = tree_secoes.arrTreeResult[idSecao+""]['Nom_Secao'];
								var idSecaoPai = tree_secoes.arrTreeResult[idSecao+""]['idSecaoPai'];
								var Link = baseUrlModule + "produtos/lista/idsecao/" + idSecao;
								if(idSecaoPai+""!="") {
									Link = Link + '/idsecaop/' + idSecaoPai;
								}
								html += strSep + '<a href="'+Link+'">'+nom_secao+'</a>';
								strSep = ' <span class="sep">:</span> ';
								//alert(nom_secao)
								// //alert(idSecao);
							}
							html += '</li>';
						}
					}
					
					var objUL = $(this).find('ul').get(0);
					if(objUL) {
						$(objUL).append(html);
					} else {
						$(this).append('<ul>'+html+'</ul>');
					}
					
					
					
					$(this).removeClass('prodcat');
					$(this).addClass('prodcatloaded');
			}
		});
		
		
		$('.__BNRTPL__FOTOS:not(.loaded)').each(function(){
			var globals_arrFotos = globals_arrDadosDB['arrImagesDIR'];
			//var globals_arrFotos = globals_arrDadosDB['arrImagesDIR']['images_list'];
			
			
			$(this).addClass('loaded');
			$(this).addClass('images_list');
			
			var strParam = $(this).attr('param');
			eval('var objParam = '+strParam+';');
			
			
			var porpag = 3;
			if(objParam) {
				porpag = objParam.porpag;
			}
			
			
			
			
			var images_list = globals_arrFotos['images_list'];
			
			var images_group = globals_arrFotos['images_group'];
			
			var html = '';
			
			if(images_group) {
				$('.images_list').append('<ul></ul>');
				for(idx in images_group) {
					var row = images_group[idx];
					
					var pathP = row[0]['path'];
					var pathG = row[1]['path'];
					
					html += '<li class="images_list_dnone"><a href="'+pathG+'" class="highslide"><img src="'+pathP+'" alt="" title=" Click para ampliar " border="0" /></a></li>';
					
										
				}
			} else {
				$('.images_list').append('<ul></ul>');
				for(idx in images_list) {
					var row = images_list[idx];
					var path = globals_arrFotos['url'] + idx;
					
					html += '<li class="images_list_dnone"><img src="'+path+'" /></li>';
				}
			}
			
				
			$($('.images_list').find('ul').get(0)).append(html);
			$('.images_list').prepend('<div style="width:1px;height:1px;overflow:hidden;"><input type="text" id="focusimg"  /></div>');
			
			
			var total = $('.images_list ul:eq(0) li').size();
			
			if(total<=porpag) { $('.images_list_dnone').removeClass('images_list_dnone'); }
			var strPaging = '';
			var totalpag = Math.round(total/porpag);
			for(i=1;i<=totalpag;i++) {
				strPaging +='<a href="#'+i+'" param="'+i+'">'+i+'</a>';
			}
			$('.images_list ul:eq(0)').after('<div class="pagination">' + strPaging + '</div>');
			
			$('.pagination a').click(function(){
				var objFocus = $("#focusimg");
				objFocus.focus();
				$('.pagination a').removeClass('current');
				$(this).addClass('current');
				var pag = $(this).attr('param');
				var start = (porpag*(pag-1));
				
				var end = (porpag*pag)-1;
				$('.images_list ul:eq(0) li').addClass('images_list_dnone');
				//alert(start + ' = ' + end)
				for(i=start;i<=end;i++) {
					if(i>total)break;
					$('.images_list ul:eq(0) li:eq('+i+')').removeClass('images_list_dnone');
				}
				
				
				return false;
			});
			$('.pagination a:eq(0)').click();
		});
		
	}
	


	function monta__BNRTPL__VIDEOS() {
		$('.__BNRTPL__VIDEOS').each(function(){
			$(this).removeClass('__BNRTPL__VIDEOS');
			
			$(this).removeClass('__BNRTPL__VIDEOS_LOADED');
			$(this).addClass('__BNRTPL__VIDEOS_LOADED');
			
			$strClass = $(this).attr('class')+'';
			eval('var param = '+$(this).attr('param')+';');
			var param = !param?'':param;
			
			
			$arrClass = $strClass.split(' ');
			
			var idxLayout = 'padrao';
			for(idx in $arrClass) {
				var strClass = $arrClass[idx];
				if(arrLayouts['videos'][strClass]) {
					idxLayout = strClass;
					break;
				}
			}
			
			var arrDATA = new Array();
			arrDATA['dados'] = new Array();
			if(param.data) {
				arrDATA['dados'] = arrDados[param.data];
			} else {
				switch(idxLayout+'') {
					default :
							arrDATA['dados'] = globals_arrDadosDB['videos'];
						break;
				}
			}
			
			

			arrDATA['tpl'] = arrLayouts['videos'][idxLayout];
			
			var arrDATA_NEW = new Array();
			arrDATA_NEW['tpl'] = arrDATA['tpl'];
			arrDATA_NEW['dados'] = new Array();
			var count=0;
			

			
			if(!arrDATA['dados'][0] && $(arrDATA['dados']).size()) {
				for(iLoop in arrDATA['dados']) {
					arrDATA_NEW['dados'][count] = arrDATA['dados'][iLoop];
					count++;
				}
				var objV = new pagingArrayData(this,arrDATA_NEW);
			} else {
				var objV = new pagingArrayData(this,arrDATA);
			}
			
			objV.setDataType('video');
			objV.create();
			
		});
	}
	function monta__BNRTPL__FORMCONTATO() {
		$('.__BNRTPL__FORMCONTATO').each(function(){
			$(this).removeClass('__BNRTPL__FORMCONTATO');
			$(this).removeClass('__BNRTPL__FORMCONTATO_LOADED');
			$(this).addClass('__BNRTPL__FORMCONTATO_LOADED');
			
			var objFormContent = $(this);
			
			var urlFomContato = baseUrlModule + 'contato/form-contato';
			
			var html = '';
			html+='						<form class="form_contato" action="'+urlFomContato+'" method="post">';
			html+='							<div class="wrap-input required">';
			html+='								<label for="nome">Nome:</label>';
			html+='								<input type="text" name="nome" title="Nome" class="inputText input-text" />';
			html+='							</div>';
			html+='							<div class="wrap-input required">';
			html+='								<label for="email">E-mail:</label>';
			html+='								<input type="text" name="email" title="E-mail" class="inputText input-text" size="10" maxlength="100" value="" type="text" />';
			html+='							</div>';
			html+='							<div class="wrap-input">';
			html+='								<label for="telefone">Telefone:</label>';
			html+='								<input type="text" id="telefone" name="telefone" title="Telefone" class="inputText input-text" size="10" maxlength="100" value="" />';
			html+='							</div>';
			html+='							<div class="wrap-input required">';
			html+='								<label for="mensagem">Mensagem:</label>';
			html+='								<textarea id="mensagem" name="mensagem" class="inputTextarea" title="Mensagem" rows="8" cols="21"></textarea>';
			html+='							</div>';
			html+='							<div class="wrap-input">';
			html+='								<label>&nbsp;</label>';
			html+='								<input type="submit" class="submit input input-submit" value="enviar" />';
			html+='							</div>';
			html+='						</form>';
			html+='';
			
			
			
			$(objFormContent).append(html);
			var objTel = $(objFormContent).find('#telefone').get(0);
			if($(objTel).is('input')) {
				$(objTel).mask('(99) 9999-9999');
			}
			
			$($(objFormContent).find('.form_contato').get(0)).submit(function(){
					var html = '';
					var boOk = true;
					var objFormContato = $(this);					
					$(this).find('input,select,textarea').each(function(){
						if(!$(this).is('input[type=button]') && !$(this).is('input[type=submit]')) {
							var label = $(this).attr('title');
							var valor = $(this).val();
							var objParent = $(this).parent('.wrap-input').get(0);
							var required = $(objParent).is('.required');
							if(required) {
								if(valor+''=='') {
									jAlert('O campo <b>"' + label + '"</b> é obrigatório e deve ser preenchido!');
									$(this).focus();
									boOk = false;
									return false;
								}
							}
							html+='<p><b>'+label+'</b>: <br />' + valor + '</p>';
						}
					});
					if(boOk) {
						var objMsg = $(objFormContato).find('#mensagem').get(0);
						var val = $(objMsg).val()+'';
						var size = val.length;
						var max = 2000;
						if(size>max) {
								var valNew = val.substring(0,max);
								$(this).val(valNew);
								jAlert('Sua mensagem deve conter no máximo <b>'+max+'</b> caracteres!<br /><br />Você informou <b>'+size+'</b>, <b>'+(size-max)+'</b> a mais.');
							return false;
						}
						
						var post = '';
						post+= $(objFormContato).serialize();
						post+= '&html='+escape(html);
						
						setAsync(true);
						$(objFormContato).block({message:'enviando...'});
						$.post(urlFomContato,post,function(a,b){
							if(a+''=='1') {
									jAlert('<font color="darkgreen">Email enviado com sucesso!</font>');
									$(objFormContato).find('input[type=checkbox],input[type=radio],input[type=text],textarea,select').val('');
									$(objFormContato).unblock();
								return false;
							} else {
								jAlert('<font color="red">Não foi possível enviar sua mensagem!</font><br/><br/>Tente outra forma de contato.');
							}
							$(objFormContato).unblock();
						})
					}
					
					
					
				return false;
			});

		});
	}
	function monta__BNRTPL__PRODUTOS() {
		$('.__BNRTPL__PRODUTOS').each(function(){
			$(this).removeClass('__BNRTPL__PRODUTOS');
			
			$(this).removeClass('__BNRTPL__PRODUTOS_LOADED');
			$(this).addClass('__BNRTPL__PRODUTOS_LOADED');
			
			
			$strClass = $(this).attr('class')+'';
			eval('var param = '+$(this).attr('param')+';');
			var param = !param?'':param;
			
			
			$arrClass = $strClass.split(' ');
			
			var idxLayout = 'padrao';
			for(idx in $arrClass) {
				var strClass = $arrClass[idx];
				if(arrLayouts['produtos'][strClass]) {
					idxLayout = strClass;
					break;
				}
			}
			
			
			$strSeparator = '';
			var arrDATA = new Array();
			if($(this).is('[class*=lancamentos]')) {
				// arrDATA['dados'] = globals_arrDadosDB['produtos_lancamentos'];
				// arrDATA['tpl'] = arrLayouts['tplProdutoSidebarLancamento'];
			} else {
				//arrDATA['tpl'] = arrLayouts['tplProduto'];
			}
			
			arrDATA['dados'] = new Array();
			if(param.data) {
				arrDATA['dados'] = arrDados[param.data];
			} else {
				switch(idxLayout+'') {
					case 'sidebarlancamento' :
							arrDATA['dados'] = arrDados['produtos_lancamentos'];
						break;
					case 'detalhe' :
							arrDATA['dados'] = arrDados['produtos'];
						break;
					default :
							arrDATA['dados'] = arrDados['produtos'];
						break;
				}
			}
			
			
			
			

			arrDATA['tpl'] = arrLayouts['produtos'][idxLayout];
			
			
			
			var arrDATA_NEW = new Array();
			arrDATA_NEW['tpl'] = arrDATA['tpl'];
			arrDATA_NEW['dados'] = new Array();
			var count=0;
			
			
			if(!arrDATA['dados'][0] && $(arrDATA['dados']).size()) {
				for(iLoop in arrDATA['dados']) {
					arrDATA_NEW['dados'][count] = arrDATA['dados'][iLoop];
					count++;
				}
				var objP = new pagingArrayData(this,arrDATA_NEW);
			} else {
				var objP = new pagingArrayData(this,arrDATA);
				
			}
			
			
			if(param.rowsPerPage) 	objP.rowsPerPage 	= param.rowsPerPage;
			if(param.maxPages) 		objP.maxPages 		= param.maxPages;
			if(param.offset) 		objP.offset 		= param.offset;
			if(param.rowCount) 		objP.rowCount 		= param.rowCount;
			
			objP.create();
			if($(this).find('.maincontent').is(':empty')) {
				objP.showData('1'); 
			}
			objP.printPagination();
			// $(this).removeClass('__BNRTPL__PRODUTOS');
			$('.aimg.loaded:not(.loadederror)').each(function(){
				$(this).addClass('loadederror');
				var href = $(this).attr('href')+'';
				if(href.indexOf('.null')!=-1) {
					var objIMG = $(this).find('img').get(0);
					$(this).after('<img src="'+IMG_DIR+'/no-image.jpg" />');
					$(this).remove();
				}
				
			});
			
			$('.__BNRTPL__PRECOBOX').each(function(){
					$(this).removeClass('__BNRTPL__PRECOBOX');
					eval('var objParam = ' + $(this).attr('param') + ';');
					if(objParam) {
						var idProduto = objParam.idproduto;
						var result = filterArray(arrDados['produtos'],idProduto,'idProduto','=');
						if(result) {
							var row = result[0];
							var clsProduto = new AbstractProduto();	
							clsProduto.setFromArray(row);
							var html='';
							html+='<div class="price-info corner">';
							html+='	<div class="price-info-container">';
							if(clsProduto.boComprar()) {
								html+='		<div class="boxcomprar"><div class="comprar corner" param="{radius:6}"><a href="" param="comprar" rel="{idproduto:'+clsProduto.GetID()+'}">Comprar</a></div></div>';
							}
							html+='		<div class="preco">'+clsProduto.GetPrecoFormated()+'</div>';
							html+='	</div>';
							html+='</div>';
							$(this).append(html);
						}
					}
			});
			$('.__BNRTPL__INDISPONIVEL').each(function(){
				$(this).removeClass('__BNRTPL__INDISPONIVEL');
				eval('var objParam = ' + $(this).attr('param') + ';');
				if(objParam) {
					var idProduto = objParam.idproduto;
					var result = filterArray(arrDados['produtos'],idProduto,'idProduto','=');
					if(result) {
						var row = result[0];
						var clsProduto = new AbstractProduto();	
						clsProduto.setFromArray(row);
						
						if(!clsProduto.boComprar()) {
							var html = '';
							html+='<div class="boxdisponivel">';
							html+='<div class="boxdisponivel_container">';
							html+='	<form id="form_aviseme" action="">';
							html+='		<fieldset>';
							html+='			<p class="tit">Avise-me quando estiver disponível:</p>';
							html+='			<div class="wrap-input"><label>Nome:</label><input type="text" class="input input-text f_av_nome" name="nome" value="" class="input input-text" /></div>';
							html+='			<div class="wrap-input"><label><b>E-mail:</b></label><input type="text" class="input input-text f_av_email" name="email" value="" class="input input-text" /></div>';
							html+='			<div class="wrap-input"><label>Comentários:</label><textarea class="f_av_comentarios" name="comentarios"></textarea></div>';
							html+='			<div class="wrap-input">';
							html+='				<label>&nbsp;</label>';
							html+='					<div class="ofertas">';
							html+='						<input type="checkbox" checked="checked" value="1" name="chk_receberOfertas" id="chk_receberOfertas"> ';
							html+='						<small>Desejo receber ofertas no meu e-mail</small>';
							html+='					</div>';
							html+='			</div>';
							html+='			<div class="wrap-input"><label>&nbsp;</label><input type="submit" value="Enviar" class="input input-button" /></div>';
							html+='		</fieldset>';
							html+='	</form>';
							html+='</div>';
							html+='</div>';
							
							$(this).append(html);
							$('#form_aviseme').submit(function(){
									var objF = $(this);
									var objN = $(objF).find('.f_av_nome').get(0);
									var objE = $(objF).find('.f_av_email').get(0);
									var objC = $(objF).find('.f_av_comentarios').get(0);
									
									var vn = $(objN).val()+'';
									var ve = $(objE).val()+'';
									var vc = $(objC).val()+'';
									
									if($(objE).val()+''=='') {
											jAlert('Precisamos do seu E-mail para contacta-lo!');
										return false;
									}
									
									var idproduto = requestJSON['idproduto'];
									
									var url = baseUrlModule + 'actionpub/enviaremail/acao/disponibilidade/';
									var vChk = $('#chk_receberOfertas').is(':checked')?'1':'';
									var strPost = 'nome='+vn+'&email='+ve+'&comentarios='+vc+'&idproduto='+idproduto+'&receberofertas='+vChk;
									
									$.post(url,strPost,function(resp){
										jAlert('Dados gravados com sucesso!');
										$(objN).val('');
										$(objE).val('');
										$(objC).val('');
										$('#chk_receberOfertas').attr('checked','checked');
										//$('#msgformdisp').remove();
										//$(objF).append('<div id="msgformdisp"><font color="green">Aguarde aviso de disponibilidade em seu email!</font></div>');
									});
									
								
								return false;
							});
						}
					}
				}
				
			});
			
			bnrtpl_loadBoxCalcFrete();
			
			$('.descricao:not(.loaded)').each(function(){
				$(this).addClass('loaded');
				$(this).find('p:empty,li:empty,ul:empty').remove();
				$(this).find('a:not(.loaded)').each(function(){
					var href = ($(this).attr('href')+'').toLowerCase();
					var onclick = $(this).attr('onclick')+'';
					var dominioAUX = (DOMINIO+'').toLowerCase();;
					if(href.indexOf('javascript')==-1 && href.indexOf('http://')!=-1 && href.indexOf(dominioAUX)==-1) {
						$(this).attr('target','_blank');
						$(this).addClass('loaded');
					}
				});
				
				//$('.boxpag').remove();
				
				// $(this).find('img:not(.loaded)').each(function(){
					// var src = ($(this).attr('src')+'').toLowerCase();
					// var dominioAUX = (DOMINIO+'').toLowerCase();
					// if(src.indexOf('http://')==-1 && src.indexOf(dominioAUX)==-1) {
						// $(this).addClass('loaded');
						// var srcNew = 'http://www.lge.com/' + src;
						// $(this).attr('src',srcNew);
					// }
				// });
				
			});
			
		});
	}
	
	
	function callTimeoutFN() {
		loadSettings();
	}
	setInterval('callTimeoutFN()',700);
	
	
	
	
  function initCorners() {
	if($('.corner').size()) {
		var settings = {
		  tl: { radius: 10 },
		  tr: { radius: 10 },
		  bl: { radius: 10 },
		  br: { radius: 10 },
		  antiAlias: true
		}
		
		$('.corner').each(function(){
			eval('var objParam = '+$(this).attr('param')+';');
			if(objParam) {
				if(objParam.radius) {
					settings.tl['radius'] = objParam.radius;
					settings.tr['radius'] = objParam.radius;
					settings.bl['radius'] = objParam.radius;
					settings.br['radius'] = objParam.radius;
				}
			}
			
			curvyCorners(settings, this);
			$(this).removeClass('corner');
		});

		// curvyCorners(settings, ".corner");
		// $('.corner').removeClass('corner');
	}
    if($('.cornertop').size()) {
		var settings = {
		  tl: { radius: 10 },
		  tr: { radius: 10 },
		  antiAlias: true
		}
		
		$('.cornertop').each(function(){
			curvyCorners(settings, this);
			$(this).removeClass('cornertop');
		});

		
		//$('.corner').removeClass('cornertop');
		//$('.corner').removeClass('cornertop');
	}
	
    if($('.cornerbottom').size()) {
		var settings = {
		  bl: { radius: 10 },
		  br: { radius: 10 },
		  antiAlias: true
		}
		
		$('.cornerbottom').each(function(){
			curvyCorners(settings, this);
			$(this).removeClass('cornerbottom');
		});

		// curvyCorners(settings, ".cornerbottom");
		// $('.corner').removeClass('cornerbottom');
	}
  }
  
  
  
	function timeLoadFotos() {
		$('.BNR_FOTOS').html('');
		$('.BNR_FOTOS').addClass('__BNRTPL__FOTOS').removeClass('BNR_FOTOS');
		
	}
	
  $(document).ready(function(){
		initCorners();
		setTimeout('timeLoadFotos()',2000);
		loadChat();
  });
  
  
var timeCEP = 0;
var intervalCEP = 0;
function timeoutCEP() {
	timeCEP = 0;
	intervalCEP = setInterval('verificaTimeCEP()',1000);
}
function verificaTimeCEP() {
	if(timeCEP<10) {
		addTimeCEP();
	} else {
		clearInterval(intervalCEP);
		jAlert('Problemas na conexão! Não foi possivel calcular o frete!');
		try{
			window.stop();
		} catch(e) {
			return false;
		}
	}
}
function addTimeCEP() {
	timeCEP+=1;
}
