function replaceAll(string, token, newtoken) {
	while (string.indexOf(token) != -1) {
 		string = string.replace(token, newtoken);
	}
	return string;
}

function escapeHTML(str)
{
   var div = document.createElement('div');
	div.innerHTML = str;
	return div.innerHTML;
}

$(function() { 		
	$(".referencia_produto:contains('[c]titulo_fabricante_idioma[/c]')").hide();
});

function AjaxPageLoad()
{
	sis_opcoes_form_carregar();

	$("li[id^='aba_']").removeClass("aba_on");
	$("div[id^='box_']").hide();
	
	$("li[id^='aba_']:first").addClass("aba_on");
	$("div[id^='box_']:first").show();
	
	$(".opiniao_titulo > img, #nota_geral > img").addClass("opaco");
	$("#nota_geral > input, .opiniao_titulo > input").each(function() 
	{ 
		var index = $(this).val()-1;
		//alert(index);
		
		var campo = $(this).nextAll("img").eq(index);
		$(campo).prevAll($(this).nextAll("img")).removeClass("opaco");
		$(campo).removeClass("opaco");
	});
	
	
	
	
	
	//PERGUNTAS
	if (flg_pergunta == "0")
		$("#aba_perguntas, #box_perguntas").hide();
	else
	{
		$("#aba_perguntas").show();
		if (flg_pergunta == "2" && cod_cliente == "[c]cod_cliente_contexto[/c]")
			$(".btn_fazer_pergunta").attr("href", link_login + "?cnt=" + chave_contexto + "&html=login&target=" + replaceAll(document.location.href, "&", ";"));
	}
	//$("#fazer_pergunta").hide();
	
	if (cod_cliente != "[c]cod_cliente_contexto[/c]")
	{
		$("#pergunta_nome, #pergunta_email").attr("disabled", "true");
		$("#pergunta_nome, #pergunta_email").css("background-color", "#efefef");
	}
	else
		$("#pergunta_nome, #pergunta_email").val("");
		
		
	$("#pergunta_nome, #pergunta_email, #pergunta_texto, #avaliacao_texto").blur(function ()
	{
		if ($(this).val() == "" )
			$($(this).attr("msg")).html(escapeHTML($(this).attr("title")));
		else
			$($(this).attr("msg")).empty();

		if ($(this).is("#pergunta_email") && $(this).val() != "")
		{
			if(!validarEmail($(this).val()))
				$($(this).attr("msg")).html(escapeHTML("Informe um e-mail v&aacute;lido."));
		}
	});	
	
	
	

	//AVALIAÇÕES
	if (flg_avaliacao == "0")
		$("#aba_opinioes, #box_opinioes").hide();
	else 
	{
		$("#aba_opinioes").show();
		if (cod_cliente == "[c]cod_cliente_contexto[/c]")
		  $(".btn_fazer_avaliacao").attr("href", link_login + "?cnt=" + chave_contexto + "&html=login&target=" + replaceAll(document.location.href, "&", ";"));
	}
	$("#dar_opiniao").hide();
	
	aval = $(".lista_opinioes > li").length;
	//alert(aval);
	if (aval == 0)
		$(".avaliacao_geral_qtde").html(escapeHTML("Nenhuma avalia&ccedil;&atilde;o dispon&iacute;vel."));
	else if (aval == 1)
		$(".avaliacao_geral_qtde").html(escapeHTML("1 avalia&ccedil;&atilde;o."));
	else
		$(".avaliacao_geral_qtde").html(escapeHTML(aval + " avalia&ccedil;&otilde;es"));
		
	$("#sem_avaliacao").each(function () {
		$(".avaliacao_geral_qtde").html(escapeHTML("Produto ainda n&atilde;o avaliado."));
		$("#nota_geral > input").val(0);
	});
	
	$("#js_btnAvaliar").click(function () 
	{
		$("#txbTitulo").val($("#js_txbTitulo").val());
		$("#btnAvaliar").click();
		$("#rfvTitulo:visible").each( function () { $("#js_rfvTitulo").show();});

	});	
	
	//alert($("#nota_geral > input").val());
	$("#estrelas > img").each(function()
	{
		$(this).css("cursor", "pointer");
		$(this).addClass("opaco");
		$(this).mouseover(function()
		{
			$(this).prevAll($("#estrelas > img")).removeClass("opaco");
			$(this).removeClass("opaco");
		});
		
		$(this).mouseup(function()
		{
		  $("#avaliacao_nota").val($("#estrelas > img").index($(this))+1);
		  $("#validacao_nota").empty();
		});
		
		$(this).mouseout(function()
		{
			$("#estrelas > img").addClass("opaco");
			var index = $("#avaliacao_nota").val();
			if (index != 0)
				$("#estrelas > img").eq(index-1).mouseover();
		});
	});
	
	
	//.NET
	//$("#dot_net_components").hide();


    //????????
	$("#js_rfvTitulo").text($("#rfvTitulo").text());
	$("#rfvTitulo:visible").each( function () {$("#js_rfvTitulo").show()});
	$("#rfvTitulo:hidden").each( function () {$("#js_rfvTitulo").hide()});
	
	
	//BOTÃO COMPRAR
	if (finalidade == "3")
	{
		$(".btn_comprar").hide();
		$(".box_pagamento_produto").find("img:eq(0)").hide();
	}
	else
	{
		$(".btn_comprar").show();
		$(".box_pagamento_produto").find("img:eq(0)").show();
	}
	
	$("#js_btnComprar").css("cursor", "pointer");
	$("#js_btnComprar").click(function () {
		
		if (sis_opcoes_form_validar())
			if (!($("#check_contrato").is(":hidden") || $("#check_contrato").is(":checked")))
				alert(escapeHTML("Voc&ecirc; deve aceitar os termos e condi&ccedil;&otilde;es de aquisi&ccedil;&atilde;o deste produto."));
			else
			{
				strOpcoes = "";
				strErro = "";
				$(".produto_opcao").each(function(){
					   
					var opcao = $(this).children("input:first").val();
					$(this).children("table").children("tbody").children("tr").each(function(){
	
						var produto = $(this).children(".componente").children("input:first").val();
						qtdeItem = parseInt($("#qtdeItem_" + produto).val(), 10);
								
								if (qtdeItem > 0)
									strOpcoes += ";"+produto +"-"+qtdeItem;
	
					});
	
					maxOpcao = $("#maxOpcao_" + opcao).val();
					minOpcao = $("#minOpcao_" + opcao).val();
					qtdeTot  = $("#qtdeTotalItem_" + opcao).val();
	
					intMinOpcao = parseInt(minOpcao);
					intMaxOpcao = parseInt(maxOpcao);
	
					desc = $(this).children(".lista_opcao_titulo").text();
	
					if (qtdeTot > intMaxOpcao)
					{
						desc = "A quantidade escolhida para a opção '"+ desc +"' tem que ser menor que "+qtdeTot;
						strErro += desc + "\n";
					}
					else
					{
						if (qtdeTot < intMinOpcao)
						{
							desc = "A quantidade escolhida para a opção '"+ desc +"' tem que ser maior que "+qtdeTot;
							strErro += desc + "\n";
						}
					}
			
				});
	
				if (strErro != "")
				{
					alert(strErro);
					$(".produto_opcao_item > .componente > input:visible:first").focus();
				}
				else
				{
					if (strOpcoes != "")
						strOpcoes = strOpcoes.substring(1);
	
					$("#txbOpcoes").val(strOpcoes);
					$("#txbValor").val($("#hdfValorTotal").val());
	
					$("#txbQtde").val($("#js_txbQtde").val());
					
					$("#btnComprar").click();
				}
				
				
			}
	});
	
	
	
	
	
	
	//IMAGENS
	$(".box_foto_produto > li > img:first").each( function() 
	{
		$(this).click(function() { $(".imagens_galeria_menores > a:first").click();});
		$(this).css("cursor", "pointer");
	});
	
	if ($(".imagens_galeria_menores > a").length > 1)
		$(".imagens_galeria_menores").show();
	
	//if ($(".imagens_galeria_menores > a").length < 2)
		//$(".imagens_galeria_menores").hide();
		
	fotosrc = $("#foto_produto").attr("src");
	if (fotosrc.indexOf("[/c]") == -1)
	{
		$(".imagem_ilustrativa").show();
		$(".imagens_ampliar").show();
	}
	else
		$("#foto_produto").attr("src", caminho_virtual + "/html/images/icones/noimage.gif"); 
		
	//$("#foto_produto[src$='[/c]']").each(function()
	//{
	//	$(this).attr("src", caminho_virtual + "/html/images/icones/noimage.gif"); 
		//$(".imagem_ilustrativa").hide();
		//$(".imagens_ampliar").hide();
	//}); 
	
			
	//PAGAMENTO
	$(".box_parcelas").each(function()
	{
		$(this).css("position", "absolute");
		$(this).css("z-index", "99999");
		$(this).hide();
		$(this).mouseover(function() { $(this).show()});
		$(this).mouseout(function() { $(this).hide()});
	});
	
	
	
	//DISPONIBILIDADE
	if (qtde_estoque == "")
		qtde_estoque = "0";
	
	if ((valor_exibir == "1" || valor_exibir == "2") && (situacao_estoque == "1"))
	{
		$(".box_valor_produto").show();
		$(".box_indisponivel").hide();
		$("#formas_pagtos > img").each( function() 
		{
			$(this).mouseover(function() 
			{ 
				var topx = $(".topo").height();
				var leftx = $("#esquerda").width() + 15;
				var index = $("#formas_pagtos > img").index($(this));
				var offset = $(this).offset();
				$(".box_parcelas").eq(index).css("left", offset.left - leftx);
				$(".box_parcelas").eq(index).css("top", offset.top + $(this).height() - topx);
				$(".box_parcelas").eq(index).show();
			});
			
			$(this).mouseout(function() { $(".box_parcelas").hide();});
			$(this).css("cursor", "pointer");
			$(".box_pagamento_produto").find("img:eq(0)").show();
		});
	}
	else
	{
		$(".box_valor_produto").hide();
		$(".vizualizar_parcelamento").hide();
		$(".box_pagamento_produto").find("img:eq(0)").hide();
		switch(valor_exibir)
		{
			case "3":
				$(".texto_indisponovel").html("Valor sob consulta");
				$(".texto_indisponovel").show();
				$(".box_indisponivel").show();
				break;
			case "0":
				$(".box_indisponivel").hide();
				break;
			default:
				$(".texto_indisponovel").show();
				$(".box_indisponivel").show();
		}			
	}	
	
	
	//VALORES
	//$(".valor_de:contains('[c]'), .valor_parcelado_detalhe:contains('[c]')").hide();
	$(".valor_de, .valor_parcelado_detalhe").each(function()
	{
		if (!$(this).is(":contains('[c]')"))
	  		$(this).show();
	});
	//$(".valor_parcelado_detalhe:visible").each(function() {$(".valor_por_grande").hide();});
	$(".valor_parcelado_detalhe:hidden").each(function() {$(".valor_por_grande").show();});
	//$(".valor_por_grande:visible").each(function() {$(".valor_por").hide();});
	$(".valor_por_grande:hidden").each(function() {$(".valor_por").show(); });
	
	$(".valor_de, .valor_por, .valor_parcelado_detalhe, .valor_por_grande").each( function ()
	{
		if ($(this).find("span").is(":empty") || $(this).find("span").is("contains('[/c]')"))
			$(this).hide();
	});

	
	
	
	//CONTRATO
	if (!$("#contrato_texto").is(":empty"))
		$("#link_contrato").show();
			
	//$("#fundo_modal").hide();	
	//$("#box_contrato").hide();
	
	$("#fundo_modal").click( function() 
	{
		$(this).fadeOut("normal");
		$("#box_contrato").hide();
		$("embed").show();
									  
	});
	
	$(".btn_fechar_lyteshop").click( function() 
	{
		$(this).hide();
		$("#box_contrato").hide();
		$("#fundo_modal").fadeOut("normal");
		$(".btn_fechar_lyteshop").show();
		$("embed").show();
	});

	//INICIO CARREGA OPÇÕES DO PRODUTO.
	$(".produto_opcao").each(function(){
	
		$("#lista_opcoes").show();
		$("#lista_opcoes").prev(".abas").show();
		
		var opcao = $(this).children("input:first").val();

		maxOpcao = $("#maxOpcao_" + opcao).val();
		minOpcao = $("#minOpcao_" + opcao).val();

		intMinOpcao = parseInt(minOpcao);
		intMaxOpcao = parseInt(maxOpcao);

		if(isNaN(intMinOpcao)) 
		{
			minOpcao = 0;
			$("#minOpcao_" + opcao).val(minOpcao);
		}
		
		if(isNaN(intMaxOpcao)) 
		{
			maxOpcao = 999999;
			$("#maxOpcao_" + opcao).val(maxOpcao);
		}

		calcOpcao = $("#calcOpcao_" + opcao).val(); 
		desc = "";
		if ( minOpcao == maxOpcao )
		{
			if (minOpcao == 1)
				desc += " (Selecione "+minOpcao+" opção)";
			else
				desc += " (Selecione "+maxOpcao+" opções)";
		}
		else
		{
			if (minOpcao == 0)
			{
				if (maxOpcao == 1)
					desc += " (Selecione "+maxOpcao+" opção)";
				else
					desc += " (Selecione até "+maxOpcao+" opções)";	
			}
			else
			{
				desc += " (Selecione de "+minOpcao+" a "+maxOpcao+"  opções)";
			}
		}

		if ((calcOpcao == "1") && (maxOpcao > 1))
			desc += " Valor é igual ao maior valor dos sub-produtos incluídos";

		$(this).children(".lista_opcao_titulo").next("span").text("");
		$(this).children(".lista_opcao_titulo").next("span").append(desc);
//		$(this).children("h3").children("span").append(desc);
					
	});

	$(".produto_opcao_item").each(function(){
		var produto = $(this).children(".componente").children("input:first").val();
		var valorItem = $("#valorItem_" + produto).val();
		var minItem = $("#minItem_" + produto).val();
		var maxItem = $("#maxItem_" + produto).val();
		var situacao = $("#situacao_" + produto).val();

		var opcao = $(this).parents(".produto_opcao").children("input:first").val();
		maxOpcao = $("#maxOpcao_" + opcao).val();
		minOpcao = $("#minOpcao_" + opcao).val();

		
		intMinItem = parseInt(minItem);
		intMaxItem = parseInt(maxItem);

		if(isNaN(intMinItem)) 
		{
			minItem = 0;
			$("#minItem_" + produto).val(0);
		}
		
		if(isNaN(intMaxItem)) 
		{
			maxItem = maxOpcao;
			$("#maxItem_" + produto).val(maxItem);
		}
		

		var escolhaItem = $("#escolhaItem_" + produto).val();

		var comp = produto;

		if (situacao == 0)
		{
			$(this).children(".disponibilidade").html('<strong style="color:#FF0000;">N&Atilde;O DISPON&Iacute;VEL</strong>');
		}
		else if (maxOpcao == 1)
		{
			if ((minOpcao == 0) && ($(".produto_opcao_item").length == 1))
			{
				$(this).children(".componente").append('<input type="checkbox" id="chkOpcao_' + comp + '" name="chkOpcao_' + opcao + '" value="' + produto + '">');
			}
			else
			if (escolhaItem == 1)
			{				
				$(this).children(".componente").append('<input type="radio" id="rdoOpcao_' + comp +  '" name="rdoOpcao_' + opcao + '" value="' + produto + '" checked="checked">');
				$("#qtdeItem_"+produto).val(1);	
			}
			else
				$(this).children(".componente").append('<input type="radio" id="rdoOpcao_' + comp +  '" name="rdoOpcao_' + opcao + '" value="' + produto + '">');

			
		}
		else if (maxItem == 1)
		{
			if (escolhaItem == 1)
			{
				$(this).children(".componente").append('<input type="checkbox" id="chkOpcao_' + comp + '" name="chkOpcao_' + opcao + '" value="' + produto + '" checked="checked">');
				$("#qtdeItem_"+produto).val(1);
			}
			else
				$(this).children(".componente").append('<input type="checkbox" id="chkOpcao_' + comp + '" name="chkOpcao_' + opcao + '" value="' + produto + '">');
		}
		else
		{
			$(this).children(".componente").append('<input type="text" id="txtOpcao_' + comp + '" name="txtOpcao_' + comp + '" value="' + minItem + '">');
			$(this).children(".componente").append('<input type="hidden" id="txtOpcaoOld_' + comp + '" name="txtOpcaoOld_' + comp + '" value="' + minItem + '">');
			$("#qtdeItem_"+produto).val(minItem);
		}
		

	//
	});
	
	

	$(".produto_opcao").each(function(){
		calcularValorOpcao(this);
		var opcao = $(this).children("input:first").val();

		valorSoma = $("#somaItensHidden_" + opcao).val();
		if (valorSoma == 0)
		{
			$(this).children("table").children("tbody").children("tr").children(".valor").hide();
		}
		

	});

	$(".componente").children("input[type='radio']").each(function()
	{
	//	setarValorRadio(this);
		var opcao = $(this).parents(".produto_opcao").children("input:first").val();
		valorSetado = $("#valorOpcao_" + opcao).val();
			
		produto = $(this).parent().children("input:first").val();

		valorItem = parseFloat($("#valorItem_" + produto).val().replace(",","."));

		valor = valorItem - valorSetado;

		$(this).parents(".produto_opcao_item").children(".valor").text(formatarValor(valor, 'F'));

		$("#valorItem_" + produto).val(valor);
	});

	$(".produto_opcao").each(function(){
		var opcao = $(this).children("input:first").val();
		$("#valorOpcaoInicial_" + opcao).val($("#valorOpcao_" + opcao).val());
		$("#valorOpcao_" + opcao).val("0");
	});

	//Fim Carrega Opções do produto.

	$(".componente").children("input[type='radio']").click(function() { 

			produto = $(this).parent().children("input:first").val();
			valorItem = parseFloat($("#valorItem_" + produto).val());
	
			var opcao = $(this).parents(".produto_opcao").children("input:first").val();
			valorAnterior = parseFloat($("#valorOpcao_" + opcao).val());

			$("#valorOpcao_" + opcao).val(valorItem);

			$(".componente").children("input[type='radio']").each(function()
			{
				var opcao = $(this).parents(".produto_opcao").children("input:first").val();
				valorSetado = $("#valorOpcao_" + opcao).val();
				$("#qtdeTotalItem_" + opcao).val(1);
					
				produto = $(this).parent().children("input:first").val();

				valorItem = parseFloat($("#valorItem_" + produto).val().replace(",","."));

				valor = valorItem - valorSetado;

				$(this).parents(".produto_opcao_item").children(".valor").text(formatarValor(valor, 'F'));

				if (this.checked)
				{
					$("#qtdeItem_" + produto).val("1");
				}
				else
				{
					$("#qtdeItem_" + produto).val("0");
				}


			});

			somarValorProduto();

	});

	$(".componente").children("input[type='checkbox']").click(function() { 

		produto = $(this).parent().children("input:first").val();
                
		if (this.checked)
		{
			$("#qtdeItem_" + produto).val("1");
		}
		else
		{
			$("#qtdeItem_" + produto).val("0");
		}
		
		$(this).parents(".produto_opcao").each(function(){
			calcularValorOpcao(this);
		});

		somarValorProduto();
			
	});

	
	$(".componente").children("input[type='text']").blur(function() { 

		produto = $(this).parent().children("input:first").val();
	
		valAtual = $(this).val();

		minValor = parseInt($("#minItem_" + produto).val());
		maxValor = parseInt($("#maxItem_" + produto).val());
		valorAntigo =  $("#txtOpcaoOld_" + produto).val();
		
		if (valAtual == "")
		{
			valAtual = 0;
			$(this).val(valAtual);		
		}

		
		intValAtual = parseInt(valAtual);
		
		if(isNaN(intValAtual)) 
		{
			valAtual = $("#txtOpcaoOld_" + produto).val();
			$(this).val(valAtual);
			intValAtual = parseInt(valAtual);
		}


		if (minValor > intValAtual)
		{
			alert("O Valor mínimo para essa opção é "+minValor);
			$(this).val(valorAntigo);
			$(this).focus();
		}
		else
		{
			if (maxValor < intValAtual)
			{
				alert("O Valor máximo para essa opção é "+maxValor);
				$(this).val(valorAntigo);
  				$(this).focus();
			}
			else
			{
				$("#qtdeItem_" + produto).val(valAtual);
				$("#txtOpcaoOld_" + produto).val(valAtual);

				$(this).parents(".produto_opcao").each(function(){
					calcularValorOpcao(this);
				});

				somarValorProduto();
			}

		}
	});

	$(".lista_opcao_tabela > tbody").children("tr:odd").addClass("lista_opcao_faixa");		
	
	$("img[src$='_']").hide();
	
	if ($("#lista_relacionados > .vitrine").length > 0)
	{
    	$("#lista_relacionados").prev("ul").show();
	    $("#lista_relacionados").show();
	}

} //fim do ajaxloder

