﻿var Noticias = {

    url: '/futebol/services/news',

    templateNoticia: "<li class=\"#CLASS#\"><div class=\"seta\"></div><span class=\"txtGray18\"><b>#DATA#</b></span><span class=\"txtSize15\"><a href='#LINK1#'>#TITULO#</a>&nbsp;-&nbsp;</span>#FONTE#</li>",

    className: 'even',

    list: null,

    listSearch: null,

    lastIndex: -1,

    time: "",

    initialize: function(time) {
        this.time = time
        this.get();
        this.list = new Array();
        this.listSearch = new Array();
        setInterval('Noticias.get()', 10000);
        setInterval('Noticias.showNews()', 120000);
    },

    contains: function(item) {
        if (null == Noticias.listSearch) return false;

        var ret;
        ret = false;

        for (i = 0; i < Noticias.listSearch.length; i++) {
            if (Noticias.listSearch[i] == item) {
                ret = true;
                break;
            }
        }
        return ret;

    },

    get: function() {
        $.getJSON(this.url+"/"+this.time,
            function(result) {

                $.each(result.noticias, function(i, noticia) {

                    if (!Noticias.contains(noticia.id)) {
                        var sNoticia = Noticias.templateNoticia.replace('#DATA#', noticia.data).replace('#TITULO#', noticia.titulo).replace('#FONTE#', noticia.fonte).replace('#TIME#', noticia.time).replace('#LINK1#', noticia.link);
                        Noticias.list.push(sNoticia);
                        Noticias.listSearch.push(noticia.id);
                    }
                });

                if (Noticias.lastIndex == -1) Noticias.showNews();
            });
    },


    updateClassName: function() {
        Noticias.className = (Noticias.className == 'odd') ? 'even' : 'odd';
    },

    showNews: function() {

        var lastIndex;
        lastIndex = (Noticias.lastIndex + 1);

        var add = false;

        if (lastIndex == 0) {
            for (i = 0; i < Noticias.list.length; i++) {
                $('#grid-noticias').prepend(Noticias.list[i].replace('#CLASS#', Noticias.className));
                Noticias.lastIndex += 1;

                add = true;
                Noticias.updateClassName();
            }
        }
        else {
            var i = (Noticias.lastIndex + 1);


            if (i < Noticias.list.length) {
                $('#grid-noticias').prepend(Noticias.list[i].replace('#CLASS#', Noticias.className));
                Noticias.lastIndex += 1;
                add = true;
                Noticias.updateClassName();
            }
        }


        if (add) {
	  jQuery('#grid-noticias').jScrollPaneNoticias({ showArrows: true });
        }
    }
}

