﻿function Produtos(_key) {
    this.keyAuth = _key;

    this.GetProdutosByShortcut = function(shortcut) {
        try {
            // Variavel que Recebe o LinkDefautl
            var linkDefault = new String();
            var caminhoWS = new String();
            var lData = new String();
            var shortcutLimpo = new Array();

            // Monta o LinkDefault com o Caminho que o Link do DHT deve Ter
            linkDefault = window.location.protocol + "//" + window.location.host + "/";
            // Seta o Caminho do WS
            caminhoWS = linkDefault + "ws/anuncioProduto.asmx/GetTopAnuncioProdutosByEmpresaShortcut";
            shortcutLimpo = shortcut.split("/");
            // Monta a String lData
            //lData = "authenticationKey=" + encodeURIComponent(this.keyAuth).replace('.', '').replace(/%20/g, "+").replace(/%26/g, "e") + "&pEmpresaShortcut=" + shortcutLimpo[shortcutLimpo.length - 1] + "&pLinkDefault=" + linkDefault;
            lData = "authenticationKey=" + this.keyAuth + "&pEmpresaShortcut=" + shortcutLimpo[shortcutLimpo.length - 1] + "&pLinkDefault=" + linkDefault;

            // Monta o Ajax
            $.ajax({
                type: "POST",
                url: caminhoWS,
                data: lData,
                dataType: "xml",
                beforeSend: function(XMLHttpRequest) {
                    Util.showLoading();
                },
                complete: function() {
                    //Util.hideLoading();
                    $('#maskCarregando').hide();
                },
                error: function(errorRequest) {
                    alert('Erro' + errorRequest);
                    Util.hideLoading();
                },
                success: function(loadedContentHTML) {
                    $(loadedContentHTML).find('produtos').each(function() {
                        var html = $(this).text();
                        $("#dhtml-ProdutosHTML").html(html);
                        $("#dhtml-ProdutosHTML-btVejaAnuncio").attr("href", linkDefault + shortcut);
                        $("#dhtml-ProdutosHTML-linkVejaAnuncio").attr("href", linkDefault + shortcut);
                        // Descobre o tamanho e posicionamento do Div
                        var winH = $(window).height();
                        var winW = $(window).width();
                        // Descobre a posicao do Scroll
                        var scrollH = Util.getScrollHeight();
                        var scrollW = Util.getScrollWidth();
                        // Descobre o Top do div
                        var divTop = ((winH / 2) - ($('#containerDhtmlProdutosID').height() / 2)) + scrollH;
                        var divLeft = ((winW / 2) - ($('#containerDhtmlProdutosID').width() / 2)) + scrollW;
                        $('#containerDhtmlProdutosID').css('top', divTop);
                        $('#containerDhtmlProdutosID').css('left', divLeft);
                        $('#containerDhtmlProdutosID').css('z-index', '9999');
                        $('#containerDhtmlProdutosID').show();

                        // Adiciona a Acao do Click na Mascara
                        $("#mask").click(function() {
                            // Remove todos os divs que ela "pode abrir"
                            $('#containerDhtmlProdutosID').hide(); // DHTML de Produtos (Busca e Departamento)
                            //Efeito na Mascara		
                            $('#mask').fadeOut("fast");
                        });

                        // Adiciona a Acao do Click do botao Fechar
                        $("#containerDhtmlProdutosFecharID").click(function() {
                            // Remove todos os divs que ela "pode abrir"
                            $('#containerDhtmlProdutosID').hide(); // DHTML de Produtos (Busca e Departamento)
                            //Efeito na Mascara
                            $('#mask').fadeOut("fast");
                        });
                    });
                }
            });
        }
        catch (e) {
            throw (e);
            return false;
        }
    }


    this.GetProdutosAtivosByDepartamento = function(pIdSegmento, pIdFranquia, pPageIndex, pNumRows, pFiltro, pUrlLink) {
        try {
            // Variavel que Recebe o LinkDefautl
            var linkDefault = new String();
            var caminhoWS = new String();
            var lData = new String();

            // Monta o LinkDefault com o Caminho que o Link do DHT deve Ter
            linkDefault = window.location.protocol + "//" + window.location.host + "/";
            // Seta o Caminho do WS
            caminhoWS = linkDefault + "ws/anuncioProduto.asmx/GetHTMLProdutosAtivasByDepartamento";
            // Monta a String lData
            lData = "authenticationKey=" + this.keyAuth + "&pIdSegmento=" + pIdSegmento + "&pIdFranquia=" + pIdFranquia + "&pPageIndex=" + pPageIndex + "&pNumRows=" + pNumRows + "&pFiltro=" + pFiltro + "&pUrlLink=" + pUrlLink;

            // Monta o Ajax
            $.ajax({
                type: "POST",
                url: caminhoWS,
                data: lData,
                dataType: "xml",
                beforeSend: function(XMLHttpRequest) {
                    Util.showLoading();
                },
                complete: function() {
                    Util.hideLoading();
                },
                error: function(errorRequest) {
                    alert('Erro' + errorRequest);
                    Util.hideLoading();
                },
                success: function(loadedContentHTML) {
                    $(loadedContentHTML).find('ofertas').each(function() {
                        var html = $(this).text();
                        $("#ctl00_content_containerBoxThumbTitID").html(html);
                    });
                }
            });
        }
        catch (e) {
            throw (e);
            return false;
        }
    }



    this.GetFiltroProdutosSubItensFinal = function(totalSubItens, linkPai, textoLink, idLink, pIdFranquia, pIdDepartamento, pSearchString, pIdCategoriaPai) {
        // Se tiver Somente 1 ou menos, quer dizer que pode ser que tenha subitens
        // ai deve-se procurar no webservice
        if (totalSubItens == 0) {
            // Variavel que Recebe o LinkDefautl
            var caminhoWS = new String();
            var lData = new String();

            if (pIdDepartamento == '') {
                pIdDepartamento = 0;
            }

            // Seta o Caminho do WS
            caminhoWS = window.location.protocol + "//" + window.location.host + "/ws/anuncioProduto.asmx/GetSubFiltros";
            // Monta a String lData
            lData = "authenticationKey=" + this.keyAuth + "&pIdDepartamento=" + pIdDepartamento + "&pSearchString=" + pSearchString + "&pCategoriaIdPai=" + pIdCategoriaPai;

            // Monta o Ajax
            $.ajax({
                type: "POST",
                url: caminhoWS,
                data: lData,
                dataType: "xml",
                beforeSend: function(XMLHttpRequest) {
                    //Util.showLoading();
                    //$("#boxFiltroCarregandoID").css("display", "block");
                },
                complete: function() {
                    //Util.hideLoading();
                },
                error: function(errorRequest) {
                    alert('Erro' + errorRequest);
                    //Util.hideLoading();
                },
                success: function(loadedContentHTML) {
                    var html = '';
                    var i = 0;
                    html = '<ul>';
                    $(loadedContentHTML).find('item').each(function() {
                        if (html != '<ul>') {
                            if ((i % 6) == 0) {
                                html += "</ul><ul>";
                            }
                        }
                        html += '<li>';
                        html += '<a href="javascript:void(0);" link="|' + $(this).attr("link") + '" idLink="' + $(this).attr("id") + '" onclick="javascript: Produtos.GetFiltroProdutosSubItens(this, \'' + pIdFranquia + '\', \'' + pIdDepartamento + '\', \'' + pSearchString + '\', ' + $(this).attr("id") + ');">';
                        html += $(this).attr("nome");
                        html += '</a>';
                        html += '</li>';
                        i++;
                    });
                    html += '</ul>';
                    $("#resultadosFiltrosID").html(html);
                    if (html == '<ul></ul>') {
                        $("#resultadosFiltrosID").parent().hide();
                        Util.submitLink($('#filtroURLDefaultID').val() + linkPai);
                        return false;
                    }
                    // Adiciona aos filtros selecionados
                    if (idLink != 0) {
                        var htmlFiltroSelect = '<a href="javascript:void(0);" onclick="javascript: Produtos.montControlFiltrosExcluir(this);" idLink="' + idLink + '" link="' + linkPai + '">' + textoLink + '</a>'

                        if ($.trim($('#filtrosSelecionadosId .filtrosSelecionados > div').html()) == '' || $.trim($('#filtrosSelecionadosId').html()) == '') {
                            var html = '';
                            html += '<div class="filtrosSelecionados">';
                            html += '<span class="filtro">Filtro:</span>';
                            html += '<div>';
                            html += htmlFiltroSelect;
                            html += '</div>';
                            html += '<a class="aplicarFiltro" href="javascript: void(0);" onclick="Util.SubmitAplicarFiltro();"></a>';
                            html += '</div>';
                            $('#filtrosSelecionadosId').html(html);
                        } else {
                            $('#filtrosSelecionadosId .filtrosSelecionados > div').append(htmlFiltroSelect);
                        }
                    }
                }
            });
        }
    }



    this.GetFiltroProdutosSubItens = function(pUlItem, pIdFranquia, pIdDepartamento, pSearchString, pIdCategoriaPai) {
        try {
            // Descobre se tem SubItens
            var totalSubItens = $(pUlItem).parent().find('ul').length;
            var linkPai = $(pUlItem).attr('link');
            var textoLink = $(pUlItem).html();
            var idLink = $(pUlItem).attr('idLink');
            Produtos.GetFiltroProdutosSubItensFinal(totalSubItens, linkPai, textoLink, idLink, pIdFranquia, pIdDepartamento, pSearchString, pIdCategoriaPai);
        }
        catch (e) {
            throw (e);
            return false;
        }
    }

    this.montControlFiltrosExcluir = function(e) {
        var idCategoriaProduto = $(e).attr("idlink");
        var apagarProximo = false;
        var linkId = $(e).prev().attr("idlink");
        if (linkId == undefined) {
            linkId = 0;
        }
        $("#filtrosSelecionadosId > .filtrosSelecionados > div > a").each(function() {
            if (apagarProximo == true) {
                $(this).remove();
            }

            if (idCategoriaProduto == $(this).attr("idLink")) {
                apagarProximo = true;
                $(this).remove();
            }
        });

        if ($.trim($("#filtrosSelecionadosId > .filtrosSelecionados > div").html()) == '') {
            $("#filtrosSelecionadosId").html('');
            Util.submitLink($('#filtroURLDefaultID').val());
            return false;
        }

        Produtos.GetFiltroProdutosSubItensFinal(0, 0, "", 0, $("#filtroIdFranquiaID").val(), $("#filtroIdDepartamentoID").val(), $("#filtroSearchStringID").val(), linkId);

        return false;
    }

}