﻿
var total_itens = 0;
var total_valor = 0;

// Inicia processo da layer da cesta
function iniciarCesta() {
	// Insere div cesta
	if(!$('#Cesta').length)
	    $('body').append('<div id="Cesta">Carregando informações...</div>');
	
	// Oculta cesta
	$('#Cesta').css('display','none');
	
	// Carrega os itens da cesta
	carregarCesta();
}


// Carrega os itens da cesta de compras
function carregarCesta() {
	if($("div.header div.itensCarrinho").length) {
		$.get('/scripts/home/layer/carrinho.asp', function(xml){
			// Fomrata o XML para a layer #Cesta
			formatarXmlCesta(xml);
			$('#Layer').html('');
			$('#Cesta').clone().addClass("cestaMostra").appendTo('#Layer');
		},'xml');
	}
}

// Formata XML de retorno com os itens da cesta de compras do cliente
function formatarXmlCesta(xml) {
    var temItem = false;
    var html = tbItens = tbRodape = tbTitulo = msgCestaVazia = '';

	tbTopo = '<div style="background:url(/imagem/layout/layout/topo_layer.png) no-repeat 0 0; width:514px; height:10px;"></div>';
	tbDiv = '<div id="Cesta2">';
	// Título
	tbTitulo = '<h2>Cesta de Compras</h2>';
	
    // Itens
    tbItens =  '<div id="itens"><table width="96%" cellspacing="0" cellpadding="2" border="0"><thead>';
    tbItens += '  <tr>';
    tbItens += '    <th>Item</th>';
    tbItens += '    <th>Disponibilidade</th>';
    tbItens += '    <th>Qtde</th>';
    tbItens += '    <th>Excluir</th>';
    tbItens += '    <th>R$</th>';
    tbItens += '  </tr></thead>';
			
    // Loop dos itens do XML
    $('item', xml).each(function(i){
	    
	    temItem = true;
	    
		nitem     = $(this).find("nitem").text();
		titem     = $(this).find("titem").text();
		id        = $(this).find("id").text();
		titulo    = $(this).find("titulo").text();
		gift      = $(this).find("gift").text();
		disp_item = $(this).find("dispo").text();
		qtde      = $(this).find("qtde").text();
		preco     = $(this).find("preco").text();
		destinatario = $(this).find("destinatario").text();
		
		if(destinatario != '')
		    para = ' (Para: ' + destinatario + ')';
		else
			para = '';
			
		// Giftcard, M-Gift, Credito, Revista da Cultura
		var link = (titem != "10" && titem != "12" && titem != "14" && nitem != "25000069");
		var link1 = link2 = "";
		
		if (link) {
			link1 = '<a href="/scripts/resenha/resenha.asp?nitem='+nitem+'">'; link2 = '</a>';
		} else {
			link1 = ''; link2 = '';
		}
		
		var classe_presente;
		
		if(gift!='' && gift!=0) {
			classe_presente = "presenteAtivo";
		} else {
			classe_presente = "presente";
		}
		
		if(titem=='10') {
			classe_presente = "presenteBloqueadoAtivo";
		} else if (titem=='12' || nitem=='22053365') {
			classe_presente = "presenteBloqueado";
		}
		
		tbItens += '  <tr><td colspan="6"><div class="linhaDivisoriaCesta"></div></td></tr>';
		tbItens += '  <tr>';
		tbItens += '    <td>'+link1+titulo+link2+para+'</td>';
		//tbItens += '    <td class="center"><a class="marcar_para_presente_'+i+' '+classe_presente+'" onclick="marcarParaPresenteCesta(\'a.marcar_para_presente_'+i+'\', \''+nitem+'\')"></a></td>';
		tbItens += '    <td>'+disp_item+'</td>';
		tbItens += '    <td><span class="qtde"><input type="text" name="cesta_qdte_'+ (i).toString() +'" value="'+(qtde)+'" size="2" maxlength="3" onkeyup="alterarQtdeCesta(this.value,'+nitem+','+id+')"'+((titem=='10' || titem=='11' || titem=='12' || titem=='14' || nitem=='22053365')?' disabled="disabled"':'')+'></span></td>';
		tbItens += '    <td class="center">' + ((nitem != '22053365') ? '<a href="javascript:excluirItemCesta('+nitem+','+id+');"><img src="/imagem/layout/icones/x.gif" border="0" alt="Retirar da Cesta" title="Retirar da Cesta" /></a>' : '') + '</td>';
		tbItens += '    <td><span id="cesta_preco_'+ (i).toString() +'">'+(preco)+'</span></td>';
		tbItens += '  </tr>';

    });
    // Fim loop dos itens do XML
	
	tbItens += '</table></div>';
	
	total_itens = $('total',xml).find('total_itens').text();
	total_valor = $('total',xml).find('total_valor').text();
	temum       = $('Cesta',xml).find('temum').text();	
	
	tbRodape  = '<table cellpadding="0" cellspacing="0" border="0" class="cesta_rodape"><tr>';
	tbRodape +=     '<td><a class="limparCesta" href="javascript:limparCesta();">Limpar Compras</a></td>';
	if(temum==1) {
		tbRodape +=     '<td><a class="oneClickAtivo" alt="Comprar com 1 Clique" title="Comprar com 1 Clique" href="javascript:comprarComUmClique();"></a></td>';
	} else {
		tbRodape +=     '<td><a class="oneClick" alt="Comprar com 1 Clique" title="Comprar com 1 Clique" href="javascript:comprarComUmClique();"></a></td>';
	}
    tbRodape +=     '<td><a class="fecharPedido" alt="Fechar Pedido" title="Fechar Pedido" href="javascript:fecharPedidoBasket();"></a></td>';
    tbRodape +=     '<td><span class="totalCesta">Total: R$ '+(total_valor)+'&nbsp;</span></td>';
    tbRodape += '</tr></table>';
	
	tbDivF = '</div>';
	tbFoot = '<div style="background:url(/imagem/layout/layout/rodape_layer.png) no-repeat 0 0; width:514px; height:22px;"></div>';
	
	// Cesta vazia
	msgCestaVazia = '<p>Sua cesta de compras est&aacute; vazia.</p>';
	
	// Prepara html
	if(temItem) {
	    html = tbTopo + tbDiv + tbTitulo + tbItens + tbRodape + tbDivF + tbFoot;
		$("img[src='/imagem/layout/titulo/cesta_compras.png']").attr({
			src: "/imagem/layout/titulo/fechar_pedido.png",
			alt: "Fechar Pedido",
			title: "Fechar Pedido"
			});
	} else {
	    //html = tbTopo + tbDiv + msgCestaVazia + tbDivF + tbFoot;
		$("img[src='/imagem/layout/titulo/fechar_pedido.png']").attr({
			src: "/imagem/layout/titulo/cesta_compras.png",
			alt: "Cesta de Compras",
			title: "Cesta de Compras"
			});
	}
	
	// Insere html na cesta
	$('#Cesta, div.cestaMostra').html(html);
}

