var MainWWClock = function () {   this.initialize.apply(this, arguments);   }
MainWWClock.prototype = {
	initialize: function (options) {
		this.options = { workStart: {day:0,hour:8,minute:0}, workEnd: {day:4,hour:18,minute:0}, clockElement: '', clockSubElement: '' };
		for (key in options) this.options[key] = options[key];

		this.clockElement = document.getElementById(this.options.clockElement);
		this.clockSubElement = document.getElementById(this.options.clockSubElement);

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

		// calculate work week start and ent
		start.setDate(now.getDate() + (this.options.workStart.day - d));
		start.setHours(this.options.workStart.hour);
		start.setMinutes(this.options.workStart.minute);
		start.setSeconds(0);

		end.setDate (now.getDate() + (this.options.workEnd.day - d));
		end.setHours(this.options.workEnd.hour);
		end.setMinutes(this.options.workEnd.minute);
		end.setSeconds(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.clockSubElement.innerHTML = 'Time left until the weekend';
		} else {
			this.countUntilEnd = false;
			// find the next start date
			this.clockSubElement.innerHTML = 'Time left until weekend is over';
			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.options.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.clockElement.innerHTML =  t;
	}
}