/**
 * Variaveis globais do Javascript
 */
var arBanner;
var idxBanner;
var iChangeTime;
var iCountTime;
var sTrackAccount;

function showLoading(call) {
    $("#loading").fadeIn("fast", function() {
        if (call)
            call();
    });
}

function hideLoading() {
    $("#loading").fadeOut("fast");
}

/**
 * Retorna os dados do php serializado
 */
function getObject(sUrl, obDados) {
    // Inicia a variavel do retorno
    var retorno = "";
    
    // Inicia o objeto de parametros
    if (! obDados)
        obDados = {};

    // Define o path
    if (obDados.path == undefined)
        obDados.path = "";

    // Verifica se foi define se asyncrono ou naum
    if (obDados.async == undefined)
        obDados.async = false;

    // Serializa os parametros
    var sParam = "";
    if (obDados.param)
        sParam = $.toJSON(obDados.param);

    $.ajax({
        cache: false,
        async: obDados.async,
        type : "POST",
        data : "&modulo=js"+
               "&acesso=getObjectFileValue"+
               "&file="+sUrl+
               "&funcao="+obDados.funcao+
               "&param="+sParam,
        url  : obDados.path+"acesso.php",
        success: function(msg) {
            if (msg != "") {
                try {
                    retorno = $.parseJSON(msg);

                    if (obDados.onRetorno)
                        obDados.onRetorno(retorno);

                } catch(e) {
                    retorno = msg;
                }
            }

            hideLoading();
        }
    });
    
    return retorno;
}

/**
 * Função que chama uma página
 */
function getPage(sUrl, obDados) {
    showLoading();

    // Inicia a variavel do retorno
    var retorno = "";

    // Inicia o objeto de parametros
    if (! obDados)
        obDados = {};

    // Define o path
    if (obDados.path == undefined)
        obDados.path = "";

    // Verifica se foi define se asyncrono ou naum
    if (obDados.async == undefined)
        obDados.async = false;

    // Serializa os parametros
    var sParam = "";
    if (obDados.param)
        sParam = $.toJSON(obDados.param);
    
    // Chama a página
    $.ajax({
        cache: false,
        async: obDados.async,
        type : "POST",
        data : "param="+sParam,
        url  : sUrl,
        success: function(msg) {
            if (msg != "") {
                retorno = msg;
                
                if (obDados.onRetorno)
                    obDados.onRetorno(retorno);

                hideLoading();
            }
        }
    });

    return retorno;
}

/**
 * Função que inicia os banners
 */
function iniciaBanners(iTime) {
    // Define o tempo de troca
    iChangeTime = iTime;

    // Chama o ajax que pega as imagens
    getObject("utils.php", {
       funcao: "getBanners",
       async : true,
       onRetorno: function(ret) {
           if (ret != false) {
                // Salva o array de banner
                arBanner  = ret;
                idxBanner = 0;

                // Monta o HTML do Navigator
                var sNavi    = "<table><tr>";
                var sDivImgs = "";
                for(var x = 0; x < arBanner.length; x++) {
                    sNavi    += "<td><div class='banner_button banner_button_off' id='"+x+"'>"+(x+1)+"</div></td>"

                    // Verifica se tem click
                    var sStyle = "";
                    var onClick = "";
                    if (
                        ((arBanner[x][1] != "") && (arBanner[x][1] != null)) ||
                        ((arBanner[x][2] != "") && (arBanner[x][2] != null)) ||
                        ((arBanner[x][3] != "") && (arBanner[x][3] != null))
                    ) {
                        sStyle = "cursor:pointer";

                        if ((arBanner[x][2] != "") && (arBanner[x][2] != null))
                            onClick = "onClick=\"javascript:abrePaginaSite("+arBanner[x][2]+");\"";
                        else
                        if ((arBanner[x][3] != "") && (arBanner[x][3] != null))
                            onClick = "onClick=\"javascript:abreInscricaoSite("+arBanner[x][3]+");\"";
                        else
                            onClick = "onClick=\"javascript:document.location='"+arBanner[x][1]+"';\"";

                    }

                    // Monta o HTML do Banner
                    sDivImgs += "<img id='img_"+x+"' src='"+arBanner[x][0]+"' style='display:none;"+sStyle+"' "+onClick+" width='400'>";
                }
                sNavi += "</tr></table>";
                $("#banner_navigator").html(sNavi);
                $("#banner_imgs").html(sDivImgs);

                // Faz o onclick do navigator
                $(".banner_button").click(function() {
                    trocaBanner($(this).attr("id"));
                });

                // Tira o carregando
                $("#banner_image").fadeOut("normal", function() {
                    // Esconde o carregando
                    $("#banner_image").hide();
                    
                    // Troca o banner
                    trocaBanner(0);

                    setInterval(function() {
                        verificaChange();
                    }, 1000);
                });

           }           
       }
    });
}

/**
 * Função resposanvel pelo efeito de troca de banner
 */
