﻿//function toggleHeader(e) {
//	if($(e.currentTarget).hasClass("btVerPerfil") || $(e.currentTarget).hasClass("btFacaSeuLogin")) {
//		$("#divHeader").stop(true, true).slideDown(function() {
//			$("#divBarraPerfil a.btVerPerfil").hide();
//			$("#divBarraPerfil a.btEsconderPerfil").show();
//		});
//	} else if ($(e.currentTarget).hasClass("btEsconderPerfil")) {
//		$("#divHeader").stop(true, true).slideUp(function() {
//			$("#divBarraPerfil a.btEsconderPerfil").hide();
//			$("#divBarraPerfil a.btVerPerfil").show();
//		});
//	}
//}

function openPopup(url, width, height) {
    window.open(url, "_blank", "width=" + width + ",height=" + height + ",left=" + parseInt((screen.width / 2) - (width / 2)) + ",top=" + parseInt((screen.height / 2) - (height / 2)) + ",directories=no,status=no, linemenubar=no,scrollbars=no,resizable=no,modal=yes");
}

function toggleHeader() {
    $("#divHeaderPrincipalLogin").toggleClass("noBg");
}

function gotoPremios() {
    window.location = "/Premios/";
}

function atualizaCarrinho(ret, $this, add) {
    if ($("#divExtratoShopping ul").length <= 0) {
        $("#divExtratoShopping p").remove();
        $("#divExtratoShopping h3").after($("<ul />"));
        $("#divExtratoShopping input").show();
        $("#divExtratoShopping a.btAcessorios").remove();
    }
    $("#divExtratoShopping ul li, #divExtratoShopping p.error").remove();
    $("#divExtratoShopping ul li, #divExtratoShopping p.sucesso").remove();

    if (ret.produtos != undefined && typeof (ret.produtos) != 'undefined') {
        var TotalMoedas = new Array();

        $.each(ret.produtos, function() {
            if ($this == null && add == true) {
                var item = $("#divListagemProdutos ul li.item_" + this.id);
                item.addClass("inativo");
                $("button", item).hide();
            }
            if (this.moedas.length > 0)
                TotalMoedas.push(this.moedas);
            $("#divExtratoShopping ul").append('<li><span>' + this.titulo + '</span> <a href="" title="Remove Produto" pId="' + this.id + '"><img src="' + rootPath + '/Img/conteudo/Shopping/btRemoverItem.gif" alt="Remover" /></a></li>');
        });

        $("#divExtratoShopping ul").append(atualizaTotal(TotalMoedas));
    }

    if (add == true) {
        if ($this != null) {
            $this.parents("li").addClass("inativo");
            $this.hide();
        }
    }
    else {
        if (ret.produtos != undefined && typeof (ret.produtos) != 'undefined') {
            if (ret.produtos.length == 0) {
                $("#divExtratoShopping ul").remove();
                $("#divExtratoShopping h3").after($("<p />").text("Nenhum produto no carrinho"));
                $("#divExtratoShopping input").hide();
            }
        }

        if ($this != null) {
            var item = $("#divListagemProdutos ul li.item_" + $this.attr("pId"));
            item.removeClass("inativo");
            $("button", item).css("display", "block");
        }
    }
}

function atualizaTotal(TotalMoedas) {
    if (null != TotalMoedas && TotalMoedas.length > 0) {
        var ret = '<li class="sep"></li>\n';
        ret += '<li class="total"><span>Total:</span>\n';
        ret += '<ul>\n';
        var azul = 0, verde = 0, amarela = 0;
        $.each(TotalMoedas, function() {
            $(this).each(function() {
                switch (this.tipoMoeda) {
                    case 1:
                        azul += this.quantidade >= 0 ? this.quantidade : 0;
                        break;
                    case 2:
                        verde += this.quantidade >= 0 ? this.quantidade : 0;
                        break;
                    case 3:
                        amarela += this.quantidade >= 0 ? this.quantidade : 0;
                        break;
                }
            });
        });

        if (azul > 0)
            ret += '<li class="azul">' + azul + '</li>';
        if (verde > 0)
            ret += '<li class="verde">' + verde + '</li>';
        if (amarela > 0)
            ret += '<li class="amarela">' + amarela + '</li>';

        ret += '</ul>\n';
        ret += '</li>';
        return ret;
    } else return "";
}

