if( !YAHOO.me2 ) {
	YAHOO.namespace("me2");
}

if( !me2 ) {
	var me2 = YAHOO.me2;
}

//
// dependency: yahoo yui library, ./php/me2.auth.login.php
//

me2.auth = {
	busy: false,

	id: "",

	pw: "",

	// ajax handler
	handleSuccess: function(o) {
		me2.auth.busy = false;

		if( o.responseText.match("me2.auth") ) {
			eval(o.responseText);
		}
		else {
			alert(o.responseText);
		}
	},

	handleFailure: function(o) {
		me2.auth.busy = false;

		me2.auth.logout();
	},

	// login
	login: function(id, pw) {
		if( me2.auth.busy ) {
			return;
		}

		if( !id || !pw ) {
			alert("아이디와 패스워드로 빈 문자열을 받지 않습니다.");
			return;
		}

		var url = "./php/me2.auth.login.php";
		var dat = "callback=me2.auth.handleLogin&id=" + id + "&pw=" + pw;
		YAHOO.util.Connect.asyncRequest("POST", url, me2.auth.callback, dat);

		me2.auth.id = id;
		me2.auth.pw = pw;
		me2.auth.busy = true;
	},

	handleLogin: function(json) {
		me2.auth.onLogin(json);
	},

	onLogin: function(json) {
	},

	// logout
	logout: function() {
		me2.auth.id = "";
		me2.auth.pw = "";

		me2.auth.onLogout();
	},

	onLogout: function() {
	}
};

me2.auth.callback = {
	success: me2.auth.handleSuccess,
	failure: me2.auth.handleFailure,
	scope: me2.auth
};

//
// dependency: yahoo yui library, ./php/me2.post.write.php
//

me2.post = {
	busy: false,

	// ajax handler
	handleSuccess: function(o) {
		me2.post.busy = false;

		if( o.responseText.match("me2.post") ) {
			eval(o.responseText);
		}
		else {
			alert(o.responseText);
		}
	},

	handleFailure: function(o) {
		me2.post.busy = false;
	},

	// read post
	read: function(permalink) {
		var id = me2.permalink.to_id(permalink);
		var date = me2.permalink.to_date(permalink);

		var from = date;
		var to = parseInt(date.substr(17, 2), 10) + 1;
		to = (to >= 10) ? to : "0" + to;
		to = date.substr(0, 17) + to;

		var url = "http://me2day.net/api/get_posts/" + id + ".json?callback=me2.post.handleRead" +
				  "&me2_application_key=7308b5ebd98dd87888dc7e6c0f0daa4d" +
				  "&from=" + from + 
				  "&to=" + to;

		var js = new JSONscriptRequest(url);
		js.buildScriptTag();
		js.addScriptTag();
	},

	handleRead: function(json) {
		me2.post.onRead(json);
	},

	onRead: function(json) {
		//alert(json[0].body);
	},

	// write post
	write: function(post_body, post_tags) {
		if( me2.post.busy ) {
			return;
		}

		if( !me2.auth.id || !me2.auth.pw ) {
			alert("미투데이 아이디와 유저키로 로그인을 해주세요.");
			return;
		}

		var url = "./php/me2.post.write.php";
		var dat = "callback=me2.post.handleWrite&id=" + me2.auth.id + "&pw=" + me2.auth.pw + "&post_body=" + URL.encode(post_body) + "&post_tags=" + URL.encode(post_tags);
		YAHOO.util.Connect.asyncRequest("POST", url, me2.post.callback, dat);

		me2.post.busy = true;
	},

	handleWrite: function(json) {
		me2.post.onWrite(json);
	},

	onWrite: function(json) {
	}
};

me2.post.callback = {
	success: me2.post.handleSuccess,
	failure: me2.post.handleFailure,
	scope: me2.post
};

//
// dependency: yahoo yui library, ./php/me2.comment.write.php
//