function somarValorProduto()
{ 
	valorSoma = 0;
	valorSomaDepois = 0;
	valorMulti = 1;
	valorSubstituicao = 0;

	$(".produto_opcao").each(function(){
		var opcao = $(this).children("input:first").val();

		valorSetado =  parseFloat($("#valorOpcao_" + opcao).val());

		calcOpcao = $("#calcOpcao_" + opcao).val(); 

		switch(calcOpcao)
		{
			case "0":	// Soma dos Valores
				valorSoma += valorSetado;
				break;
			case "1":	// Maior Valor
				valorSoma += valorSetado;
				break;
			case "2":	// Soma dos Valores (Depois)
				valorSomaDepois += valorSetado;
				break;
			case "3":	// Multiplicação
				valorMulti *= valorSetado;
				break;
			case "4":	// Substituição do Valor
				valorSubstituicao += valorSetado;
				break;
		}		
        
	});
        
    valorProduto = parseFloat($("#hdfValorProduto").val().replace(",","."));

	if (valorSubstituicao != 0)
	{
		valorProduto = valorSubstituicao;
	}

	valorProdutoFinal = ((valorSoma + valorProduto) * valorMulti) + valorSomaDepois;
                
	$("#hdfValorTotal").val(valorProdutoFinal);
	$(".valor_por").children("span:first").text(formatarValor(valorProdutoFinal, ''));

	$(".valor_por_grande").children("span:first").text(formatarValor(valorProdutoFinal, ''));	
	if (valorProdutoFinal != valorProduto)
	{
		$(".valor_por").hide();
		$(".valor_parcelado_detalhe").hide();
		$(".valor_por_grande").show();
		$("#formas_pagtos > img").unbind('mouseover');
		$(".vizualizar_parcelamento").hide();
		

	}
	
	
	
}