function atualizaSaldo() {
    $.getJSON("/Util/Services/atualizarSaldo.aspx",
		function(ret, status) {
		    if (ret.code == 0) {
		        $("ul.lstMoedas li").remove();
		        $(".totalMoedas").text("");

		        if (ret.moedas != null && ret.moedas.length > 0) {
		            $.each(ret.moedas, function() {
		                switch (this.tipoMoeda) {
		                    case 1:
		                        $("ul.lstMoedas").append($("<li />").addClass("azul").text(this.quantidade));
		                        break;
		                    case 2:
		                        $("ul.lstMoedas").append($("<li />").addClass("verde").text(this.quantidade));
		                        break;
		                    case 3:
		                        $("ul.lstMoedas").append($("<li />").addClass("amarela").text(this.quantidade));
		                        break;
		                }
		            });

		            $(".totalMoedas").text(ret.totalMoedas);
		        }
		    }
		}
	);
}

function exibirFeedback(tipo) {
    switch (tipo) {
        case "cadastro":
            $("#divFeedbackCadastro").css('top', centralizaFeedback($("#divFeedbackCadastro").height()));
            $("#divFeedbackCadastro").show();
            $("#divOverlay").show();
            //$("body").append('<img height="1" width="1" src="http://view.atdmt.com/action/frcvvo_VivoCOPAConfirmao_1"/>');
            break;
        case "avatarFinalizado":
            $("#divFeedbackAvatarCriado").css('top', centralizaFeedback($("#divFeedbackAvatarCriado").height()));
            $("#divFeedbackAvatarCriado").show();
            $("#divOverlay").show();
            break;
        case "primeiroLogin":
            $("#divFeedbackLoginInicial").css('top', centralizaFeedback($("#divFeedbackLoginInicial").height()));
            $("#divFeedbackLoginInicial").show();
            $("#divOverlay").show();
            break;
        case "faleconosco":
            $("#divFaleConoscoEnviado").css('top', centralizaFeedback($("#divFaleConoscoEnviado").height()));
            $("#divFaleConoscoEnviado").show();
            $("#divOverlay").show();
            break;
        case "migracao":
            $("#divFeedbackMigracao").css('top', centralizaFeedback($("#divFeedbackMigracao").height()));
            $("#divFeedbackMigracao").show();
            $("#divOverlay").show();
            break;
        case "logar":
            $("#divFeedbackLogar").css('top', centralizaFeedback($("#divFeedbackLogar").height()));
            $("#divFeedbackLogar").show();
            $("#divOverlay").show();
            break;
        case "sucessoQuiz":
            $("#divSucessoQuiz").css('top', centralizaFeedback($("#divSucessoQuiz").height()));
            $("#divSucessoQuiz").show();
            $("#divOverlay").show();
            break;   
    }

}

function centralizaFeedback(heightDiv) {
    return (parseInt($(window).scrollTop()) + (parseInt($(window).height() / 2))) - parseInt(heightDiv) / 2;
}

function checkFirstLogin() {
    if ($("#divHeaderPrincipalPerfil").length > 0) {
        $.post("/Util/Services/verificaLogin.aspx", function(ret) {
            if (ret == 1)
                exibirFeedback('primeiroLogin');
        });
    }
}

function carregaParticipantes(participantes, parent, e) {
    var ul = $('<ul />');
    var serviceParticipante = new ServiceParticipante();
    var participanteLogado = serviceParticipante.obterIdParticipanteLogadoEncrypted();

    $.each(participantes, function() {
        var item = e.clone();
        item.attr("pId", this.id);
        $(".divAddFavorito", item).remove();

        if (participanteLogado != "" && null != participanteLogado) {
            if (serviceParticipante.checkFavoritosEncrypted(participanteLogado, this.id) == false && participanteLogado != this.id)
                $("div.img", item).append($('<div class="divAddFavorito"><a href="" title="Adicionar aos favoritos">Adicionar aos favoritos<div class="balao"></div></a></div>'));
        }
        $("img", item).attr({ "src": this.Imagem, "alt": this.nome });
        $(".Descricao, h4 > a", item).attr({ "href": "/Perfil/?uid=" + this.cpf, "title": this.nome });
        $(".Descricao, h4 > a", item).find("label").text(this.nome);
        ul.append(item);
        item = null;
    });
    removeLoading(parent);
    $(parent).prepend(ul);
}

function showLoading(e) {
    var ret = $("ul li:eq(0)", e).attr("src", "").clone()
    $("ul", e).remove();
    e.append($('<div class="divLoading"></div>'));
    return ret;
}

function removeLoading(e) {
    $("div.divLoading", e).remove();
}

