// JavaScript Document

function BOQCountDown (container, opt) {
	
	this.container = $(container);
	this.untilAsString = '';
	this.dateAsString = '';
	this.opts = {
		dateURL:'cashdraw_date.htm',
		untilURL:'until.htm'
	}
	$.extend(this.opts, opt || {});
	
	this.init = function() {
		
		$.ajax( {
			url:this.opts.dateURL,
			type:'GET',
			data:'ts='+new Date().getTime(),
			dataType:'text',
			callingObject:this,
			success:function(data, textStatus) {
					this.callingObject.processDate(data);
				},
			error:function (XMLHttpRequest, textStatus, errorThrown) { /* Fail silently */ }
		});
		
		$.ajax( {
			url:this.opts.untilURL,
			type:'GET',
			data:'ts='+new Date().getTime(),
			dataType:'text',
			callingObject:this,
			success:function(data, textStatus) {
					this.callingObject.processUntil(data);
				},
			error:function (XMLHttpRequest, textStatus, errorThrown) { /* Fail silently */ }
		});
	};
	
	this.processDate = function(dateStr){
		var dowAry = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
		var mthAry = ['January','February','March','April','May','June','July','August','September','October','November','December'];
		var extAry = ['th','st','nd','rd','th','th','th','th','th','th'];
		var dateBits = dateStr.split('/');
		
		if (dateBits.length < 3) { return false; }
		this.date = new Date(dateBits[2],dateBits[1]-1,dateBits[0],10,0,0,0);
		var useExt = extAry[this.date.getDate()%10];
		if (this.date.getDate() == 11 || this.date.getDate() == 12 || this.date.getDate() == 13) { useExt = 'th' }
		this.dateAsString = dowAry[this.date.getDay()] + ' ' + this.date.getDate() + useExt + ' ' + mthAry[this.date.getMonth()];
		this.renderCheck();
	};
	
	this.processUntil = function(untilStr){
		if (untilStr.match(/\+\d*d\s\+\d*h\s\+\d*m/gi)) { 
			this.untilAsString = untilStr;
			this.renderCheck();
		} else {
			this.renderToday(untilStr);
		}
	};
	
	this.renderCheck = function() {
		if ( this.dateAsString !== '' && this.untilAsString !== '') {
			this.renderCountDown();
		}
	};
	
	this.renderCountDown = function() {
		this.container
			.html(
				'<div class="todate">' + this.dateAsString + '</div>' +
				'<div class="counter"></div>' +
				'<div class="clear"></div>' +
				'<div class="sweep"><div></div></div>'
			);
		$('div.counter', this.container).countdown({ 
			until: this.untilAsString, 
			format: 'dHMS',
			layout: '<div>{dnn}<div>Days</div></div><div>{hnn}<div>Hours</div></div><div>{mnn}<div>Mins</div></div>',
			onTick: function(periods){ $('div.sweep div', this.container).css('width', Math.round(periods[6]/60 * 100)+'%'); } 
		});
	};
	
	this.renderToday = function(str) {
		this.container
			.html(
				'<div class="todate">' + this.dateAsString + '</div>' +
				'<div class="counter">'+str+'</div>' +
				'<div class="clear"></div>'
			);
	};
	
	this.init();
	
}