function formatarValor(num, tipo)
{
	x = 0;

	if(num<0) {
		num = Math.abs(num);
		x = 1;
	} 
	if(isNaN(num)) 
		num = "0";
	cents = Math.floor((num*100+0.5)%100);

	num = Math.floor((num*100+0.5)/100).toString();

	if(cents < 10) 
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+'.'+num.substring(num.length-(4*i+3));
	ret = num + ',' + cents;
	ret = "R$ "+ret;
	if (num!=0 && tipo=='F')

		if (x == 1)
			ret = "- " + ret;
		else
			ret = "+ " + ret;

	return ret;
}

function setarValorRadio(objRadio)
{
	
	var opcao = $(objRadio).parents(".produto_opcao").children("input:first").val();
	valorSetado = $("#valorOpcao_" + opcao).val();
		
	produto = $(objRadio).parent().children("input:first").val();

	valorItem = parseFloat($("#valorItem_" + produto).val().replace(",","."));

	valor = valorItem - valorSetado;

	$(objRadio).parents(".produto_opcao_item").children(".valor").text(formatarValor(valor, 'F'));

	$("#valorItem_" + produto).val(valor);
}


function calcularValorOpcao(objOpcao)
{
	var opcao = $(objOpcao).children("input:first").val();

	maxOpcao = $("#maxOpcao_" + opcao).val();
	minOpcao = $("#minOpcao_" + opcao).val();
	calcOpcao = $("#calcOpcao_" + opcao).val(); 

	somaItens = 0;
	multItens = 1;
	
	maiorValor = 0;

	qtdeTotal = 0;	
	somaValores = 0;

	$(objOpcao).children("table").children("tbody").children("tr").each(function(){

		var produto = $(this).children(".componente").children("input:first").val();
	
		valorItem = parseFloat($("#valorItem_" + produto).val().replace(",","."));
		qtdeItem = parseInt($("#qtdeItem_" + produto).val(), 10);

		somaValores += valorItem;

		multi = valorItem * qtdeItem;
		somaItens += multi;
		multItens *= multi;
		if (qtdeItem > 0)
		{	
			qtdeTotal += qtdeItem;
			if (valorItem > maiorValor )
			{
				maiorValor = valorItem;
			}
		}

	});
	valorOpcao = 0;
	switch(calcOpcao)
	{
		case "0":	// Soma dos Valores
			valorOpcao = somaItens;
			break;
		case "1":	// Maior Valor
			valorOpcao = maiorValor;
			break;
		case "2":	// Soma dos Valores (Depois)
			valorOpcao = somaItens;
			break;
		case "3":	// Multiplicação
			valorOpcao = multItens;
			break;
		case "4":	// Substituição do Valor
			valorOpcao = somaItens;
			break;
	}
	valorInicial = parseFloat($("#valorOpcaoInicial_" + opcao).val());
	if(isNaN(valorInicial)) 
		valorInicial = 0;

	valorOpcao = valorOpcao - valorInicial;
	$("#valorOpcao_" + opcao).val(valorOpcao);

	$("#qtdeTotalItem_" + opcao).val(qtdeTotal);

	$("#somaItensHidden_" + opcao).val(somaValores);

	

}

