﻿function TimeDevCountdown(id, eventDate, pathImages, functionUpdate)
{
	this.id = id.toString().toLowerCase();
	this.eventDate = eventDate;
	this.pathImages = pathImages;
	this.functionUpdate = functionUpdate;
	this.counterStarted = false;
	this.countdown = null;
}

TimeDevCountdown.prototype.updateCounter = function()
{
	if (!this.setCountdown()){
		this.counterStarted = false;
		return;
	}
	
	var value;
	var num;

	do { //while counter
		//Seconds
		value = this.countdown.getUTCSeconds(); 
		num = value % 10;
		this.setNumber("s1", num);
		
		if (num != 9 && this.counterStarted) {
			break;
		}

		num = Math.floor(value / 10);
		this.setNumber("s2", num);
		
		if (num != 5 && this.counterStarted) {
			break;
		}
		
		//Minutes
		value = this.countdown.getUTCMinutes();
		num = value % 10;
		this.setNumber("m1", num);
		
		if (num != 9 && this.counterStarted) {
			break;
		}

		num = Math.floor(value / 10);
		this.setNumber("m2", num);
		
		if (num != 5 && this.counterStarted) {
			break;
		}
				
		//Hours
		value = this.countdown.getUTCHours();
		this.setNumber("h1", (value % 10));
		this.setNumber("h2", Math.floor(value / 10));
		
		//Days
		value = Math.floor(this.countdown.getTime() / (24 * 3600000));
		num = value % 10;
		this.setNumber("d1", num);
		
		num = Math.floor(value / 10) % 10;
		
		if (num == 0) {
			n = 10;
		}
		
		this.setNumber("d2", num);
	} while(0); //while counter

	this.counterStarted = true;
	setTimeout(this.functionUpdate, 1001 - (new Date()).getMilliseconds());
}

TimeDevCountdown.prototype.drawNumber = function(type)
{
	for (var i = 0; i <= 9; i++){
		document.write('<img id="' + this.getImageId(type, i) + '" src="' + this.getImagePath(i) + '" style="display:' + ((i == 0) ? "block" : "none") + '" alt="" />');
	}
}

TimeDevCountdown.prototype.setNumber = function(type, num)
{
	for (var i = 0; i <= 9; i++){
		var img = document.getElementById(this.getImageId(type, i));
		
		if (!img){
			continue;
		}
		
		var imgDisplay = (i == num) ? "block" : "none";
		
		if (img.style.display != imgDisplay){
			img.style.display = imgDisplay;
		}
	}
}

TimeDevCountdown.prototype.getImageId = function(type, num)
{
	var imageId = this.id + "_" + type.toString().toLowerCase() + "_" + num.toString();
	
	return imageId;
}

TimeDevCountdown.prototype.getImagePath = function(num)
{
	var imagePath = this.pathImages + num.toString() + ".gif";
	
	return imagePath;
}

TimeDevCountdown.prototype.setCountdown = function()
{
	var now = new Date();
	
	if (this.eventDate <= now){
		this.countdown = null;
		return false;
	}else{
		this.countdown = new Date(this.eventDate - new Date());
		return true;
	}
}
