/**
 * DYF Clock for dyf-clock.php
 *
 * Copyright 2009 DYF IT-Division All right reserved.
 * http://it-division.jpn.org/
 *
 */

function DyfClock(options) {

	this._id = options["id"];
	this.container = document.getElementById(options["id"]);

	var saved_dt = this.getCookie(this.COOKIE_DATE_KEY);
	var saved_scale = this.getCookie(this.COOKIE_SCALE_KEY);

	if (saved_dt && saved_scale) {
		var ymd = String(saved_dt).split("_");
		var dt = new Date(ymd[0], ymd[1] - 1, ymd[2]);
		var title = this.getCookie(this.COOKIE_TITLE_KEY);
		var comment = this.getCookie(this.COOKIE_COMMENT_KEY);
		this.showClock(dt, saved_scale, title, comment);
	} else {
		this.showForm();
	}
}

DyfClock.prototype.COOKIE_LIFETIME = 3650;
DyfClock.prototype.COOKIE_DATE_KEY = 'dyf_clock_date';
DyfClock.prototype.COOKIE_SCALE_KEY = 'dyf_clock_scale';
DyfClock.prototype.COOKIE_TITLE_KEY = 'dyf_clock_title';
DyfClock.prototype.COOKIE_COMMENT_KEY = 'dyf_clock_comment';

DyfClock.prototype.showClock = function (dt, scale, title, comment) {
	title = title || "目標";
	var now = new Date();
	var scale_postfix = (scale == "day" ? " 日" : " 時間");
	var remain;
	if (scale == "day") {
		remain = Math.ceil((dt.getTime() - now.getTime()) / 1000 / 60 / 60 / 24);
	} else {
		remain = Math.ceil((dt.getTime() - now.getTime()) / 1000 / 60 / 60);
	}
	
	this._interval_id = null;
	this.digits = [];
	this.items = [];
	this.container.innerHTML = "";

	var p = document.createElement('P');
	p.className = "title";
	p.innerHTML = title + "の日まで：";
	this.container.appendChild(p);

	var clock = document.createElement('DIV');
	clock.className = "body";
	this._buildClock(clock, remain, "あと ", scale_postfix);
	this.container.appendChild(clock);

	if (comment) {
		var com = document.createElement('DIV');
		com.className = "dyf-comment";
		com.innerHTML = comment;
		this.container.appendChild(com);
	}

	this._startClock();
};

DyfClock.prototype._addResetBtn = function () {
	var owner = this;
	var div = document.createElement("DIV");
	div.className = "reset";
	var btn = document.createElement("A");
	btn.href = "#dummy";
	btn.innerHTML = "再設定";
	this.addEvent(btn, "click", function (ev) {
		if (owner._interval_id) {
			clearInterval(owner._interval_id);
		}
		owner.expireCookie(owner.COOKIE_KEY);
		owner.showForm();
	});
	div.appendChild(btn);
	this.container.appendChild(div);
};

DyfClock.prototype._startClock = function () {
	if (this._interval_id) {
		clearInterval(this._interval_id);
	}
	var owner = this;
	var list = this.items;
	var index = list.length - 1;
	list[index].className = "digit-active";
	this._interval_id = setInterval(function () {
		var d = Number(list[index].innerHTML);
		if (d > owner.digits[index]) { 
			list[index].innerHTML = --d;
		}
		if (d == owner.digits[index]) {
			list[index].className = "digit-active";
			index--;
		}
		if (index < 0) {
			clearInterval(owner._interval_id);
			owner._interval_id = null;
		}
	}, 100);
	this._addResetBtn();
};

DyfClock.prototype._buildClock = function (parent, remain, prefix, postfix) {
	if (remain < 0) remain = 0;
	this.digits = remain.toString().split("");
	parent.appendChild(document.createTextNode(prefix));
	for (var i = 0; i < this.digits.length; i++) {
		var span = document.createElement("SPAN");
		span.innerHTML = "9";
		span.className = "digit";
		parent.appendChild(span);
		this.items.push(span);
	}
	parent.appendChild(document.createTextNode(postfix));
};