function carregarRecados(id, page, pageSize, container, callback) {
    $.getJSON("/Util/Services/paginarRecados.aspx",
		{
		    participanteId: id,
		    page: page,
		    pageSize: pageSize
		},
		function(ret, status) {
		    if (ret.code == 0) {
		        if (typeof (callback) === 'function')
		            callback.call(ret.recados, container);
		    }
		    else alert(ret.mensagem);
		}
	);
}

function carregarFavoritos(id, container, callback) {
    $.getJSON("/Util/Services/paginarFavoritos.aspx",
		{
		    participanteId: id		},
		function(ret, status) {
		    if (null != ret) {
		        if (ret.code == 0) {
		            if (typeof (callback) === 'function')
		                callback.call(ret.favoritos, container);
		        }
		        else alert(ret.mensagem);
		    }
		}
	);
}

function carregarFavoritado(id, page, pageSize, container, callback) {
    $.getJSON("/Util/Services/paginarFavoritado.aspx",
		{
		    participanteId: id,
		    page: page,
		    pageSize: pageSize
		},
		function(ret, status) {
		    if (ret.code == 0) {
		        if (typeof (callback) === 'function')
		            callback.call(ret.favoritos, container);
		    }
		    else alert(ret.mensagem);
		}
	);
}


function carregarTweets() {
    $.getJSON("/Util/Services/getTweets.aspx", { pg: 1, ps: 3 }, function(ret) {
        if (null != ret) {
            for (var i = 0; ret.length > i; i++) {
                $("#footerTwitter .scroll").append("<p>" + ret[i].titulo + "</p>");
            }
        }
    });

}

function carregarPostBlog() {
    $.post('/util/Services/carregarPostBlog.aspx', function(data) {
        var post = $.xmlToJSON(data);
        var texto = post.channel[0].item[0].description[0].Text;
        var titulo = post.channel[0].item[0].title[0].Text;
        var creator = post.channel[0].item[0].creator[0].Text;
        var data = post.channel[0].item[0].pubDate[0].Text;
        var link = post.channel[0].item[0].link[0].Text;
        var dataAux = data.split(" ");
        data = dataAux[0] + " " + dataAux[2] + " " + dataAux[1] + " " + dataAux[4] + " CET " + dataAux[3];

        $("h4 a", $("#footerBlog")).attr("href", link).attr("title", titulo).text(titulo);
        $("p.dataVivoBlog", $("#footerBlog")).html("Por " + creator + " em " + $.format.date(data, "dd/MM/yyyy"));
        $("div.scroll", $("#footerBlog")).html(texto);
    });

}

var lastPageComentarios = 1;
var lastPageNoticias = 1;

function carregarComentariosNoticia(noticiaId, page, pageSize, container) {
    setarRetornoComentarios(0);
    $.getJSON('/Util/Services/carregarComentariosNoticia.aspx',
        {
            noticiaId: noticiaId,
            page: page,
            pageSize: pageSize
        },
        function(ret) {
            if (null != ret) {
                if (parseInt(ret.code) == 0) {
                    var ul = $("<ul />");
                    var default_element = $('<li><a href="" title=""><img src="" alt="" width="73" height="73" /></a><p></p></li>');

                    if (null != ret.comentarios) {
                        setarRetornoComentarios(1);
                        $.each(ret.comentarios, function(i, el) {
                            var item = default_element.clone();
                            $("a", item).attr({
                                "href": this.url,
                                "title": this.titulo
                            });

                            $("a img", item).attr({
                                "src": this.thumb,
                                "alt": this.titulo
                            });

                            $("p", item).text(this.titulo);

                            ul.append(item);
                            if (i < (ret.comentarios.length - 1))
                                ul.append('<li class="sep"></li>');
                        });

                        if ($("> ul", $(container)).length > 0) {
                            ul.prepend('<li class="sep"></li>');
                            $("ul", $(container)).append($("li", ul));
                        }
                        else {
                            $(container).append(ul);
                        }

                        $(container).jScrollPaneAux({
                            scrollbarWidth: 14,
                            scrollbarHeight: 263,
                            dragMinHeight: 37,
                            dragMaxHeight: 37,
                            percentLoadMore: 0.8,
                            onContentEnd: function(scroll, oi) {

                                var noticiaId = $("body").hasClass("home") ? 0 : parseInt($("input[type=hidden].hiddenIdNoticiaPrincipal").val());

                                if (!isNaN(noticiaId)) {
                                    var page = parseInt($("input.hiddenComentariosPage").val()) + 1;

                                    if (lastPageComentarios != page) {
                                        carregarComentariosNoticia(noticiaId, page, 15, container);

                                        setTimeout(function() {
                                            if (lastPageComentarios == 1) {
                                                $("input.hiddenComentariosPage").val(page);
                                                scroll.data('loadingMore', false);
                                            }
                                        }, 1000);
                                    }
                                }
                            }
                        });
                        ul = null;
                    }
                    else {
                        if ($(".btnComentarNoticia", $(container)).length == 0) {
                            $(container).append('<p align="center"><a href="" class="btnComentarNoticia"><img alt="Seja o primeiro a comentar esta notícia" src="/Util/Img/home/imgTxtSejaPrimeiroComentar.gif"></a></p>');
                        }
                    }
                }
            }
        }
    );
}

