/**
 * Pre-load images etc. on page load 
 */

var viraladnetwork = viraladnetwork || {};

jQuery(function () {
    var files = ["/++resource++images/nav/over_advertisers.png",
                "/++resource++images/nav/over_publishers.png",
                "/++resource++images/nav/over_about.png",
                "/++resource++images/nav/over_blog.png",
                "/++resource++images/nav/over_login.png",
                "/++resource++images/nav/over_contactus.png",
                "/++resource++images/busy.gif"];

    viraladnetwork.preloaded = viraladnetwork.preloaded || {};

    for (k in files) {
        viraladnetwork.preloaded[k] = new Image(1,1);
        viraladnetwork.preloaded[k].src = files[k];
    }

    /* Now post load jQueryUI */
    jQuery.ajaxSetup({ cache: true });
    jQuery.getScript("/++resource++js/jquery-ui-1.7.2.custom.min.js");
    jQuery.ajaxSetup({ cache: false });
});


/**
 * Ticker object - TimW Oct '09
 */
function Ticker(value){
    /* value shown in page */
    this.ghostval = value;
    this.setValue(value);
    
    /* rate of increase */
    this.ghostrate = 0;
    this.setRate(0);
    
    /* timing info */
    this.lastupdate = new Date();
    this.lastrealvalue = new Date();
}

Ticker.prototype.getValue = function () {
    this.update()
    return this.ghostval;
}

Ticker.prototype.setValue = function (val) {
    this.realval = val;
    this.lastrealvalue = new Date();
}

Ticker.prototype.getRate = function () {
    this.update()
    return this.ghostrate;
}

Ticker.prototype.setRate = function (rate) {
    this.realrate = rate;
}

Ticker.prototype.update = function () {
    /**
     * Update ghosted rate.
     * we shift slightly closer to the server's rate each time.
     */
    
    this.ghostrate = 0.25 * (this.ghostrate * 3 + this.realrate);
    
    /* Update ghosed value */
    var time_now = new Date();
    var time_diff = (time_now - this.lastupdate);
    
    var pullback = 1;
    if ( this.ghostval > this.realval + ( 
         (time_now - this.lastrealvalue) * 0.001 * this.realrate )){
        /**
         * Manually slow down the rate if we've over-approximated
         */
        pullback = 0.9;
    }
    
    this.ghostval = this.ghostval + (time_diff/1000) * this.ghostrate * pullback;
    
    this.lastupdate = time_now;
}


/**
 * Dirty CommaFormatting function - copied from the messy polarbear.js
 */
function CommaFormatted(amount) {
	var delimiter = ","; // replace comma if desired
	var d = amount;
	var i = parseFloat(amount);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);

	amount = minus + n;
	return amount;
}