DyfClock.prototype.showForm = function () {
	var prefix = this._id;

	this.container.innerHTML = "";

	var div = document.createElement("DIV");
	div.className = "form";

	var html = "<p class='title'>あなたの目標を入力してください！</p><p>" +
	"日付： <input type='text' size='4' maxlength='4' id='" + prefix + "-year'/>年 " +
	"<input type='text' size='2' maxlength='2' id='" + prefix + "-month'/>月 " +
	"<input type='text' size='2' maxlength='2' id='" + prefix + "-day'/>日 " +
	"</p>" +
	"<p>目標： " +
	"<input type='text' size='20' id='" + prefix + "-title'/></p>" +
	"<p>一言： " +
	"<input type='text' size='20' id='" + prefix + "-comment'/></p>" +
	"単位： <select id='" + prefix + "-scale'/>" +
	"<option selected='selected' value='day'>日数</option>" +
	"<option value='hour'>時間数</option>" +
	"</select>&nbsp;&nbsp;&nbsp;";
	div.innerHTML = html;

	var owner = this;
	var div_btn = document.createElement("DIV");
	div_btn.className = "btn";
	var btn = document.createElement("INPUT");
	btn.type = "button";
	btn.value = "設定";
	this.addEvent(btn, "click", function (ev) {
		var y = document.getElementById(prefix + "-year").value;
		var m = document.getElementById(prefix + "-month").value;
		var d = document.getElementById(prefix + "-day").value;
		var title = document.getElementById(prefix + "-title").value;
		var comment = document.getElementById(prefix + "-comment").value;
		var scale_sel = document.getElementById(prefix + "-scale");
		var scale = scale_sel.options[scale_sel.selectedIndex].value;
		var dt = new Date(y, m - 1, d);
		if (dt && dt.getTime() > 0 && (new Date()).getTime() < dt.getTime()) {
			owner.setCookie(owner.COOKIE_DATE_KEY, y + "_" + m + "_" + d, owner.COOKIE_LIFETIME);
			owner.setCookie(owner.COOKIE_SCALE_KEY, scale, owner.COOKIE_LIFETIME);
			if (title) {
				title = title.replace(/[<>#&"']/g, "");
				owner.setCookie(owner.COOKIE_TITLE_KEY, title, owner.COOKIE_LIFETIME);
			}
			if (comment) {
				comment = comment.replace(/[<>#&"']/g, "");
				owner.setCookie(owner.COOKIE_COMMENT_KEY, comment, owner.COOKIE_LIFETIME);
			}
			owner.showClock(dt, scale, title, comment);
		} else {
			alert("日付の指定が不正です。");
		}
	});
	div_btn.appendChild(btn);
	this.container.appendChild(div);
	this.container.appendChild(div_btn);
};

DyfClock.prototype.getCookie = function (name) {
	var regex = new RegExp("; " + name + "=(.*?);");
	var match = ("; " + document.cookie + ";").match(regex);
	return match ? decodeURIComponent(match[1]) : false;
};

DyfClock.prototype.setCookie = function (name, value, expire_day, domain, path, is_secure) {
	var str = name + "=" + encodeURIComponent(value);
	if (expire_day) {
		var ex = new Date();
		ex.setTime(ex.getTime() + (expire_day * 86400000));
		str += '; expires=' + ex.toUTCString();
	}
	if (domain) str += '; domain=' + domain;
	if (path) str += '; path=' + path;
	if (is_secure) str += '; secure';
	document.cookie = str;
};

DyfClock.prototype.expireCookie = function(name) {
	var ex = new Date();
	ex.setFullYear(1997);
	document.cookie = name + '= ;expires=' + ex.toUTCString();
};

DyfClock.prototype.addEvent = function (obj, evName, func, useCap) {
    if (obj.addEventListener){
        useCap = useCap || false;
        obj.addEventListener(evName, func, useCap);
    } else if (obj.attachEvent){
        obj.attachEvent("on"+evName, func);
    }
};

DyfClock.prototype.removeEvent = function (obj, evName, func, useCap) {
    if (obj.removeEventListener){
        useCap = useCap || false;
        obj.removeEventListener(evName, func, useCap);
    } else if (obj.detachEvent){
        obj.detachEvent("on"+evName, func);
    }
};

/* Invoke by dyf-clock.php
DyfClock.prototype.addEvent(window, "load", function () {
	var dc = new DyfClock({
		id : 'dyf-clock'
	});
});
*/

