<script type="text/javascript">

//  OpenProximity2.0 is a proximity marketing OpenSource system.
//  Copyright (C) 2010,2009 Naranjo Manuel Francisco <manuel@aircable.net>
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation version 2 of the License.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License along
//  with this program; if not, write to the Free Software Foundation, Inc.,
//  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

var last_post = null;
var queue = Array();

function sort_queue(a, b){
    return a.pk - b.pk
}

function update_posts(){
    var url;
    if ( last_post != null )
        url = '{{url}}/posts/?pk=' + escape(last_post);
    else
        url = '{{url}}/posts/?amount={{ amount }}';
    $.ajax(url, {
        'cache': false,
        'success': function(posts){
            var mesg = $('#{{ element }}');
            for ( var i in posts ){
                var post = posts[i]
                queue.unshift(post)
            }
            queue.sort(sort_queue)

            while ( queue.length > {{ amount }})
                queue.shift()

            var out = "";

            for ( var i in queue ){
                var post = queue[i]
                {% autoescape off %}
                    out = {{ line_format }} + out;
                {% endautoescape %}
            }
            mesg.clear();
            mesg.append($("<pre>"+out+"</pre>"));
        },
        'error': function(){
            var mesg = $("#{{ element }}");
            mesg.text("There are no messages");
        }
    });
}

function check_last_post(){
    $.ajax('{{ url }}/latest/',{
        'cache': false,
        'success': function(meta) {
            if (last_post != meta[0].{{field}}){
                update_posts();
                last_post = meta[0].{{field}};
            }
        },
        'error': function(){
            var mesg = $("#{{ element }}");
            mesg.text("There are no messages");
        }
    });
}

check_last_post()

setInterval("check_last_post()", {{ interval }}000)

</script>

