(function($){

$.fn.alertticker = function(o){

var $$ = this,
    fetchtimer = false,
    opts = $.extend({
        rate: 8000,
        displaycount: 3
    },o);
$$.data('placeinline',0);
$$.data('tries',1);

function _fix_alertbox_height(){
    var $clone = $$.clone();
    for(i=0;i<opts.displaycount;i++){
        $clone.append(_generate_list_item({logo:'http://local.nixle.com/static/img/ui/nologo_48.png',level:'Alert',time:'2 hours ago',agency:'Sample Agency',agency_link:'',headline:'Sample headline',link:''}));
    }
    var aheight = $clone.css({'visibility':'hidden'}).appendTo('#alerts_liner').height();
    $$.css({"height":aheight, "max-height":aheight,"overflow":"hidden"});
    $clone.remove();
};

function _fetch_alerts(extra_callback){
    var alertsXHR = $.ajax({
        url:'http://local.nixle.com/latestalerts/?jsoncallback=?',
        dataType:'json',
        success:function(d){
            clearInterval(fetchtimer);
            if(typeof d.latest_alerts != 'undefined' && d.latest_alerts != null){
                $$.data('alerts',d.latest_alerts);
                $$.data('tries',0);
            }else if(!$$.data('alerts')){
                _default_to_noscript();
            }
        }
    });
    var c = extra_callback || false;
    if(c){ alertsXHR.success(c); }
};

function _fetch_initial_alerts(){
    if($$.data('tries')<3){
        $$.data('tries',$$.data('tries')+1);
        _fetch_alerts(_initial_populate);
    }else{
        _default_to_noscript();
        clearInterval(fetchtimer);
        $$.data('tries',0);
    }
}

function _initial_populate(data){
    if($$.data('alerts').length>0){
        $('#tickerheader').html('Recent Publications');
        var d = data || $$.data('alerts'),
            f = $(document.createDocumentFragment());
        if(typeof d.latest_alerts != 'undefined'){ d = d.latest_alerts; }
        for(i=0;i<opts.displaycount;i++){ $$.prepend(_generate_list_item(d[i])); }
        $$.data('placeinline',opts.displaycount);
        setInterval(_insert_list_item, opts.rate);
        setInterval(_fetch_alerts, 600000); //<-- or something to refresh set of alerts every 10 minutes
    }else{
        _default_to_noscript();
    }
};

function _default_to_noscript(){
    var noscr='<li><img src="http://i.nixle.com/uploads/agency_logos/sm/user750-1254527437-lacsd.jpg" width="48" height="48" alt=""/><p class="sentby"><a href="http://local.nixle.com/lasd----headquarters-newsroom-shb-los-angeles-county-sheriff/">Los Angeles County Sheriff</a></p><p class="time"><span class="since">Member since:</span> 2009</p><p class="lede"><a href="http://local.nixle.com/lasd----headquarters-newsroom-shb-los-angeles-county-sheriff/">View alerts sent by this agency &raquo;</a></p></li><li><img src="http://i.nixle.com/uploads/agency_logos/sm/user750-1254632848-hawaii_pd.jpg" width="48" height="48" alt=""/><p class="sentby"><a href="http://local.nixle.com/hawaii-police-department/">Hawaii Police Department</a></p><p class="time"><span class="since">Member since:</span> 2009</p><p class="lede"><a href="http://local.nixle.com/hawaii-police-department/">View alerts sent by this agency &raquo;</a></p></li><li><img src="http://i.nixle.com/uploads/agency_logos/sm/user1732-1244812315-star.jpg" width="48" height="48" alt=""/><p class="sentby"><a href="http://local.nixle.com/chicago-police-department---headquarters/">Chicago Police Department</a></p><p class="time"><span class="since">Member since:</span> 2009</p><p class="lede"><a href="http://local.nixle.com/chicago-police-department---headquarters/">View alerts sent by this agency &raquo;</a></p></li>';
    $$.html(noscr);
    $('#tickerheader').html('Featured agencies');
}

function _generate_list_item(o){
    o.time = o.time.replace(/^0/,'');
    var $li = $('<li/>'),
        content = '<img src="'+o.logo+'" width="48" height="48" alt=""/><p class="time"><span class="level '+o.level.toLowerCase()+'">'+o.level+'</span> '+o.time+'</p><p class="sentby"><span>Sent by:</span> <a href="'+o.agency_link+'">'+o.agency+'</a></p><p class="lede">'+o.headline+(o.headline.length==32?'...':'')+' <a href="'+o.link+'">More &raquo;</a></p><div class="fade"></div>';
    $li.html(content);
    return $li;
};

function _insert_list_item(){
    $$.prepend('<li style="margin:0;padding:0;height:0;min-height:0;background-color:transparent;" id="dummy"/>');
    var $li = _generate_list_item($$.data('alerts')[$$.data('placeinline')]);
    var h = $li.prependTo($$).outerHeight(true);
    $li.hide();
    $('#dummy').animate({'height':h},function(){$(this).remove();$li.fadeIn();});
    $$.data('placeinline',($$.data('placeinline')+1));
    if($$.data('placeinline')===$$.data('alerts').length){ $$.data('placeinline',0); }
    $$.find('li:gt(5)').remove();
};

$$.before('<p id="tickerheader" class="hdr">Loading...</p>');
_fix_alertbox_height();
_fetch_alerts(_initial_populate);
fetchtimer = setInterval(_fetch_initial_alerts,4000);

return this;
};

})(jQuery);