function comprarComUmClique() {
	location.href = "/scripts/home/ssl/login.asp?dest=compra_umclick&tela=basket&ntp=1&" + getSid(location.search);
}

function fecharPedidoBasket() {
	location.href = "/scripts/home/basket/basket.asp?" + getSid(location.search);
}

function getSid(txt) {
	var i = txt.indexOf("sid=");
	var f = txt.indexOf("&", i);
	return txt.substring(i,f);
}

//------------------------------------------------------------------------------------------------
//     AÇÕES     ---------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------
function marcarParaPresenteCesta(id, nitem) {
	var r = Number(Math.random());
    // loading
    loadingCesta();
	
	var checked = 0;
	
	if($(id).hasClass("presenteBloqueado") || 
	   $(id).hasClass("presenteBloqueadoAtivo"))
		 return;

	if($(id).hasClass("presente")) {
		checked = 2;
		$(id).removeClass("presente").addClass("presenteAtivo");
	} else if($(id).hasClass("presenteAtivo")) {
		checked = 0;
		$(id).removeClass("presenteAtivo").addClass("presente");
	}
		
	// request
    $.get(
		'/scripts/home/layer/carrinho.asp',
		{ acao:'setaParaPresente', 
		  nItem:nitem, 
		  valor:checked, 
		  rnd:r
		});
}

function limparCesta() {
    var r = Number(Math.random());
    // loading
    loadingCesta();
	// request
	$.get('/scripts/home/layer/carrinho.asp', {acao:'limparCesta', rnd:r}, function(xml){
        formatarXmlCesta(xml);
        refreshCesta();
	}, 'xml');
}

function excluirItemCesta(nitem, id) {
	alterarQtdeCesta('0', nitem, id);
}

function alterarQtdeCesta(qt, nitem, id) {
    var r = Number(Math.random());
	qt = qt.replace(/\D/g, '');
	if(!id) id = 0;
	if(!isNaN(qt) && qt!='') {
	    // loading
	    loadingCesta();
		// request
		$.get('/scripts/home/layer/carrinho.asp', {acao:'alterarQtde', nItem:nitem, quant:qt, id:id, rnd:r}, function(xml){
            formatarXmlCesta(xml);
            refreshCesta();
		}, 'xml');
	}
}

// loading
function loadingCesta() {
    //if( $('#Layer #Cesta h2 span img').length == 0 )
    // $('#Layer #Cesta h2').append('<span style="font-size:9px; padding-left:10px;"><img src="/imagem/comum/loading01.gif" algin="middle" alt="carregando" border="0"></span>');
}

// refresh
function refreshCesta() {
	$('#Layer').html('');
    $('#Cesta').clone().appendTo('#Layer').css('display','').addClass("cestaMostra");
    atualizaCestaTopo();
}

// cesta Topo
function atualizaCestaTopo() {
    var itens, valor;
   
    if(isNaN(total_itens) || total_itens == '')
        itens = '0 item'
    else
        if(Number(total_itens) > 1)
            itens = total_itens + '&nbsp;itens'
        else
            itens = total_itens + '&nbsp;item';
    	
    if(!isNaN(total_valor) || total_valor == '')
        total_valor = '0,00';
	
    $('span.cesta_itens').html(itens);
    $('span.cesta_valor').html('R$&nbsp;' + total_valor);
}

//------------------------------------------------------------------------------------------------
//    INICIO     ---------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------
$(document).ready(function(){
	iniciarCesta();
});
