var WWClock = function () {  this.initialize.apply(this, arguments);   }
WWClock.prototype = {
	initialize: function (op) {
		this.op = { workStart: {day:0,hour:8,minute:0}, workEnd: {day:4,hour:18,minute:0}, clEl: 'work_week_countdown_clock', clSEl: 'work_week_countdown_clock_sub', wt:'weekend left', bt: 'until the weekend' };
		for (key in op) this.op[key] = op[key];

		this.clEl = this.op.clEl;
		if (typeof(this.op.clEl)=='string') this.clEl = document.getElementById(this.op.clEl);
		this.clSEl = this.op.clSEl;
		if (typeof(this.op.clSEl)=='string') this.clSEl = document.getElementById(this.op.clSEl);

		var now = new Date();
		var d = now.getDay() - 1; if (d < 0) d += 7;

		var start = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (this.op.workStart.day - d), this.op.workStart.hour, this.op.workStart.minute, 0);
		var end = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (this.op.workEnd.day - d), this.op.workEnd.hour, this.op.workEnd.minute, 0);

		var endTime = end.getTime();
		var startTime = start.getTime();
		var nowTime = now.getTime();

		var iswt = false; // is work time
		if (startTime < endTime)
			iswt = (nowTime >=startTime && nowTime <= endTime)
		else
			iswt = (nowTime < startTime || nowTime > endTime)

		if ( iswt ) {
			this.countUntilEnd = true;
			this.countoMSecs = endTime;
			this.clSEl.innerHTML = this.op.bt;
		} else {
			this.countUntilEnd = false;
			this.clSEl.innerHTML = this.op.wt;
			if (nowTime > startTime)
				startTime += 7 * 24 * 60 * 60 * 1000;
			this.countoMSecs = startTime;
		}

		this.updateClock();
		var f =  function (context) { return function () { context.updateClock(); } }(this);
		interval = setInterval (f, 1000);
	},
	toTwoDigits: function (n) {
		return (n < 10 ? '0' + n : n);
	},
	updateClock: function () {
		var now = new Date();
		var sl = parseInt((this.countoMSecs - now.getTime()) / 1000);
		var d = Math.floor(sl / 86400);
		var rest = sl - d * 86400; // 60 * 60 * 24
		var h = Math.floor(rest / 3600);
		rest = rest - h * 3600;  // 60 * 60
		var m = Math.floor(rest / 60);
		var s = Math.floor(rest % 60);
		var t = '';
		t += d + ' day' + (d != 1?'s':'') + ' ';
		if (this.op.format == 'short') {
			t += this.toTwoDigits(h) + ' : ' + this.toTwoDigits(m) + ' : ' + this.toTwoDigits(s);
		} else {
			t += this.toTwoDigits(h) + ' hour' + (h != 1?'s':'') + ' ';
			t += this.toTwoDigits(m) + ' minute' + (m != 1?'s':'') + ' ';
			t += this.toTwoDigits(s) + ' second' + (s != 1?'s':'');
		}
		//t = d + " days " + this.toTwoDigits(h) + ":" + this.toTwoDigits (m) + ":" + this.toTwoDigits(s);
		this.clEl.innerHTML =  t;
	}
}