/*
	jQuery Plugin spy (leftlogic.com/info/articles/jquery_spy2)
	(c) 2006 Remy Sharp (leftlogic.com)
	$Id: spy.js,v 1.4 2006/09/30 11:05:04 remy Exp $
*/
var limit = 7;
var spyRunning = 1;

JQ.fn.spy = function(settings) {
	var spy = this;
	spy.epoch = new Date(1970, 0, 1);
	spy.last = '';
	spy.parsing = 0;
	spy.waitTimer = 0;
	spy.json = null;
	spy.first = 1;

	spy.attachHolder = function() {
		// not mad on this, but the only way to parse HTML collections
		if (o.method == 'html') JQ('body').append('<div style="display: none!important;" id="_spyTmp"></div>');
	}

	// returns true for 'no dupe', and false for 'dupe found'
	// latest = is latest ajax return value (raw)
	// last = is previous ajax return value (raw)
	// note that comparing latest and last if they're JSON objects
	// always returns false, so you need to implement it manually.
	spy.isDupe = function(latest, last) {
		if (latest.currentlive == -1) return 1;
		/*else if (latest.currentlive == -2) {
			topstory = 0;
			location.reload();
			return 1;
		}*/
	}
	
	spy.parse = function(e, r) {
		spy.parsing = 1; // flag to stop pull via ajax
		if (o.method == 'html') JQ('div#_spyTmp').html(r); // add contents to hidden div
		else if (o.method == 'json') eval('spy.json = ' + r); // convert text to json

		if ((o.method == 'json' && spy.json.constructor == Array) || o.method == 'html') {
			if (spy.parseItem(e)) {
				spy.waitTimer = window.setInterval(function() {
					if (spyRunning) {
						if (!spy.parseItem(e)) {
							spy.parsing = 0;
							clearInterval(spy.waitTimer);
						}
					}
				}, o.timeout);
			} else {
				spy.parsing = 0;
			}
		} else if (o.method == 'json') { // we just have 1*/
			eval('spy.json = ' + r)
			spy.addItem(e, spy.json);
			spy.parsing = 0;
		}
	}
	
	// returns true if there's more to parse
	spy.parseItem = function(e) {
		if (spy.json.length) {
			var i = spy.json.shift();
			spy.addItem(e, i);
		}

		return (spy.json.length != 0);
	}
	
	spy.addItem = function(e, i) {
		if (! o.isDupe.call(this, i, spy.last)) {
			spy.last = i; // note i is a pointer - so when it gets modified, so does spy.last
			JQ('#' + e.id + ' > div:gt(' + (limit - 2) + ')').remove();
			JQ('#' + e.id + ' > div:gt(' + (limit - o.fadeLast - 2) + ')').fadeEachDown();
			o.push.call(e, i);
			JQ('#' + e.id + ' > div:first').fadeIn(o.fadeInSpeed);
		}
	}
	
	spy.push = function(r) {
		JQ('#' + this.id).prepend(r.contents);
		lastTime = r.currentlive;

		if (r.type != 4) {
			var obj = document.getElementById('diggs-strong-' + r.postSeq);
			if (obj && (obj.innerHTML < r.point)) obj.innerHTML = r.point;
			if ((r.type == 0) || (r.type == 1)) {
				obj = document.getElementById('commentCount' + r.postSeq);
				if (obj) {
					var commentsCount = parseInt(obj.innerHTML);
					if (commentsCount < r.commentCount) obj.innerHTML = commentsCount + 1;
				}
			}
		}
		else {
         if (!spy.first) {
            var obj = document.getElementById('todayCount');
            if (obj) {
               var todayCount = parseInt(delComma(obj.innerHTML));
               obj.innerHTML = addComma(todayCount + 1);
            }
            obj = document.getElementById('totalCount');
            if (obj) {
               var totalCount = parseInt(delComma(obj.innerHTML));
               obj.innerHTML = addComma(totalCount + 1);
            }
         }

			if (typeof addNewpost == 'function') addNewpost(r.postSeq, r.point);
		}
	}
	
	var o = {
		limit: 7,
		fadeLast: 1,
		ajax: settings.ajax,
		timeout: 3000,
		method: 'json',
		push: spy.push,
		fadeInSpeed: 'slow',		// 1400 = crawl
		isDupe: spy.isDupe
	};

	spy.attachHolder();

	return this.each(function() {
		var e = this;
		var lr = ''; // last ajax return
		spy.ajaxTimer = window.setInterval(function() {
			if (spyRunning && (!spy.parsing)) {
                spy.parsing = 1;
                JQ.ajax({
                    type: "GET",
                    url: o.ajax,
                    data: "timestamp=" + lastTime,
                    timeout: 2000,
                    error: function() {
                        spy.parsing = 0;
                    },
                    success: function(r) {
                        spy.parse(e, r);
                        if (spy.first) spy.first = 0;
                    }
                });
			}	
		}, o.timeout);
	});
};

JQ.fn.appearEachDown = function() {
    var s = this.size();
    return this.each(function(i) {
        var e = this.style;
        if (window.ActiveXObject) e.filter = "alpha(opacity=100)";
        e.opacity = 1;
    });
};

JQ.fn.fadeEachDown = function() {
	var s = this.size();
	return this.each(function(i) {
		var o = 1 - (s == 1 ? 0.5 : 0.85/s*(i+1));
		var e = this.style;
		if (window.ActiveXObject) e.filter = "alpha(opacity=" + o*100 + ")";
		e.opacity = o;
	});
};

function pauseSpy() {
	spyRunning = 0;
	return false;
}

function playSpy() {
	spyRunning = 1;
	return false;
}

function addComma(val) {
   var str = new Array();
   val = String(val);
   for (i = 1; i <= val.length; i ++) {
      if (i % 3) str[val.length - i] = val.charAt(val.length - i);
      else str[val.length - i] = ',' + val.charAt(val.length - i);
   }
   return str.join('').replace(/^,/, '');
}

function delComma (val) {
   var retValue = "";
   for (i = 0; i < val.length; i ++) {
      if (val.charAt(val.length - i - 1) != ",") retValue = val.charAt(val.length - i - 1) + retValue;
   }
   return retValue;
}


