///////////////////////////////////////////////////////////////////////////////////////
// Cria pacote: com.webvenda.componentes
// Diego Nepomuceno - 06/02/09
///////////////////////////////////////////////////////////////////////////////////////
var com = com ? com : {}
com.webvenda = com.webvenda ? com.webvenda : {}
com.webvenda.componentes = com.webvenda.componentes ? com.webvenda.componentes : init

function init(sUrl) {

    //*********************************************
    // funções disponíveis nos objetos desta classe
    //*********************************************
    this.preencheDepartamento = preencheDepartamento;
    this.preencheFabricante = preencheFabricante;
    this.busca = busca;
    this.addCompraAtualNoAnalytics = addCompraAtualNoAnalytics;
    this.AdicionarLista = AdicionarLista;
    this.addCompraAtualNoLomadee = addCompraAtualNoLomadee;

    //*********************************************
    // funções disponíveis nos objetos desta classe
    //*********************************************
    if (sUrl != null && siteURL == null)
        siteURL = sUrl

    function preencheDepartamento(pdep) {
        $('select[@id=' + pdep.id + ']').html('<option value="-1">Procurando :::::::</option>');
        $.post('/' + siteURL + '/loja.aspx', { ajax: 'getDepartamentosOptions' },
			function (resposta) {
			    $('select[@id=' + pdep.id + ']').html(resposta);
			}
		);
    }

    function preencheFabricante(pfab) {
        $('select[@id=' + pfab.id + ']').html('<option value="-1">Procurando :::::::</option>');
        $.post('/' + siteURL + '/loja.aspx', { ajax: 'getFabricantesOptions' },
			function (resposta) {
			    $('select[@id=' + pfab.id + ']').html(resposta);
			}
		);
    }

    ///////////////////////////////////////////////////////////////////////////////////////
    // Componente Busca, permite que a busca seja utilizada em qualquer lugar da loja.
    // Diego Nepomuceno - 11/12/08
    ///////////////////////////////////////////////////////////////////////////////////////
    function busca() {
        this.fazBusca = fazBusca;
        //ordem do texto: nomeproduto,departamento,fabricante,valorminimo,valormaximo,ordem
        function fazBusca(prod, pdep, pfab, vmin, vmax, ord) {
            prod = (prod ? prod : '');
            pdep = (pdep ? pdep : 0);
            pfab = (pfab ? pfab : 0);
            vmin = (vmin ? vmin : 0);
            vmax = (vmax ? vmax : 0);
            ord = (ord ? ord : 2);
            var paginaBusca = '/' + siteURL + '/loja.aspx?tipobusca=2';
            paginaBusca += '&prod=' + prod;
            paginaBusca += '&pdep=' + pdep;
            paginaBusca += '&pfab=' + pfab;
            paginaBusca += '&vmin=' + vmin;
            paginaBusca += '&vmax=' + vmax;
            paginaBusca += '&ord=' + ord;
            try {
                window.event.returnValue = false;
            } catch (e) { }
            location.href = paginaBusca;
            return false;
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////
    // Função para monitorar transações de comércio eletrônico no analytics
    // Diego Nepomuceno - 02/06/09
    // Diego Nepomuceno - 14/02/11 - modificado para modo assincrono do analytics
    ///////////////////////////////////////////////////////////////////////////////////////
    function addCompraAtualNoAnalytics(codigoGA, idcompra) {
        var query = (idcompra != null ? '&idcompra=' + idcompra : '');

        $.ajax({
            type: "GET",
            url: "/admin/inbox/integracao/ajax.aspx?ajax=getCompra" + query,
            dataType: "xml",
            success: function (xml) {
                try {
                    _gaq.push(['_setAccount', codigoGA]);
                    _gaq.push(['_trackPageview']);

                    $(xml).find('Compras').find('Compra').each(function () {
                        var Compra = $(this);

                        var OrderID = Compra.find('OrderID').text();
                        var Affiliation = Compra.find('Affiliation').text();
                        var Total = Compra.find('Total').text();
                        var Tax = Compra.find('Tax').text();
                        var Shipping = Compra.find('Shipping').text();
                        var City = Compra.find('City').text();
                        var State = Compra.find('State').text();
                        var Country = Compra.find('Country').text();

                        _gaq.push(['_addTrans',
							OrderID,
							Affiliation,
							Total,
							Tax,
							Shipping,
							City,
							State,
							Country
						  ]);

                        Compra.find('Produtos').find('Produto').each(function () {
                            var Produto = $(this);

                            var SKU = Produto.find('SKU').text();
                            var ProductName = Produto.find('ProductName').text();
                            var Category = Produto.find('Category').text();
                            var Price = Produto.find('Price').text();
                            var Quantity = Produto.find('Quantity').text();

                            _gaq.push(['_addItem',
								OrderID,
								SKU,
								ProductName,
								Category,
								Price,
								Quantity
							]);
                        }); //close each(

                    }); //close each(

                    _gaq.push(['_trackTrans']);

                    (function () {
                        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
                        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
                    })();
                } catch (err) { };
            }
        }); //close $.ajax(

    };

    /*
    *Método que enviar dados para Lomadee de forma dinâmica.
    *@Param = IDAnunciante, Pais, IDEvento (opcional).
    *@Result = imagem com url dinâmica enviando dados para Lomadee;
    *Diego Nepomuceno - 17.05.11
    */
    function addCompraAtualNoLomadee(IDAnunciante, Pais, IDEvento) {
        $.ajax({
            type: "GET",
            url: "/admin/inbox/integracao/ajax.aspx?ajax=getCompra&Opcao=new",
            dataType: "xml",
            success: function (xml) {
                try {
                    var urlLomadee = 'https://secure.lomadee.com/at/actionlog?adv=' + IDAnunciante + '&country=' + Pais;
                    $(xml).find('Compras').find('Compra').each(function () {
                        var Compra = $(this);
                        var OrderID = Compra.find('OrderID').text();
                        var Total = Compra.find('Total').text();
                        urlLomadee += '&transaction=' + OrderID;
                        if (IDEvento != null) {
                            urlLomadee += '&value=' + Total;
                        } else {
                            var i = 0;
                            Compra.find('Produtos').find('Produto').each(function () {
                                var Produto = $(this);
                                var IDEventoLomadee = Produto.find('IDEventoLomadee').text();
                                var Price = Produto.find('Price').text();
                                var Quantity = Produto.find('Quantity').text();
                                var Total = (Price * Quantity);
                                i++;
                                urlLomadee += '&event' + i + '=' + IDEventoLomadee;
                                urlLomadee += '&value' + i + '=' + Total;
                            });
                        }
                    }); //close each de compra
                    //gera imagem dinamicamente
                    (function () {
                        var imagemLomadee = document.createElement('img');
                        imagemLomadee.src = urlLomadee;
                        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(imagemLomadee, s);
                    })();
                } catch (err) { };
            }
        });      //close $.ajax
    }

    function AdicionarLista(idProd) {
        var drp = document.getElementById('IDVariacao_' + idProd);
        var quantidade = document.getElementById('Qtd_' + idProd);
        var drpPrimeiroNivel = document.getElementById('IDVariacao_' + idProd + '_1');
        var drpSegundoNivel = document.getElementById('IDVariacao_' + idProd + '_2');
        var drpTerceiroNivel = document.getElementById('IDVariacao_' + idProd + '_3');
        var IDVar = 0;
        var nivel = 0;

        if (drpTerceiroNivel !== null) {
            IDVar = drpTerceiroNivel.options[drpTerceiroNivel.selectedIndex].value;
            if (IDVar == 0) {
                drpTerceiroNivel.style.backgroundColor = '#ff0000';
                alert('Por favor, selecione uma variação.');
                drpTerceiroNivel.focus();
                return;
            }
            nivel = 3;
        } else if (drpSegundoNivel !== null) {
            IDVar = drpSegundoNivel.options[drpSegundoNivel.selectedIndex].value;
            if (IDVar == 0) {
                drpSegundoNivel.style.backgroundColor = '#ff0000';
                alert('Por favor, selecione uma variação.');
                drpSegundoNivel.focus();
                return;
            }
            nivel = 2;
        } else if (drpPrimeiroNivel !== null) {
            IDVar = drpPrimeiroNivel.options[drpPrimeiroNivel.selectedIndex].value;
            if (IDVar == 0) {
                drpPrimeiroNivel.style.backgroundColor = '#ff0000';
                alert('Por favor, selecione uma variação.');
                drpPrimeiroNivel.focus();
                return;
            }
            nivel = 1;
        }

        var IDsPersonalizacoes = "";
        var RespostasPersonalizacoes = "";

        $(".Personalizacoes .Resposta").each(function () {
            if ($(this).val() != "") {
                IDsPersonalizacoes += $(this).parent().attr("class").split("_")[1] + ";";
                RespostasPersonalizacoes += $(this).val() + ";";
            }
        })

        IDsPersonalizacoes = (IDsPersonalizacoes == "", IDsPersonalizacoes, IDsPersonalizacoes.substring(0, IDsPersonalizacoes.length - 1));
        RespostasPersonalizacoes = (RespostasPersonalizacoes == "", RespostasPersonalizacoes, RespostasPersonalizacoes.substring(0, RespostasPersonalizacoes.length - 1));

        var str = '/' + siteURL + '/Listas/AdicionarMinhasListas.aspx?IDProduct=' + idProd + '&IDVar=' + IDVar + '&NivelDeVariacao=' + nivel + '&QtdProduto=' + quantidade.value + "&IDsPersonalizacoes=" + IDsPersonalizacoes + "&RespostasPersonalizacoes=" + RespostasPersonalizacoes;
        try {
            window.event.returnValue = false;
        } catch (e) { }
        location.href = str;
    }

}

///////////////////////////////////////////////////////////////////////////////////////
// Inclui bibliotecas necessárias para funcionamento deste
// Diego Nepomuceno - 04/06/09
///////////////////////////////////////////////////////////////////////////////////////
try {
    document.write(unescape("%3Cscript src='/_js/jquery.js' type='text/javascript'%3E%3C/script%3E"));
} catch (err) { }

try {
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
} catch (err) { }

///////////////////////////////////////////////////////////////////////////////////////
// Variáveis JavaScript acessiveis na página.
// Diego Nepomuceno - 01/07/09
///////////////////////////////////////////////////////////////////////////////////////
try {
    var _gaq = _gaq || [];
    var siteURL;
    var IPCliente;
    $.ajax({
        type: "GET",
        url: "/admin/inbox/integracao/ajax.aspx?ajax=getSiteURL",
        dataType: "string",
        success: function (xml) {
            siteURL = xml;
        }
    });

    $.ajax({
        type: "GET",
        url: "/admin/inbox/integracao/ajax.aspx?ajax=getIPCliente",
        dataType: "string",
        success: function (xml) {
            IPCliente = xml;
        }
    });
} catch (err) { }

///////////////////////////////////////////////////////////////////////////////////////
// Alerta padrão para produtos esgotados
// Diego Nepomuceno - 01/07/09
///////////////////////////////////////////////////////////////////////////////////////
function alertMaxVenda(arrAlertas) {
    if (arrAlertas != null) {
        var strAlerta = '';
        for (arrAlertas in alerta) {
            var ObjProduto = alerta;
            strAlerta += ("O produto \"" + ObjProduto.Name + "\" só pode ser vendido " + ObjProduto.RealQuantity + " unidades por vez.\n");
        }
        alert(strAlerta);
    }

}