function somarValorOpcaoProduto()
{

	valorSoma = 0;
	valorSubstitui = 0;
	maiorValor = 0;
	valorMulti = 1;
	valorSomaDepois = 0;

	$(".produto_opcao").each(function(){

		var opcao = $(this).children("input:first").val();

		calcOpcao = $("#calcOpcao_" + opcao).val(); 
		valorOpcao = parseFloat($("#valorOpcao_" + opcao).val());

		qtde_escolha = 	parseInt($("#qtdeItem_" + produto).val(), 10);

		if (qtde_escolha > 0)
		{		
			switch(calcOpcao)
			{
				case "0":	// Soma dos Valores
					valorSoma += valorOpcao;
					break;
				case "1":	// Maior Valor
					maiorValor += valorOpcao;
					break;
				case "2":	// Soma dos Valores (Depois)
					valorSomaDepois += valorOpcao;
					break;
				case "3":	// Multiplicação
					valorMulti += valorOpcao;
					break;
				case "4":	// Substituição do Valor
					valorSubstitui += valorOpcao;
					break;
			}
		}
		
	});

	valorProd = parseFloat($("#hdfValorProduto").val().replace(",","."));
	
	if (valorSubstitui != 0)
	{
		valorProd = valorSubstitui;
	}
	valorProd += valorSoma + maiorValor;

	valorProdutoFinal = valorProd * valorMulti + valorSomaDepois;

	$("#hdfValorTotal").val(valorProdutoFinal);

}