me2.comment = {
	busy: false,

	// ajax handler
	handleSuccess: function(o) {
		me2.comment.busy = false;

		if( o.responseText.match("me2.comment") ) {
			eval(o.responseText);
		}
		else {
			alert(o.responseText);
		}
	},

	handleFailure: function(o) {
		me2.comment.busy = false;
	},

	// read post
	read: function(permalink) {
		var url = "http://me2day.net/api/get_comments.json?callback=me2.comment.handleRead" + 
				  "&me2_application_key=7308b5ebd98dd87888dc7e6c0f0daa4d" +
				  "&post_id=" + escape(permalink);

		var js = new JSONscriptRequest(url);
		js.buildScriptTag();
		js.addScriptTag();
	},

	handleRead: function(json) {
		me2.comment.onRead(json);
	},

	onRead: function(json) {
		alert(json.comments.length);
	},

	// write post
	write: function(permalink, comment) {
		if( me2.comment.busy ) {
			return;
		}

		if( !me2.auth.id || !me2.auth.pw ) {
			alert("미투데이 아이디와 유저키로 로그인을 해주세요.");
			return;
		}

		var url = "./php/me2.comment.write.php";
		var dat = "callback=me2.comment.handleWrite&id=" + me2.auth.id + "&pw=" + me2.auth.pw + "&permalink=" + URL.encode(permalink) + "&comment=" + URL.encode(comment);
		YAHOO.util.Connect.asyncRequest("POST", url, me2.comment.callback, dat);
		
		me2.comment.busy = true;
	},

	handleWrite: function(json) {
		me2.comment.onWrite(json);
	},

	onWrite: function(json) {
	}
};

me2.comment.callback = {
	success: me2.comment.handleSuccess,
	failure: me2.comment.handleFailure,
	scope: me2.comment
};

//
// dependency: yahoo yui library
//

me2.person = {
	read: function(id) {
		var url = "http://me2day.net/api/get_person/" + id + ".json?callback=me2.person.handleRead&akey=a19db36f6c4a219d21355b58ce7c9a7b";
		var js = new JSONscriptRequest(url);
		js.buildScriptTag();
		js.addScriptTag();
	},

	handleRead: function(json) {
		me2.person.onRead(json);
	},

	onRead: function(json) {
	}
};

me2.friends = {
	read: function(id) {
		var url = "http://me2day.net/api/get_friends/" + id + ".json?callback=me2.friends.handleRead&akey=a19db36f6c4a219d21355b58ce7c9a7b";
		var js = new JSONscriptRequest(url);
		js.buildScriptTag();
		js.addScriptTag();
	},

	handleRead: function(json) {
		me2.friends.onRead(json);
	},

	onRead: function(json) {
	}
};

me2.latests = {
	read: function(id) {
		var url = "http://me2day.net/api/get_latests/" + id + ".json?callback=me2.latests.handleRead&akey=a19db36f6c4a219d21355b58ce7c9a7b";
		var js = new JSONscriptRequest(url);
		js.buildScriptTag();
		js.addScriptTag();
	},

	handleRead: function(json) {
		me2.latests.onRead(json);
	},

	onRead: function(json) {
	}
};

//
// dependency: -
//

me2.permalink = {
	to_id: function(permalink) {
		if( !permalink.match("http://me2day.net/") ) {
			return null;
		}

		permalink = permalink.substr(18);
		var pos = permalink.indexOf("/");
		permalink = permalink.substr(0, pos);
		return permalink;
	},

	to_date: function(permalink) {
		if( !permalink.match("http://me2day.net/") ) {
			return null;
		}

		permalink = permalink.substr(permalink.length - 19);
		var date = permalink.substr(0, 10).replace(/\//g, "-");
		var time = permalink.substr(11);
		var h = parseInt(time.substr(0, 2), 10);

		if( h >= 9 ) {
			h = h - 9;
			var pub_date = date + " " + ((h > 9) ? h : "0" + h) + time.substr(2);
		}
		else {
			h = 24 + h - 9;
			date = me2.date.getOffsetDate(date, -1);
			var pub_date = date + " " + ((h > 9) ? h : "0" + h) + time.substr(2);
		}

		return pub_date;
	}
};

//
// dependency: -
//

me2.date = {
	day: 24 * 60 * 60 * 1000,

	_isValid: function(date) {
		return (date.length == 8 || date.length == 10) ? true : false;
	},

	_getYear: function(date) {
		if( !me2.date._isValid(date) ) {
			return 0;
		}

		var y = parseInt(date.substr(0, 4), 10);
		return (y >= 2000) ? y : null;
	},

	_getMonth: function(date) {
		if( !me2.date._isValid(date) ) {
			return null;
		}

		var m = parseInt((date.length == 8) ? date.substr(4, 2) : date.substr(5, 2), 10);
		return (m >= 1 && m <= 12) ? m : null;
	},

	_getDate: function(date) {
		if( !me2.date._isValid(date) ) {
			return null;
		}

		var d = parseInt((date.length == 8) ? date.substr(6, 2) : date.substr(8, 2), 10);
		return (d >= 1 && d <= 31) ? d : null;
	},

	ymd_to_string: function(y, m, d) {
		return y + "-" +  ((m > 9) ? m : "0" + m) + "-" + ((d > 9) ? d : "0" + d);
	},

	getOffsetDate: function(date, offset) {
		// offset =  0 --> today
		// offset = -1 --> yesterday
		// offset =  1 --> tomorrow
		var y = me2.date._getYear(date);
		var m = me2.date._getMonth(date);
		var d = me2.date._getDate(date);
		
		if( offset ) {
			var another_day = new Date(y, m - 1, d + offset);
			y = another_day.getFullYear();
			m = another_day.getMonth() + 1;
			d = another_day.getDate();
		}

		return me2.date.ymd_to_string(y, m, d);
	}
};

//
// dependency: -
//

URL = {
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

    _utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		
		return utftext;
	},

	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		
		return string;
	}
};

