// tdslive.js
// IMPORTANT NOTE: Needs maxItemsToShow and tdsLivedataURL to be preset
// JJ :: 25/4/2010, 18/5/2010 increased timeout

var t = 0;
var interval = 15000;
var _tids = [];
var pending = 0;

function smoothAdd(id, text) {
	var maxItems = maxItemsToShow;
	var duration = 1500; // ms
	var animRatio = 5;

	var animUnit = duration / (2 + animRatio);
	var el = $('#' + id);
	var h = el.height();

	el.css({
		height:   h,
		overflow: 'hidden'
	});

	var ulPaddingTop    = parseInt(el.css('padding-top'));
	var ulPaddingBottom = parseInt(el.css('padding-bottom'));

	var numItems = $(el).children().length;

	el.prepend('<li style="list-style: none;">' + text + '</li>');

	var first = $('li:first', el);
	var last  = $('li:last',  el);
	var foh = first.outerHeight();
	var heightDiff = numItems >= maxItems ? foh - last.outerHeight() : foh;
	var oldMarginTop = first.css('margin-top');

	first.css({
		width: 900, // JJ :: 18/11/2010 :: Solves border overwrite in new Xmas wide layout design
		marginTop: 0 - foh,
		position:  'relative',
		top:       0 - ulPaddingTop
	});

	if (numItems >= maxItems) {
		last.css('position', 'relative');
	}

	// Number of animations to complete before a cleanup should occur
	pending = numItems >= maxItems ? 2 : 1;

	el.animate({ height: h + heightDiff }, duration, function() { cleanUp(el); });

	first.animate({ top: 0 }, numItems >= maxItems ? animUnit : 2 * animUnit, function() {
		first.animate({ marginTop: oldMarginTop }, animUnit * animRatio, numItems >= maxItems ? function() {
			last.animate({ top: ulPaddingBottom }, animUnit, function() {
				last.remove();
				cleanUp(el);
			});
		} : '');
	});
}

function preloads(id) {
	var el = $('#' + id);
	$.ajax({
		dataType: "html",
		type: "GET",
		url: tdsLivedataURL,
		cache: false,

		success: function(data) {
			_exclusions = data.split(",");
			for (i=0; i < _exclusions.length; i++) {
				_tids.push(_exclusions[i]);
			}
			t = setTimeout(loadBm, interval);
		}
	});
}

function cleanUp(el) {
	if (!--pending)	{
		el.css({
			height:   'auto',
			overflow: 'visible'
		});
	}
}

function newView(tid) {
	for (i=0; i < _tids.length; i++) {
 	       	if (_tids[i] == tid) {
         		return(false);
		}
   	}
	return(true);
}

function init()	{
	preloads('lastviewed');
}
 
function loadBm() {
	$.ajax({
		dataType: "html",
		type: "GET",
		url: 'http://www.thediamondstore.co.uk/getLastOrders.cfm',
		cache: false,

		success: function(data) {
			if (newView(data.split("^")[0])) {
				smoothAdd('lastviewed', data.split("^")[1] );
				_tids.push(data.split("^")[0]);
			}
			t = setTimeout(loadBm, interval);
		}
	});
}

$(document).ready(function() {
   init();
});