function carregarUltimasNoticias(page, pageSize, container) {
    setarRetornoNoticias(0);
    var request = $.getJSON('/util/Services/carregarUltimasNoticias.aspx',
        {
            page: page,
            pageSize: pageSize
        },
        function(ret) {
            var retorno = null;
            if (null != ret) {
                if (parseInt(ret.code) == 0) {
                    var ul = $("<ul />");
                    var default_element = $('<li><h4><a title="" href=""></a></h4></li>');

                    if (null != ret.noticias) {
                        setarRetornoNoticias(1);
                        $.each(ret.noticias, function(i) {
                            var item = default_element.clone();
                            $("h4 a", item).attr({
                                "href": "/Noticias/?id=" + this.id,
                                "title": this.titulo
                            }).text(this.titulo);

                            if (null != this.subtitulo && this.subtitulo != "")
                                item.append('<p>' + this.subtitulo + '</p>')

                            ul.append(item);

                            if (i < (ret.noticias.length - 1))
                                ul.append('<li class="sep"></li>');
                        });

                        if ($("> ul", $(container)).length > 0) {
                            ul.prepend('<li class="sep"></li>');
                            $("ul", $(container)).append($("li", ul));
                        }
                        else {
                            $(container).append(ul);
                        }

                        $(container).jScrollPaneAux({
                            scrollbarWidth: 14,
                            scrollbarHeight: 360,
                            dragMinHeight: 37,
                            dragMaxHeight: 37,
                            percentLoadMore: 0.8,
                            onContentEnd: function(scroll, oi) {
                                var page = parseInt($("input[type=hidden].hiddenMaisNoticiasPage").val()) + 1;

                                if (lastPageNoticias != page) {
                                    carregarUltimasNoticias(page, 15, container);
                                    setTimeout(function() {
                                        if (lastPageNoticias == 1) {
                                            $("input.hiddenMaisNoticiasPage").val(page);
                                            scroll.data('loadingMore', false);
                                        }
                                    }, 1000);
                                }
                            }
                        });

                        ul = null;
                    }
                }
            }
            return retorno;
        }
    );
}

function setarRetornoComentarios(val) {
    lastPageComentarios = val;
}

function setarRetornoNoticias(val) {
    lastPageNoticias = val;
}



/*****************************************************************
jquery upload de fotos - Cadastro de Participantes
*****************************************************************/
function UploadFotos(pathSite, pathUpload, btnProcurar, txtCaminhoImagem, imgFoto, hfNomeFoto) {
    var upload1;
    $(document).ready(function() {
        var button1 = $('#' + btnProcurar), interval;

        upload1 = new AjaxUpload(button1,
        {
            action: pathSite + 'Util/Services/UploadFotoParticipante.ashx',
            name: 'fileUpload1',
            autoSubmit: true,

            onChange: function(file, extension) {

                $('#' + imgFoto).css('display', 'none');
            },

            onSubmit: function(file, ext) {
                this.disable();
                interval = window.setInterval(function() {
                    var text = button1.text();
                }, 200);
            },

            onComplete: function(file, response) {

                response = response.split("||||")[1];

                if (response == "ERROR") {
                    document.getElementById(txtCaminhoImagem).value = "Imagem com tamanho inv\xE1lido";
                    document.getElementById(hfNomeFoto).value = "ERRO";
                }
                else {
                    document.getElementById(hfNomeFoto).value = response;
                    document.getElementById(txtCaminhoImagem).value = file;
                }

                window.clearInterval(interval);
                this.enable();
                $('#' + imgFoto).css('display', '');

                if (response != "ERROR") {
                    $('#' + imgFoto).attr('src', pathUpload + response);
                }
                else
                    $('#' + imgFoto).attr('src', pathSite + "util/img/conteudo/foto_usuario.gif");
            }
        });
    });
}