InputForm = {
	wnd: null,

	create: function() {
		if( InputForm.wnd ) {
			return;
		}

		var html = "<span class='me2login_fnt' style='width: 115px; color: #000000;'>me2DAY ID</span><input id='me2color_id' class='textbox' type='text' />"
				 + "<div class='me2login_sep'></div>"
				 + "<div style='float: right; width: 4px; height: 5px; overflow: hidden;'></div>"
				 + "<div class='btn_medium' style='float: right;' onclick='InputForm.onESC()'>Cancel</div><div class='btn_medium' style='float: right;' onclick='InputForm.onEnter()'>OK</div>";
		InputForm.wnd = new WINDOW('InputForm');
		InputForm.wnd.color = "#cccccc";
		InputForm.wnd.title_color = "#333333";
		InputForm.wnd.create(-1000, 0, 310, 59, 'CLOSE');
		InputForm.wnd.enableDragdrop();
		InputForm.wnd.setTitle("ME2DAY ID");
		InputForm.wnd.center();
		InputForm.wnd.addHTML(html);

		YAHOO.util.Dom.setStyle(InputForm.wnd.get_id(), "padding", "5px");
		YAHOO.util.Dom.setStyle(InputForm.wnd.container, "zIndex", "999");
		InputForm.wnd.onClose = InputForm.hide;
		InputForm.hide();

		YAHOO.util.Event.addListener("me2color_id", "keydown", InputForm.handleKey);
	},

	handleKey: function(e) {
		if( e.keyCode != 13 && e.keyCode != 27 ) {
			return;
		}

		switch( e.keyCode ) {
		case 13: // Enter
			InputForm.onEnter();
			break;
		case 27: // ESC
			InputForm.onESC();
			break;
		}
	},

	onEnter: function() {
		var id = YAHOO.util.Dom.get('me2color_id').value;

		if( !id ) {
			alert("Input your ID");
			return;
		}

		SEA.onSave = function(json) {
			alert("컬러세팅을 저장했습니다.");
			InputForm.hide();
			SETTING.hide();
		}
		SEA.saveColor(id);
	},

	onESC: function() {
		InputForm.hide();
	},

	show: function() {
		InputForm.create();
		DPModal.show(0.3);
		InputForm.wnd.center();
		InputForm.wnd.show();
		YAHOO.util.Dom.get('me2color_id').focus();
	},

	hide: function() {
		InputForm.create();
		DPModal.hide();
		InputForm.clear();
		InputForm.wnd.hide();
	},

	clear: function() {
		YAHOO.util.Dom.get('me2color_id').value = "";
	}
};