function mostrar_contrato()
	{
		$("embed").hide();
		$("#fundo_modal").fadeIn("normal");	
		$("#box_contrato").show();	
	}


function enviar_pergunta()
{  
	$("#pergunta_nome, #pergunta_email, #pergunta_texto").blur();
	//var form = document.getElementById('form1');
	//var email = document.getElementById('pergunta_email');

	if ($("#validacao_nome").is(":empty") && $("#validacao_email").is(":empty") && $("#validacao_texto").is(":empty"))
	{
		$("form:first").attr("action", "produtoacao.aspx?cnt=" + chave_contexto + "&acao=P&pergunta_prod=" + cod_produto + "&html=none")
		$("form:first").submit();
	}
}

function enviar_avaliacao()
{  
     //var form = document.getElementById('form1');
	
	//form.action = "produtoacao.aspx?cnt=[c]chave_contexto[/c]&acao=A&avaliacao_prod=[c]cod_produto[/c]&avaliacao_opcao=[c]flg_produto_aceita_avaliacao[/c]&html=none";
	//form.submit(); -->
	if ($("#avaliacao_nota").val() == "0")
		$("#validacao_nota").html(escapeHTML("Informe a avalia&ccedil;&atilde;o."));
	else
		$("#validacao_nota").empty();


	$("#avaliacao_texto").blur();
	if ($("#validacao_nota").is(":empty") && $("#validacao_texto2").is(":empty"))
	{
		$("form:first").attr("action", "produtoacao.aspx?cnt=" + chave_contexto + "&acao=A&avaliacao_prod=" + cod_produto + "&html=none")
		$("form:first").submit();
	}
}

