vm7.pedidos = {
    setup: function() {
        $('.btDetalhePedido').bind('click', function() {
            if($(this).parents('.categoria-engloba').find('div.tabela').hasClass('aberta')) {
                $(this).parents('.categoria-engloba').find('div.tabela').slideToggle();
                $(this).parents('.categoria-engloba').find('div.tabela').removeClass('aberta');
                $(this).parents('.categoria-engloba').find('div.tabela').addClass('fechada');
            } else {
                $(this).parents('.categoria-engloba').find('div.tabela').slideToggle();
                $(this).parents('.categoria-engloba').find('div.tabela').removeClass('fechada');
                $(this).parents('.categoria-engloba').find('div.tabela').addClass('aberta');
            }
        });

        $('#categorias .bx-categoria ul li a').bind('click', function() {
            $('#categorias .bx-categoria ul li').removeClass('selecionado');
            $(this).parent().addClass('selecionado');
        });
        var pattern =  /\*?[0-9]{1,}/;
        var categId = $('#categorias .bx-categoria ul li:first-child').attr('id');
        if(typeof categId != 'undefined') {
            var id = categId.match(pattern);
            vm7.pedidos.listaValores('produtos/lista_valores/', id);
        }
        $('#FormPedido').submit(function() {
            var numRegistros = $('#ListaProdutos tbody tr').size();
            if(numRegistros > 0) {
                return true;
            } else {
                backend.messages.alertBox('Seu pedido não contém produtos. Adicione-os selecionando a categoria desejada, aguardando a listagem e clicando no botão "Adicionar" correpondente ao produto desejado.');
                return false;
            }
        });
    },
    listaValores: function(url, id) {
        if(id != 'config') {
        $.getJSON(getBaseURL + url + id, function(retorno) {
            var html = '';
            for(i in retorno) {
                if(retorno[i]['PrecoProduto'] != 'undefined' && retorno[i]['PrecoProduto'] != false) {
                    html += '<tr>';
                    html += '<td align="right">' + retorno[i]['cd_produto'] + '</td>';
                    html += '<td align="left">' + retorno[i]['nm_produto'] + '</td>';
                    html += '<td align="right">' + retorno[i]['PrecoProduto'][0]['vl_produto'] + '</td>';
                    html += '<td align="right"><button onclick="vm7.pedidos.adicionar('+retorno[i]['id']+'); return false;" type="button" title="Adicionar" class="bt-adicionar">Adicionar</button></td>';
                    html += '</tr>';
                }
                $('#ProdutosCategoria tbody').html(html);
            }            
        });
        } else {
            var html = '';
            html += '<tr>';
            html += '<td align="right">---</td>';
            html += '<td align="left"><input type="text" id="PedidoProdutoDcProduto" value="" name="data[PedidoProduto][dc_produto]"></td>';
            html += '<td align="right">---</td>';
            html += '<td align="right"><button onclick="vm7.pedidos.adicionar(\'config\'); return false;" type="button" title="Adicionar" class="bt-adicionar">Adicionar</button></td>';
            html += '</tr>';
            $('#ProdutosCategoria tbody').html(html);

        }
    },
    adicionar: function(id) {
        var html = '';
        var row = $('#ListaProdutos tbody tr').size();
        if(id != 'config') {
            var url = getBaseURL + 'produtos/busca_produto/' + id;
            $.getJSON(url, function(retorno) {
                if(retorno['PrecoProduto'] != 'undefined' || retorno['PrecoProduto'] != false) {
                    if(vm7.pedidos.registro_inserido(id)) {
                        backend.messages.alertBox('O produto selecionado já foi inserido no pedido.');
                    } else {
                        html += '<tr id="linha'+row+'">';
                        html += '<td align="center">';
                        html += '<input type="hidden" id="ProdutoPedido'+row+'ProdutoId" value="'+retorno['Produto']['id']+'" name="data[ProdutoPedido]['+row+'][produto_id]" />';
                        html += '<input type="hidden" id="ProdutoPedido'+row+'VlProduto" value="'+retorno['PrecoProduto'][0]['vl_produto']+'" name="data[ProdutoPedido]['+row+'][vl_produto]" />';
                        html += '<input type="hidden" id="ProdutoPedido'+row+'VlTotal" value="'+retorno['PrecoProduto'][0]['vl_produto']+'" name="data[ProdutoPedido]['+row+'][vl_total]" />';
                        html += '<input type="checkbox" id="ProdutoPedido'+row+'Selected" value="" name="data[ProdutoPedido]['+row+'][selected]">';
                        html += '</td>';
                        html += '<td align="right">'+retorno['Produto']['cd_produto']+'</td>';
                        html += '<td align="left">'+retorno['Produto']['nm_produto']+'</td>';
                        html += '<td align="right">R$'+retorno['PrecoProduto'][0]['vl_produto']+'</td>';
                        html += '<td align="right">';
                        html += '<input class="num" id="ProdutoPedido'+row+'QtProduto" value="1" name="data[ProdutoPedido]['+row+'][qt_produto]" maxlength="2" onchange="vm7.pedidos.recalcula('+row+');" />';
                        html += ' ' + retorno['Produto']['dc_unidade_medida'];
                        html += '</td>';
                        html += '<td class="vl-total-produto" align="right">R$<span>'+retorno['PrecoProduto'][0]['vl_produto']+'</span></td>';
                        html += '</tr>';
                        $('#ListaProdutos tbody').append(html);
                        row++;
                        vm7.pedidos.calcula_total();
                    }
                }
            });
        } else {
            if($('#PedidoProdutoDcProduto').val() != '') {
                html += '<tr id="linha'+row+'">';
                html += '<td align="center">';
                html += '<input type="hidden" id="ProdutoPedido'+row+'DcUnidadeMedida" value="'+$('#PedidoProdutoDcUnidadeMedida').val()+'" name="data[ProdutoPedido]['+row+'][dc_unidade_medida]" />';
                html += '<input type="hidden" id="ProdutoPedido'+row+'VlTotal" value="1.00" name="data[ProdutoPedido]['+row+'][vl_total]" />';
                html += '<input type="checkbox" id="ProdutoPedido'+row+'Selected" value="" name="data[ProdutoPedido]['+row+'][selected]">';
                html += '</td>';
                html += '<td align="right">---</td>';
                html += '<td align="left">';
                html += '<input class="txt" id="ProdutoPedido'+row+'DcProduto" value="'+$('#PedidoProdutoDcProduto').val()+'" name="data[ProdutoPedido]['+row+'][dc_produto]" minlength="3" />';
                html += '</td>';
                html += '<td align="right">';
                html += '<input class="num" id="ProdutoPedido'+row+'VlProduto" name="data[ProdutoPedido]['+row+'][vl_produto]" value="0.00" onchange="vm7.pedidos.recalcula('+row+');" onblur="vm7.pedidos.recalcula('+row+');" disabled="disabled" />';
                html += '</td>';
                html += '<td align="right">';
                html += '<input class="num" id="ProdutoPedido'+row+'QtProduto" name="data[ProdutoPedido]['+row+'][qt_produto]" value="1" maxlength="2" onchange="vm7.pedidos.recalcula('+row+');" onblur="vm7.pedidos.recalcula('+row+');" />';
                html += '<select id="ProdutoPedido'+row+'DcUnidadeMedida" name="data[ProdutoPedido]['+row+'][dc_unidade_medida]">';
                html += '<option value="">Selecione</option>';
                html += '<option value="un">Unidade(s)</option>';
                html += '<option value="gr">Grama(s)</option>';
                html += '<option value="kg">Kilograma(s)</option>';
                html += '<option value="lt">Litro(s)</option>';
                html += '</select>';
                html += '</td>';
                html += '<td class="vl-total-produto" align="right">R$<span>1.00</span></td>';
                html += '</tr>';                
                $('#ListaProdutos tbody').append(html);
                $('#CategoriaId').val(0);
                $('#ProdutoId').val(0);
                row++;
                vm7.pedidos.calcula_total();
            } else {
                backend.messages.alertBox('Preencha a descrição do produto.');
            }
        }
    },
    recalcula: function(id) {
        var vl_produto = parseFloat($('#ListaProdutos tbody tr#linha'+id).find('input#ProdutoPedido'+id+'VlProduto').val());
        var qt_produto = parseInt($('#ListaProdutos tbody tr#linha'+id).find('input#ProdutoPedido'+id+'QtProduto').val());
        var vl_total_produto = (vl_produto * qt_produto);
        $('#ListaProdutos tbody tr#linha'+id+' td:last-child').html('R$<span>'+vm7.pedidos.formatNumber(vl_total_produto, 2, true, false, false)+'</span>');
        $('#ListaProdutos tbody tr#linha'+id+' td').find('input#ProdutoPedido'+id+'VlTotal').val(vm7.pedidos.formatNumber(vl_total_produto, 2, true, false, false));
        vm7.pedidos.calcula_total();
    },
    calcula_total: function() {
        var vl_total_pedido = 0;
        var qt_produtos_pedido = 0;
        $('#ListaProdutos tbody tr').each(function() {
            vl_total_pedido += parseFloat($(this).find('td:last-child').children('span').text());
            qt_produtos_pedido += parseInt($(this).find('td:last-child').prev().find('input').val());
        });
        $('#PedidoQtProdutosPedido').val(qt_produtos_pedido);
        $('#PedidoVlTotal').val(vm7.pedidos.formatNumber(vl_total_pedido, 2, true, false, false));
        $('#ListaProdutos tfoot tr').find('td:last-child').children('strong').html('R$'+vm7.pedidos.formatNumber(vl_total_pedido, 2, true, false, false));
        
    },
    excluir_listados: function() {
        if(confirm('Tem certeza que deseja remover do seu pedido os produtos selecionados?')) {
            $('#ListaProdutos tbody tr').each(function() {
                if($(this).find('input[type="checkbox"]').is(':checked')) {
                    $(this).remove();
                }
            });
            vm7.pedidos.calcula_total();
        }
    },
    registro_inserido: function(produto_id) {
        var achou = false;
        $('#ListaProdutos tbody tr').each(function() {
            if($(this).children('td:first-child').children('input:first-child').val() == produto_id) {
                achou = true;
            }
        });
        if(achou) {
            return true;
        } else {
            return false;
        }
    },
    formatNumber: function(num,decimalNum,bolLeadingZero,bolParens,bolCommas) {
        /**********************************************************************
	IN:
	NUM - the number to format
	decimalNum - the number of decimal places to format the number to
	bolLeadingZero - true / false - display a leading zero for
									     numbers between -1 and 1
	bolParens - true / false - use parenthesis around negative numbers
	bolCommas - put commas as number separators.

	RETVAL:
	The formatted number!
         **********************************************************************/
        if (isNaN(parseInt(num)))
            return "NaN";
        var tmpNum = num;
        var iSign = num < 0 ? -1 : 1; // Get sign of number

        // Adjust number so only the specified number of numbers after
        // the decimal point are shown.
        tmpNum *= Math.pow(10,decimalNum);
        tmpNum = Math.round(Math.abs(tmpNum))
        tmpNum /= Math.pow(10,decimalNum);
        tmpNum *= iSign; // Readjust for sign

        // Create a string object to do our formatting on
        var tmpNumStr = new String(tmpNum);

        // See if we need to strip out the leading zero or not.
        if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
            if (num > 0)
                tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
            else
                tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);

        // See if we need to put in the commas
        if (bolCommas && (num >= 1000 || num <= -1000)) {
            var iStart = tmpNumStr.indexOf(".");
            if (iStart < 0)
                iStart = tmpNumStr.length;
            iStart -= 3;
            while (iStart >= 1) {
                tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
                iStart -= 3;
            }
        }
        var iDec = tmpNumStr.indexOf(".");
        if (iDec < 0) {
            iDec = tmpNumStr.length;
            tmpNumStr += '.00';
        } else {
            var iTam = tmpNumStr.length;
            for (i = 0; i < (decimalNum - (iTam - (iDec+1))); i++) {
                tmpNumStr += '0';
            }
        }
        // See if we need to use parenthesis
        if (bolParens && num < 0)
            tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";
        return tmpNumStr; // Return our formatted string!
    }
};