LoginForm = {
	wnd: null,

	create: function() {
		if( LoginForm.wnd ) {
			return;
		}

		var html = "<span class='me2login_fnt' style='width: 115px; color: #000000;'>me2DAY ID</span><input id='me2login_id' class='textbox' type='text' />"
				 + "<div class='me2login_sep'></div>"
				 + "<span class='me2login_fnt' style='width: 115px; color: #000000;'>me2DAY User-key</span><input id='me2login_pw' class='textbox' type='password' />"
				 + "<div class='me2login_sep'></div>"
				 + "<div style='float: right; width: 4px; height: 5px; overflow: hidden;'></div>"
				 + "<div class='btn_medium' style='float: right;' onclick='LoginForm.onESC()'>Cancel</div><div class='btn_medium' style='float: right;' onclick='LoginForm.onEnter()'>OK</div>";
		LoginForm.wnd = new WINDOW('LOGIN');
		LoginForm.wnd.color = "#cccccc";
		LoginForm.wnd.title_color = "#333333";
		LoginForm.wnd.create(-1000, 0, 310, 86, 'CLOSE');
		LoginForm.wnd.enableDragdrop();
		LoginForm.wnd.setTitle("LOGIN");
		LoginForm.wnd.center();
		LoginForm.wnd.addHTML(html);

		YAHOO.util.Dom.setStyle(LoginForm.wnd.get_id(), 'padding', '5px');
		YAHOO.util.Dom.setStyle(LoginForm.wnd.container, "zIndex", "999");
		LoginForm.wnd.onClose = LoginForm.hide;
		LoginForm.hide();

		YAHOO.util.Event.addListener(['me2login_id', 'me2login_pw'], 'keydown', LoginForm.handleKey);
	},

	handleKey: function(e) {
		if( e.keyCode != 13 && e.keyCode != 27 ) {
			return;
		}

		switch( e.keyCode ) {
		case 13: // Enter
			LoginForm.onEnter();
			break;
		case 27: // ESC
			LoginForm.onESC();
			break;
		}
	},

	onEnter: function() {
		var id = YAHOO.util.Dom.get('me2login_id').value;
		var pw = YAHOO.util.Dom.get('me2login_pw').value;
		var btn = YAHOO.util.Dom.get('me2login_btn');

		if( id == '' || pw == '' ) {
			alert('Input your id and password');
			return;
		}

		me2.auth.onLogin = function(json) {
			if( json.error ) {
				alert("로그인에 실패했습니다. 아이디와 유저키를 확인하세요.");
				LoginForm.clear();
				return;
			}
			TOOLBOX.onMe2day();
			LoginForm.hide();
		}
		me2.auth.login(id, pw);
	},

	onESC: function() {
		LoginForm.hide();
	},

	show: function() {
		LoginForm.create();
		DPModal.show(0.3);
		LoginForm.wnd.center();
		LoginForm.wnd.show();
		YAHOO.util.Dom.get('me2login_id').focus();
	},

	hide: function() {
		LoginForm.create();
		DPModal.hide();
		LoginForm.clear();
		LoginForm.wnd.hide();
	},

	clear: function() {
		YAHOO.util.Dom.get('me2login_id').value = "";
		YAHOO.util.Dom.get('me2login_pw').value = "";
	}
};

DPModal = {

	modal: null,

	create: function(opacity) {		
		if( opacity != 0 && !opacity ) {
			opacity = 0.3;
		}

		if( !DPModal.modal ) {
			DPModal.modal = new DIV('dp.modal_background');
			DPModal.modal.create(0, 0, YAHOO.util.Dom.getDocumentWidth(), YAHOO.util.Dom.getDocumentHeight());
			//DPModal.modal.setStyle("width", "100%");
			//DPModal.modal.setStyle("height", "100%");
			DPModal.modal.setStyle("background", "#000000");
			DPModal.modal.setStyle("zIndex", "900");
		}

		DPModal.setOpacity(opacity);

		YAHOO.util.Event.addListener(window, "resize", function(e) {
			this.setXYWH(0, 0, YAHOO.util.Dom.getDocumentWidth(), YAHOO.util.Dom.getDocumentHeight());
		}, DPModal.modal, true);
	},

	setOpacity: function(opacity) {
		DPModal.modal.setStyle("filter", "alpha(opacity:" + opacity * 100 + ", style:0)");
		DPModal.modal.setStyle("mozOpacity", opacity);
		DPModal.modal.setStyle("opacity", opacity);
		DPModal.modal.setStyle("khtmlOpacity", opacity);
	},

	show: function(opacity) {
		if( !DPModal.modal ) {
			DPModal.create();
		}
		DPModal.modal.show();

		if( parseInt(opacity) != "NaN" && opacity >= 0 && opacity <= 1 ) {
			DPModal.setOpacity(opacity);
		}
	},
	
	hide: function() {
		if( !DPModal.modal ) {
			DPModal.create();
		}
		DPModal.modal.hide();
	}
};

Query = {
	args: null,

	get: function(name) {
		if( !Query.args ) {
			Query.args = new Object();
			var pairs = location.search.substring(1).split("&");
			for( var i = 0; i < pairs.length; i++ ) {
				var pos = pairs[i].indexOf('=');
				if( pos == -1 ) { 
					continue;
				}
				var key = pairs[i].substring(0, pos); 
				var value = pairs[i].substring(pos + 1); 
				Query.args[key] = unescape(value); 
			}
		}

		return Query.args[name] ? Query.args[name] : null;
	}
};
