var jsDebug = false;
$(document).ready(function(){
    $(".pack_detalhes").css("display", "none");
    $("#desconto_codigo").attr("value", "");
    change('m_orcamento', 'item_menu ativo_menu');
    $('#calc').className = 'calculadora_aberta'
    $('#calc').css('right', '0px')
    $('#abre_calc').toggle(function(){
        $('#calc').animate({
            right: '-226px'
        }, 900);
        document.getElementById('calc').className = 'calculadora_fechada';
    }, function(){
        $('#calc').animate({
            right: '0px'
        }, 900);
        document.getElementById('calc').className = 'calculadora_aberta';
    });
    var vValorInicial = -80;
    var vValorPorPagina = 80;
    var vBruto = vValorInicial;
    var vRadio = new Array();
    var vDesconto = 0;
    var vPaginas = 0;
    $("#desconto_codigo").bind("keyup change", fGetDesconto);
    $("#paginas").change(function(){
        var vCalculaPaginas = parseFloat(vValorPorPagina * $(this).val());
        var vCalculaPaginasCached = parseFloat(vValorPorPagina * vPaginas);
        vBruto -= vCalculaPaginasCached;
        vBruto += vCalculaPaginas;
        vPaginas = $(this).val();
        aplica_desconto(vDesconto);
    }).change();
    var page_loading = true;
    $(".orc_check").change(function(){
        if (page_loading == true) {
            vEsteBruto = parseFloat($('#preco_' + $(this).val()).val());
            if ($(this).attr('checked') == true) {
                vBruto += vEsteBruto;
                if (vBruto < 0) {
                    vBruto = 0;
                }
                $("#item_orca_" + $(this).attr("id")).addClass("item_ativo");
            }
        }
        aplica_desconto(-1);
    }).change();
    $(".orc_radio").change(function(){
        if (page_loading == true) {
            vEsteBruto = parseFloat($(this).parent().find("input[type=hidden]").val());
            if ($(this).attr('checked') == true) {
                vBruto += vEsteBruto;
                vRadio['bruto_' + $(this).attr('name')] = vEsteBruto;
                vRadio['id_' + $(this).attr('name')] = $(this).attr('id');
                if (vBruto < 0) {
                    vBruto = 0;
                }
	            if ("pack_informacoes" == $(this).parent().parent().attr("class")) {
	                $(this).closest("ul").find(".item_ativo").each(function(i){
	                    $(this).removeClass("item_ativo");
	                });
	                $(this).closest("a").addClass("item_ativo");
	            }
	            else {
	                $(this).closest("ul").find(".item_ativo").each(function(i){
	                    $(this).removeClass("item_ativo");
	                });
					$(this).parent().parent().find("a").addClass("item_ativo");
	            }
            }
        }
        aplica_desconto(-1);
    }).change();
    page_loading = false;
    var evt = $.browser.msie ? "click" : "change";
    function orc_radio(i){
        vEsteBruto = parseFloat(i.parent().find("input[type=hidden]").val());
        if (jsDebug) {
            alert(vEsteBruto + ' status: ' + i.attr('checked') + ' bruto: ' + $("#bruto").html());
        }
        if (i.attr('checked') == true) {
            vBruto += vEsteBruto;
            vBruto -= vRadio['bruto_' + i.attr('name')];
            vRadio['bruto_' + i.attr('name')] = vEsteBruto;
            if (vBruto < 0) {
                vBruto = 0;
            }
            if ("pack_informacoes" == i.parent().parent().attr("class")) {
                i.closest("ul").find(".item_ativo").each(function(i){
                    $(this).removeClass("item_ativo");
                });
                i.closest("a").addClass("item_ativo");
            }
            else {
                i.closest("ul").find(".item_ativo").each(function(i){
                    $(this).removeClass("item_ativo");
                });
                i.parent().parent().find("a").addClass("item_ativo");
            }
            vRadio['id_' + i.attr('name')] = i.attr('id');
        }
        aplica_desconto(vDesconto);
    }
    function orc_check(i){
        vEsteBruto = parseFloat($('#preco_' + i.val()).val());
        if (i.attr('checked')) {
            vBruto += vEsteBruto;
            if (vBruto < 0) {
                vBruto = 0;
            }
            i.parent().parent().find("a").addClass("item_ativo");
        }
        else {
            vBruto -= vEsteBruto;
            if (vBruto < 0) {
                vBruto = 0;
            }
            i.parent().parent().find("a").removeClass("item_ativo");
        }
		aplica_desconto(-1);
    }
	
	function toggle_check(i) {
		if(!i.attr("checked")) {
			i.attr("checked", "checked");
		} else {
			i.removeAttr("checked");
		}
	}
	
    $(".item_desativo").click(function(){
		if(!$(this).parent().find("input[type=checkbox]").val() == false) {
			toggle_check($(this).parent().find("input[type=checkbox]"));
        	orc_check($(this).parent().find("input[type=checkbox]"));
		}
		else if(!$(this).parent().find("input[type=radio]").val() == false) {
			$(this).parent().find("input[type=radio]").attr("checked","checked");
        	orc_radio($(this).parent().find("input[type=radio]"));
		}
    });
	
    $(".orcamento_packs a[rel=pack]").click(function(){
        $(this).find("input[type=radio]").attr("checked", "checked");
        orc_radio($(this).find("input[type=radio]"));
    });
    $(".orcamento_packs a.bt_open_pack").toggle(function(){
        var titulodopack = $(this).parent().find(".titulo_pack").text();
        $(this).text('Esconder detalhes do conteudo da' + titulodopack);
        $(this).parent().find(".pack_detalhes").slideDown('normal');
    }, function(){
        var titulodopack = $(this).parent().find(".titulo_pack").text();
        $(this).text('Detalhar conteudo da' + titulodopack);
        $(this).parent().find(".pack_detalhes").slideUp('normal');
    });


    $(".orc_radio").bind(evt, function(){
        orc_radio($(this));
		console.log($(this));
    });
	$(".orc_check").bind(evt, function(){
        orc_check($(this));
    });

    function aplica_desconto(perc_desconto, verifica){
        clearTimeout(acertotime);
        clearTimeout(errotime);
		if(verifica) {
	        if (perc_desconto != -1) {
	            vDesconto = Math.round(perc_desconto);
	        }
	        else {
	            vDesconto = 0;
	        }
		}

        if (perc_desconto < 0) {
            $('.valor_ticket').text('');
            $('#desconto_codigo').removeClass("descontos_certo");
        }
        else 
            if (perc_desconto == 0) {
                $('span.tip_desconto').fadeIn(200);
                $('#tip_label').text('Desculpe, Este código não existe');
                var errotime = setTimeout(function(){
                    $('span.tip_desconto').fadeOut(200);
                }, 4000)
                $('.tip_loader').fadeOut(200);
                $('#tip_label').css("color", "#bc0221")
                $('#desconto_codigo').addClass("descontos_errado");
                $('#desconto_codigo').removeClass("descontos_certo");
            }
            else {
                $('span.tip_desconto').fadeIn(300);
                var acertotime = setTimeout(function(){
                    $('span.tip_desconto').fadeOut(200);
                }, 4000);
                $('#tip_label').text('Seu Ticket de Desconto é de ' + vDesconto + '%');
                $('#tip_label').css("color", "#639337")
                $('.tip_loader').fadeOut(200);
                $('#desconto_codigo').removeClass("descontos_errado");
                $('#desconto_codigo').addClass("descontos_certo")
            }
        var vValorDesconto = parseFloat(desconto(vBruto, vDesconto));
        var vTotal = (vBruto - vValorDesconto);
        if (vDesconto > 0) {
            display_calculadora(vBruto, vDesconto, vValorDesconto, vTotal);
        }
        else {
            display_calculadora(vBruto, 0, 0, vTotal);
        }
    }
    function display_calculadora(investimento, desconto_perc, desconto, total){
        if (investimento) {
            $("#bruto").text(investimento.toFixed(2));
        }
        else {
            $("#bruto").text('0,00');
        }
        if (desconto_perc) {
            $('#perc_desconto').text(desconto_perc);
        }
        else {
            $('#perc_desconto').text('0');
        }
        if (desconto) {
            $('#desconto').text(desconto.toFixed(2));
        }
        else {
            $('#desconto').text('0,00');
        }
        if (total) {
            $('#liquido').text(total.toFixed(2));
        }
        else {
            $('#liquido').text('0,00');
        }
    }
    function fGetDesconto(){
        $('.tip_loader').fadeIn(200);
        var getValor = $(this).val();
        $.get("/achar_desconto", {
            desconto_codigo: getValor
        }, function(x){
            if (getValor.length > 3) {
                aplica_desconto(x,true);
            }
        })
        if (getValor.length <= 3) {
            $('.valor_ticket').text('');
            $('.tip_loader').fadeOut(200);
            $('#desconto_codigo').removeClass("descontos_errado");
            $('#desconto_codigo').removeClass("descontos_certo");
            aplica_desconto(0, true);
        }
    };
    window.onscroll = function(){
        if (document.documentElement.scrollTop > 300 || self.pageYOffset > 300) {
            var vLimite = $('#rodape').position().top - 160
            if (document.documentElement.scrollTop < vLimite || self.pageYOffset < vLimite) {
                $('#calc').css('position', 'fixed');
                $('#calc').animate({
                    top: '2px'
                }, {
                    duration: 300,
                    queue: false
                });
            }
            else {
                vLimite -= document.documentElement.scrollTop;
                $('#calc').css('position', 'fixed');
                $('#calc').animate({
                    top: vLimite + 'px'
                }, {
                    duration: 300,
                    queue: false
                });
            }
        }
        else 
            if (document.documentElement.scrollTop < 298 || self.pageYOffset < 298) {
                var posicao_correta = parseInt(275 - document.documentElement.scrollTop);
                $('#calc').css('position', 'fixed');
                $('#calc').animate({
                    top: posicao_correta + 'px'
                }, {
                    duration: 300,
                    queue: false
                });
            }
    }
});
function desconto(b, d){
    var vDesconto = 0;
    vDesconto = parseFloat((parseFloat(b) * parseFloat(d)) / 100);
    return vDesconto;
}