function validarEmail(email)
{
	var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
	if(typeof(email) == "string")
	{
		if(er.test(email))
		 { return true; }
	}else if(typeof(email) == "object")
	{
		if(er.test(email.value))
		{return true; }
	}else
	{
	  return false;
	}
}

function mudar_aba (nome) 
	{
		$("li[id^='aba_']").removeClass("aba_on");
		$("div[id^='box_']").hide();
		
		$("#aba_" + nome).addClass("aba_on");
		$("#box_" + nome).show();
		
	}
	

function mostrar_form_pergunta ()
{
	$("#fazer_pergunta").toggle();
}

function mostrar_form_opiniao ()
{
	$("#dar_opiniao").toggle();
}

//inicialização do formulário das opções extras
function sis_opcoes_form_carregar()
{
	$(".sis_opcoes_form_tipo").each(function(){
		var objTitle = $(this).nextAll(".sis_opcoes_form_nome:first").val();
		var objId = "sis_opcoes_form_campo" + $(this).val();
		var objClass = "sis_opcoes_form_campo " + $(this).attr("class");
		
		if ($(".sis_opcoes_form_tipo1, .sis_opcoes_form_tipo2, .sis_opcoes_form_tipo3, .sis_opcoes_form_tipo5").index(this) > -1)
			$(this).before('<input type="text" value=""  class="' + objClass + '" id="' + objId + '" name="' + objId + '" title="' + objTitle + '"/>');
			
		if ($(".sis_opcoes_form_tipo4").index(this) > -1)
			$(this).before('<textarea class="' + objClass + '" id="' + objId +  '" name="' + objId + '" title="' + objTitle + '"></textarea>');		  
		
		if ($(".sis_opcoes_form_tipo7, .sis_opcoes_form_tipo7").index(this) > -1)
			$(this).before('<input type="file" class="' + objClass + '" id="' + objId +  '" name="' + objId + '" title="' + objTitle + '">');		  
		
	});
	
	$(".sis_opcoes_form_campo").removeClass("sis_opcoes_form_tipo");
	$(".sis_opcoes_form_tipo, .sis_opcoes_form_nome").remove();
	
	if ($(".sis_opcoes_form_campo:file").length > 0)
		$('#form1').attr("enctype", "multipart/form-data");
	
	if ($(".sis_opcoes_form_campo").length > 0)
		$(".sis_opcoes_form").show();
}