function trocaBanner(idx) {
    // Zera o tempo de troca
    iCountTime = 0;
    
    // Troca a class do botão antigo
    $("#"+idxBanner).removeClass("banner_button_on");
    $("#"+idxBanner).addClass("banner_button_off");

    $("#img_"+idxBanner).fadeOut("normal", function() {
        // Passa para o proximo
        idxBanner++;
        if (idxBanner > (arBanner.length-1))
            idxBanner = 0;


        // Verifica qual deve mostrar
        if (idx != undefined)
            idxBanner = idx;

        // Coloca a class no novo
        $("#"+idxBanner).removeClass("banner_button_off");
        $("#"+idxBanner).addClass("banner_button_on");

        $("#img_"+idxBanner).fadeIn("normal");
    });
}

/**
 * Verifica se tem que trocar imagem
 */
function verificaChange() {
    iCountTime++;
    if (iCountTime == iChangeTime)
        trocaBanner();
}

/**
 * Implementa a rotina de replaceAll
 */
String.prototype.replaceAll = function(sSearch, sReplace, bInsensitive){
   if (bInsensitive)
      return this.replace(new RegExp(sSearch,'gi'), sReplace);
   else
      return this.replace(new RegExp(sSearch,'g'), sReplace);
}

/**
 * Abre um HTML da pagina
 */
function abrePaginaSite(cod) {
    showLoading(function() {
        $("#div_pagina").fadeOut("normal", function() {
            getObject("utils.php", {
                funcao: "getPaginaSite",
                async : true,
                param : [cod],
                onRetorno: function(ret) {
                    if (ret != false) {
                        // Arruma o HTML
                        var sVlr = ret['html'];
                        sVlr     = sVlr.replaceAll("BNhv", "&");

                        // Coloca o HTML
                        $("#div_pagina").html(sVlr);
                        $("#div_pagina").fadeIn("normal", function() {
                            // Envia o tracker para o Google
                            sendTracker("/"+ret['pagina']);

                            hideLoading();
                        });
                    }
                }
            });
        });
    });
}

/**
 * Executa o Tracker do google
 */
function sendTracker(sUrl) {
    try {
        var pageTracker = _gat._getTracker(sTrackAccount);
        if (sUrl == undefined)
            pageTracker._trackPageview("/");
        else
            pageTracker._trackPageview(sUrl);
    } catch(err) {}
}

/**
 * Converte a data
 */
function ConverteData(sData) {
    if (sData == null) {
        return "";
    } else
    if (sData.indexOf("/") > -1) {
        var arData = sData.split("/");
        return arData[2]+"-"+arData[1]+"-"+arData[0];
    } else
    if (sData.indexOf("-") > -1) {
        var arData = sData.split("-");
        return arData[2]+"/"+arData[1]+"/"+arData[0];
    } else
        return "";
}


/**
 * Abre noticia no painel de notícias
 */
function abreNoticia(codigo) {
    showLoading(function() {
        $("#nome_noticia").fadeOut("normal");
        $("#html_noticia").fadeOut("normal", function() {
                getObject("utils.php", {
                funcao: "getNoticiaSite",
                async : true,
                param : [codigo],
                onRetorno: function(ret) {
                    if (ret != false) {
                        var sVlr = ret['html'];
                        sVlr     = sVlr.replaceAll("BNhv", "&");

                        $("#html_noticia").html(sVlr);
                        $("#nome_noticia").html(ret['titulo']);

                        sendTracker("/"+ret['pagina']);
                    }

                    $("#nome_noticia").fadeIn("normal");
                    $("#html_noticia").fadeIn("normal", function() {
                        hideLoading();
                    })
                }
            });            
        });
    });
}

function openImage(albcodigo, aftcodigo, tag) {    
    if (tag) {
        $("#div_"+tag).fadeOut(750, function() {
            $(".fotos_album_"+albcodigo).hide();
            $("#img_"+tag+"_"+aftcodigo).show();

            $("#div_"+tag).fadeIn(750);
        });
    } else {
        var sUrl = "album.php?tipo=getimage&albcodigo="+albcodigo+"&aftcodigo="+aftcodigo;
        window.open(sUrl, "fotoEnergia", "menubar=no,location=no,resizable=no,scrollbars=no,status=yes,width=640,height=480");
    }
}

function abreEvento(albcodigo) {
    window.open("aguarde.html", "fotoEnergia_Album_"+albcodigo, "menubar=no,location=no,resizable=no,scrollbars=no,status=yes,width=700,height=400");

    setTimeout(function() {
        var sUrl = "album.php?tipo=getalbum&albcodigo="+albcodigo;
        window.open(sUrl, "fotoEnergia_Album_"+albcodigo, "menubar=no,location=no,resizable=no,scrollbars=no,status=yes,width=700,height=400");        
    }, 200);
}

function abreInscricaoSite(inscodigo) {
    var sUrl = "inscricao.php?inscodigo="+inscodigo;
    window.open(sUrl, "fotoEnergia", "menubar=no,location=no,resizable=no,scrollbars=yes,status=yes,width=640,height=550");

}

function trim(s) {
    return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}

