(function ($) {
    $.fn.kEroFotografo = function (options) {
		var $div = $(this).selector;
		$($div).html('<div id="toda_api"><div class="fotPaginacao"></div><div class="fotBusca"><select id="selectGrupos" class="ComboGrupos" onchange="$(this).kEroFotografo.FiltrarEventos()"></select><input type="text" id="txtDescricao" class="busca" value="Pesquisar..." /><input type="button" onclick="$(this).kEroFotografo.FiltrarEventos()" class="btBusca"/></div><div id="carinho" class="fotCarrinho"></div><div class="fotEventos"><div id="EventosFotografo">Aguarde, carregando</div><div id="TempEventos"></div></div></div>');
        $("#txtDescricao").focusin(function () {
            if ($(this).val() == "Pesquisar...") {
                $(this).val("");
            }
        });
        $("#txtDescricao").focusout(function () {
            if ($(this).val() == " ") {
                $(this).val("Pesquisar...");
            }
        });
        $.ajax({
            url: "http://api.zyoncore.com.br/script/jquery.cookie.js",
            dataType: "script",
            success: function () {
                link2();
            }
        });
        link2 = function () {
            $.ajax({
                url: "http://api.zyoncore.com.br/script/EventosPrincipais.js",
                dataType: "script",
                success: function () {
                    link3();
                }
            });
        }

        link3 = function () {
            $.ajax({
                url: "http://api.zyoncore.com.br/script/jquery.pagination.js",
                dataType: "script",
                success: function () {

                    var opts = $.extend({}, $.fn.kEroFotografo.defaults, options);
                    var cookieAcesso = $.cookie("Acesso");
                    if (cookieAcesso != null) {
                        _idAcesso = cookieAcesso;
                    } else {
                        _idAcesso = 0;
                    }
                    var url = "http://api.zyoncore.com.br/AcessoCarrinhoFotografo.aspx?idFotografo=" + options._idFotografo + "&idAcesso=" + _idAcesso + "&callback=?";
                    jQuery.getJSON(url, function (data) {
                        if (data.CarrinhoEmAberto == true) {
                            var htmlCarrinho = "<a href='" + data.UrlCarrinhoCompras + "'>";
                            htmlCarrinho += "<span>Vocę possui " + data.CarrinhoFotografo.NumeroCompras + " pedido(s) em aberto(s), no total de " + data.CarrinhoFotografo.ValorCompra + "</span></a>";
                            $("#carinho").html(htmlCarrinho);
                            $("#carinho").show();
                        };
                        _idAcesso = data.IdAcesso;
                        $.cookie("Acesso", _idAcesso, {
                            expires: 1
                        });
                        if (options._ordenacao == '' || options._ordenacao == undefined) {
                            options._ordenacao = 2
                        }
                        if (options._idGrupo != undefined) {
                            url = "http://api.zyoncore.com.br/EventoPrincipal.aspx?idFotografo=" + options._idFotografo + "&idAcesso=" + _idAcesso + "&idGrupo=" + options._idGrupo + "&ordenacao=" + options._ordenacao + "&callback=?";
                            $('#debuger').append(url);
                        } else {
                            url = "http://api.zyoncore.com.br/EventoPrincipal.aspx?idFotografo=" + options._idFotografo + "&idAcesso=" + _idAcesso + "&ordenacao=" + options._ordenacao + "&callback=?";
                            $('#debuger').append(url);
                        }
                        jQuery.getJSON(url, function (data) {
                            _eventos = data.itens;
                            $.fn.kEroFotografo.PreecherListaEventos(_eventos);
                        });
                    })
                    $("#selectGrupos option").remove();
                    $("#selectGrupos").append("<option value='0'>Todos</option>");
                    var url = "http://api.zyoncore.com.br/GruposEventos.aspx?idFotografo=" + options._idFotografo + "&callback=?";
                    jQuery.getJSON(url, function (data) {
                        $.each(data.itens, function (i, grupoEvento) {
                            $("#selectGrupos").append("<option value=" + grupoEvento.IdGrupo + ">" + grupoEvento.Descricao + "</option>");
                        })
                    })
                    $.fn.kEroFotografo.PreecherListaEventos = function (listaEventos) {
                        var htmlProdutos = "";
                        $.each(listaEventos, function (i, eventoPrincipal) {
                            if (eventoPrincipal.IsSenha) {
                                htmlProdutos += "<div class='fotEvento'><a href='javascript:;'onclick='" + eventoPrincipal.AcaoDoClick + "'>";
                            } else {
                                htmlProdutos += "<div class='fotEvento'><a href=" + eventoPrincipal.AcaoDoClick + " target='_parent'>";
                            }
                            htmlProdutos += "<div class='img'><img src='" + eventoPrincipal.UrlImagemCapaEvento + "' /></div>";
                            htmlProdutos += "<div class='data'>" + eventoPrincipal.DataEvento + "</div>";
                            htmlProdutos += "<div class='descricao'>" + eventoPrincipal.Descricao + "</div>";
                            htmlProdutos += "</a></div>";
                        });
                        $("#TempEventos").html(htmlProdutos);
                        $.fn.kEroFotografo.IniPaginacao();
                    }
                    $.fn.kEroFotografo.IniPaginacao = function () {
                        var num_entries = $('#TempEventos .fotEvento').length;
                        $(".fotPaginacao").pagination(num_entries, {
                            num_edge_entries: options._itensFinais,
                            num_display_entries: options._itensIniciais,
                            callback: $.fn.kEroFotografo.pageselectCallback,
                            items_per_page: options._itensPorPagina
                        })
                    }
                    $.fn.kEroFotografo.pageselectCallback = function (page_index, jq) {
                        var num_entries = $('#TempEventos .fotEvento').length;
                        var items_per_page = options._itensPorPagina;
                        if (num_entries != 0) {
                            var max_elem = Math.min((page_index + 1) * items_per_page, num_entries);
                            var newContent = '';
                            for (var j = page_index * items_per_page; j < max_elem; j++) {
                                newContent += "<div class='fotEvento'>";
                                newContent += $('#TempEventos .fotEvento:eq(' + j + ')').html();
                                newContent += "</div>";
                            }
                        } else {
                            newContent = "Nenhum evento cadastrado";
                        }
                        $($div).animate({
                            opacity: 0.10
                        }, 500, function () {
                            $(this).animate({
                                opacity: 1
                            });
                            $("#EventosFotografo").html(newContent);
                        });
                        return false;
                    }
                    $.fn.kEroFotografo.Autenticar = function () {
                        $("#lblMensagem").text("aguarde, autenticando");
                        var usuario = $("#usuario").val();
                        var senha = $("#senha").val();
                        var url = "http://api.zyoncore.com.br/AutenticarUsuarioEvento.aspx?idFotografo=" + options._idFotografo + "&idEventoPrincipal=" + _idEventoPrincipal + "&usuario=" + usuario + "&senha=" + senha + "&idAcesso=" + _idAcesso + "&callback=?";
                        jQuery.getJSON(url, function (data) {
                            if (data.Autenticou == true) {
                                $("#lblMensagem").text("Autenticado, aguarde redirecionando...");
                                window.parent.location = data.UrlEvento;
                            } else {
                                $("#lblMensagem").text("Usuário ou senha inválidos");
                            }
                        })
                    }

                }
            });
        }
    }


    $.fn.kEroFotografo.fotFechar = function () {
        $('#mascara,#fotLogar').toggle();
		$('#mascara,#fotLogar').remove();
        $("#lblMensagem").html('');
        $("#usuario,#senha").val('');
    }
    $.fn.kEroFotografo.solicitarAutenticacao = function (idEvento) {
		$('body').append('<div id="mascara"></div>');
		$('body').append('<div id="fotLogar"><h2><span id="fotFechar" onClick="$(this).kEroFotografo.fotFechar()">Fechar</span></h2><span id="lblMensagem" class="fotMensagem"></span><label class="usuario"><span>Usu&aacute;rio:</span><input type="text" id="usuario" /></label><label class="senha"><span>Senha:</span><input type="password" id="senha" /></label><label class="fotLogar"><input type="button" onClick="$(this).kEroFotografo.Autenticar();" /></label></div>');

		_idEventoPrincipal = idEvento;
        //marcara
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
        $('#mascara').css({
            'width': maskWidth,
            'height': maskHeight
        });
        $('#mascara').css('height', $(document).height()).hide();

        var winH = $(window).height();
        var winW = $(window).width();

        $('#fotLogar').css('top', winH / 2 - $('#fotLogar').height() / 2);
        $('#fotLogar').css('left', winW / 2 - $('#fotLogar').width() / 2);
        $('#mascara,#fotLogar').toggle();
        $('#mascara').fadeTo("slow", 0.8);

    }
    $.fn.kEroFotografo.FiltrarEventos = function () {
        var idGrupo = $("#selectGrupos").val();
        var descricao = $("#txtDescricao").val();
        if (descricao == 'Pesquisar...') {
            descricao = '';
        }
        $.fn.kEroFotografo.PreecherListaEventos(retornarListaFiltrada(_eventos, idGrupo, descricao));
    }


    $(function () {

    })
})(jQuery);
