
(function($){

    // Debug Helper
    var debug = function(){
        firebug = window.console || false
        if(firebug) firebug.log(arguments)
    }

    /* Constructor */
    var Live_Quotes = function($wrapper, settings){
		this.settings = jQuery.extend({
            prune_quotes      : 3,
            scroll_rate       : 5000,
            ajax_update_rate  : 180000,
            json_endpoint     : '/tools/fetch_live_quotes.php',
            template          : function(){ with(this){ return "<div><strong>"+make +' '+model +"</strong><em>&pound;"+best_price+"</em><span>"+age+' yo, '+marital_status+' '+gender +' from '+address+"</span></div>" }}
		}, settings);


        this.$wrapper    = $wrapper;
        this.latest_quote_id = 0;
        this.cache       = {};

        this.init()
    }

    /* Init */
    Live_Quotes.prototype.init = function(){
        var self = this
        this.$wrapper
            .ajaxStart( function(){
                //$("<i>Loading, Please Wait...</i>")
                //.prependTo(this)
                //.ajaxStop(function(){ $(this).hide() })
            })
            .ajaxError( function(){
                debug("Oops, the AJAX made a PooPoo", arguments )
                // if we already are showing some results then die silently without panicking the user
                if( self.latest_quote_id > 0 && self.cache.quotes[0].quote_id != self.latest_quote_id ){
                    return false;
                }else{
                    $("<em>Sorry, Live Quotes are currently unavailable.</em>")
                    .addClass('error')
                    .prependTo( $(this).empty() )
                }
            })
            .ajaxSuccess( function(){
                $('em.error', this).remove()
            })

        this.ajax_update(function(){
            self.scroll()
        });
    }

    /* Ajax Update */
    Live_Quotes.prototype.ajax_update = function(callback){
        var self=this
        // fetch the live data now
        $.getJSON(this.settings.json_endpoint, function(data, status){
            debug('Fetching JSON:'+status, data)
            self.cache.quotes = data.quotes;
            if( $.isFunction(callback) )
                callback.apply(self)
                
            setTimeout( function(){ self.ajax_update(); }, self.settings.ajax_update_rate);
        })
    }


    /* Update */
    Live_Quotes.prototype.scroll = function(){
        var self   = this
        var quotes = this.cache.quotes

        //if the latest quote in the cache is bigger that the shown quote
        if( quotes && quotes[0].quote_id > this.latest_quote_id){
            // loop quotes in reverse order
            for(var i=quotes.length-1; i>-1; i--){
                var quote = quotes[i]
                if( quote.quote_id > this.latest_quote_id ){
                    this.add(quote);
                    // we have to one only 1 quote per run unless we are in the begining
                    //  and have to fill the placeholder initialy
                    if( $('>div',this.$wrapper).length >= this.settings.prune_quotes )
                        break;
                }
            }
        }
        setTimeout( function(){ self.scroll(); }, self.settings.scroll_rate);
    }

    /* Add Quote */
    Live_Quotes.prototype.add = function(quote){
        this.latest_quote_id = quote.quote_id
        var self=this
        var fx_speed = 'normal' // on initial page load it will show fast

        if( $('>div',this.$wrapper).length >= this.settings.prune_quotes ){
            fx_speed = 'slow'
            $('>div',this.$wrapper).slice(this.settings.prune_quotes-1, 999).slideUp(fx_speed).queue( function(){ $(this).remove() } )
        }

        //append and animate the template
        $( self.settings.template.apply(quote) )
         .hide()
         .prependTo(self.$wrapper)
         .slideDown(fx_speed)
    }


    /* jQuery Plugin Register */
    $.fn.live_quotes = function(settings){
        return new Live_Quotes($(this), settings)
    }
    
})(jQuery)