//validação do formulário das opções extras
function sis_opcoes_form_validar()
{
	var sis_msg = "";
	$(".sis_opcoes_form_campo").removeClass("sis_opcoes_form_error");
	
	$(".sis_opcoes_form_obrigatorio1").each(function(){
		var valor = $(this).val();
		var titulo = $(this).attr("title");
													
		if (valor == "")
		{
			sis_msg = sis_msg + 'O campo "' + titulo + '" deve ser preenchido. \n';
			$(this).addClass("sis_opcoes_form_error");
		}
	});
	
	var extencoes_img = "#gif#jpg#png#";
	$(".sis_opcoes_form_tipo7").each(function(){
		var valor = $(this).val();
		if (valor != "")
		{
			var titulo = $(this).attr("title");
			
			if (valor.indexOf(".") != -1)
				valor = valor.substring(valor.lastIndexOf(".") + 1);
												
			if (extencoes_img.indexOf(valor.toLowerCase()) == -1)
			{
				sis_msg = sis_msg + 'O campo "' + titulo + '" aceita apenas arquivos do tipo JPG, GIF e PNG. \n';
				$(this).addClass("sis_opcoes_form_error");
			}
		}
	});
	
	if (sis_msg != "")
	{
		alert(sis_msg);
		$(".sis_opcoes_form_error:first").focus();
	}
	
	return (sis_msg == "");	
}




