﻿function Anuncios(_key) {
    this.keyAuth = _key;

    this.GetEmpresasAtivasByDepartamento = 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/anuncio.asmx/GetHTMLEmpresasAtivasByDepartamento";
            // Monta a String lData
            //lData = "authenticationKey=" + encodeURIComponent(this.keyAuth).replace('.', '').replace(/%20/g, "+").replace(/%26/g, "e") + "&pIdSegmento=" + pIdSegmento + "&pIdFranquia=" + pIdFranquia + "&pPageIndex=" + pPageIndex + "&pNumRows=" + pNumRows + "&pFiltro=" + pFiltro + "&pUrlLink=" + pUrlLink;
            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.GetFiltroEmpresasSubItensFinal = function(totalSubItens, linkPai, textoLink, idLink, pIdFranquia, pIdDepartamento, pSearchString, pIdDepartamentoPai) {
        // 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;
            }

            if (pIdDepartamentoPai == 0) {
                if ($("#filtroIdDepartamentoID").val() != "") {
                    pIdDepartamentoPai = $("#filtroIdDepartamentoID").val();
                }
            }

            // Seta o Caminho do WS
            caminhoWS = window.location.protocol + "//" + window.location.host + "/ws/anuncio.asmx/GetFiltrosFilhos";
            // Monta a String lData
            //string authenticationKey, int pIdFranquia, int pIdDepartamento, string pSearchString, int pIdCategoriaPai
            lData = "authenticationKey=" + this.keyAuth + "&pIdFranquia=" + pIdFranquia + "&pIdDepartamento=" + pIdDepartamento + "&pSearchString=" + pSearchString + "&pIdDepartamentoPai=" + pIdDepartamentoPai;

            // 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: Anuncios.GetFiltroEmpresasSubItens(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: Anuncios.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.GetFiltroEmpresasSubItens = function(pUlItem, pIdFranquia, pIdDepartamento, pSearchString, pIdDepartamentoPai) {
        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');
            Anuncios.GetFiltroEmpresasSubItensFinal(totalSubItens, linkPai, textoLink, idLink, pIdFranquia, pIdDepartamento, pSearchString, pIdDepartamentoPai);
        }
        catch (e) {
            throw (e);
            return false;
        }
    }

    this.montControlFiltrosExcluir = function(e) {
        var idDepartamento = $(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 (idDepartamento == $(this).attr("idLink")) {
                apagarProximo = true;
                $(this).remove();
            }
        });

        if ($.trim($("#filtrosSelecionadosId > .filtrosSelecionados > div").html()) == '') {
            $("#filtrosSelecionadosId").html('');
            Util.submitLink($('#filtroURLDefaultID').val());
            return false;
        }


        Anuncios.GetFiltroEmpresasSubItensFinal(0, 0, "", 0, $("#filtroIdFranquiaID").val(), $("#filtroIdDepartamentoID").val(), $("#filtroSearchStringID").val(), linkId)
    }

    this.SaveLogAnuncioView = function(pIdAnuncio) {
        // Cria as Variaveis de Controle
        var authenticationKey = new String();
        var idViewType = new Number();
        var idAnuncio = new Number();
        var urlAtual = new String();
        var extra = new String();

        // Seta o valor das Variaveis Automaticos
        authenticationKey = this.keyAuth;
        idViewType = 1
        urlAtual = window.location;
        extra = "";

        // Seta os valores das Variavies recebidas
        idAnuncio = pIdAnuncio;

        // Variaveis de Controle do AJAX
        var lData = new String();
        var caminhoWS = new String();

        // Seta os Dados a Enviar
        lData = "authenticationKey=" + authenticationKey + "&pIdViewType=" + idViewType + "&pIdAnuncio=" + idAnuncio + "&pUrlAtual=" + urlAtual + "&pExtra=" + extra;
        // Seta o Caminho do WS
        caminhoWS = window.location.protocol + "//" + window.location.host + "/" + "ws/anuncio.asmx/SaveView";

        // Monta o Ajax
        $.ajax({
            type: "POST",
            url: caminhoWS,
            data: lData,
            dataType: "html",
            error: function(errorRequest) {
                alert('Erro' + errorRequest);
            },
            success: function(loadedContentHTML) {
            }
        });

        return false;
    }

    this.SaveLogEmpresaClick = function(pIdEmpresa, pUrlDestino) {
        // Cria as Variaveis de Controle
        var authenticationKey = new String();
        var idClickType = new Number();
        var idEmpresa = new Number();
        var urlAtual = new String();
        var urlDestino = new String();
        var extra = new String();
        // Seta o valor das Variaveis Automaticos
        authenticationKey = this.keyAuth;
        idClickType = 1
        urlAtual = window.location;
        extra = "";

        // Seta os valores das Variavies recebidas
        idEmpresa = pIdEmpresa;
        urlDestino = pUrlDestino;

        // Variaveis de Controle do AJAX
        var lData = new String();
        var caminhoWS = new String();

        // Seta os Dados a Enviar
        lData = "authenticationKey=" + authenticationKey + "&pIdClickType=" + idClickType + "&pIdEmpresa=" + idEmpresa + "&pUrlAtual=" + urlAtual + "&pUrlDestino=" + urlDestino + "&pExtra=" + extra;
        // Seta o Caminho do WS
        caminhoWS = window.location.protocol + "//" + window.location.host + "/" + "ws/anuncio.asmx/EmpresaSaveClick";

        // Monta o Ajax
        $.ajax({
            type: "POST",
            url: caminhoWS,
            data: lData,
            dataType: "html",
            beforeSend: function(XMLHttpRequest) {
                Util.showLoading();
            },
            complete: function() {
                Util.hideLoading();
            },
            error: function(errorRequest) {
                alert('Erro' + errorRequest);
                Util.hideLoading();
                // Da o redirect
                setTimeout(function() {
                    top.location = urlDestino;
                }, 20);
            },
            success: function(loadedContentHTML) {
                // Da o redirect
                setTimeout(function() {
                    top.location = urlDestino;
                }, 20);
            }
        });

        return false;
    }

    this.SaveLogLojasEspeciaisHomeClick = function(pIdEmpresa, pUrlDestino) {
        // Cria as Variaveis de Controle
        var authenticationKey = new String();
        var idClickType = new Number();
        var idEmpresa = new Number();
        var urlAtual = new String();
        var urlDestino = new String();
        var extra = new String();
        // Seta o valor das Variaveis Automaticos
        authenticationKey = this.keyAuth;
        idClickType = 7
        urlAtual = window.location;
        extra = "";

        // Seta os valores das Variavies recebidas
        idEmpresa = pIdEmpresa;
        urlDestino = pUrlDestino;

        // Variaveis de Controle do AJAX
        var lData = new String();
        var caminhoWS = new String();

        // Seta os Dados a Enviar
        lData = "authenticationKey=" + authenticationKey + "&pIdClickType=" + idClickType + "&pIdEmpresa=" + idEmpresa + "&pUrlAtual=" + urlAtual + "&pUrlDestino=" + urlDestino + "&pExtra=" + extra;
        // Seta o Caminho do WS
        caminhoWS = window.location.protocol + "//" + window.location.host + "/" + "ws/anuncio.asmx/EmpresaSaveClick";

        // Monta o Ajax
        $.ajax({
            type: "POST",
            url: caminhoWS,
            data: lData,
            dataType: "html",
            beforeSend: function(XMLHttpRequest) {
                Util.showLoading();
            },
            complete: function() {
                Util.hideLoading();
            },
            error: function(errorRequest) {
                alert('Erro' + errorRequest);
                Util.hideLoading();
            },
            success: function(loadedContentHTML) {
                Util.hideLoading();
            }
        });

        // Abre a Nova Janela
        //newWindow = window.open(window.location.protocol + "//" + window.location.host + "/link.aspx?stShow=" + urlDestino, '_blank');
        //newWindow.focus();

        //return false;
    }
}