EventUtility.prototype.AddEventListener(window, 'load', function () {
	//======================================================
	//Ctrl Init
	//======================================================
	var loop_flag = true;
	var to = null;
	var event_listener_type = EventUtility.prototype.GetEventListenerType(window);
	var limit = 50;
	var old_log_list = [];
	var topic_edit_mode = false;
	var cookie_domain = 'rs.wakabadou.net';
	var cookie_name = {
		'user': 'user_name'
	};
	var _imgCache = {};
	var _msgCache = {};
	var _log_max = 50;
	var _hidden_time_out = null;
	var _div = document.createElement('DIV');
	_div.id = 'res';
	var _viewFlg = false;
	var message_send = false;

	//======================================================
	//URL Init
	//======================================================
	var setUrl = './agileSet.php';
	var getUrl = './agileGet.php';
	var setTopicUrl = './agileTopicSet.php';
	var syncFlag = true;
	var isLink = false;
	var last_id = 0;

	//======================================================
	//XHR Init
	//======================================================
	var sendAc = new AjaxClient();
	var getAc = new RealTimeUpdateClient(getUrl);

	//======================================================
	//Regex Init
	//======================================================
	var rsuploader_url = 'http:\/\/nosm2o\.hp\.infoseek\.co\.jp\/cgi\-bin\/up\/src\/';
	var rsuploader_file_name = 'rs[0-9]+\.';
	var enable_rsuploader_archive_ext = '(txt|lzh|zip|rar|gca|mpg|mp3|avi|swf)';
	var enable_rsuploader_img_ext = '(bmp|jpg|gif|png)';
	var rsuploader_archive = "^"+ rsuploader_url + rsuploader_file_name + enable_rsuploader_archive_ext +"$";
	var rsuploader_img = "^"+ rsuploader_url + rsuploader_file_name + enable_rsuploader_img_ext +"$";

	var rs_up_regex = {
		'archive': new RegExp(rsuploader_archive),
		'img': new RegExp(rsuploader_img)
	};

	//======================================================
	//Cookie Init
	//======================================================
	var cookie = CookieUtility.prototype.loadCookie();

	//======================================================
	//Element Init
	//======================================================
	var inputForm = document.getElementsByName('inputForm')[0];
	var name = inputForm.elements.name;
	var send_message = inputForm.elements.send_message;
	var message = inputForm.elements.message;

	var topic_edit = document.getElementById('topic_edit');
	var topic_from_time = document.getElementById('topic_from_time');
	var topic_writer_name = document.getElementById('topic_writer_name');

	var topic_field = document.getElementById('topic_field');
	topic_field = DomUtility.prototype.Init(topic_field);

	var topic_input = document.getElementById('topic_input');
	topic_input.style.display = 'none';

	var topic_view_mode = document.getElementById('topic_view_mode');

	//======================================================
	//Functions Init
	//======================================================
	var _func = {
		'event': {}
	}

	//======================================================
	//Event Functions
	//======================================================
	_func.event = {
		'anchor': {},
		'form': {},
		'img': {},
		'window': {},
		'status': false
	}
	_func.event.anchor = {
		'changeTopicEdit': function (e) {
			if (!topic_edit_mode) {
				_showTopicField();
			}
			else {
				_hideTopicField();
			}
			topic_edit_mode = !topic_edit_mode;

			return false;
		}
	};
	_func.event.form = {
		'enter': function (e){
			var _event = EventUtility.prototype.GetEvent(e);
			if (_event.keyCode == 9) {
				return true;
			}
			if (EventUtility.prototype.IsIMEFixation(_event) && !_event.shiftKey) {
				send_message.click();
				_func.event.status = true;
				return false;
			}
			return true;
		},
		'noneFocus': function  (e) {
			if (_func.event.status) {
				inputForm.elements.message.focus();
			}
			_func.event.status = false;
		},
		'submitCancel': function (e) {
			var _event = EventUtility.prototype.GetEvent(e);
			EventUtility.prototype.CancelBubble(_event);
			EventUtility.prototype.CancelDefaultEvent(_event);
			inputForm.elements.message.focus();
			return false;
		},
		'sendMessage': function (e){
			var _event = EventUtility.prototype.GetEvent(e);

			var _temp_name = name.value;
			if (_temp_name == '') {
				_temp_name = window.prompt('ユーザ名は必須項目です。', 'R-X774');
				if (_temp_name == null || _temp_name == '') {
					return false;
				}
				name.value = _temp_name;
			}

			message.value = message.value.replace(/(\r\n|\r|\n)+$/, '');

			var _send_data = {
				'name':		name.value,
				'message':	message.value
			};

			if (_send_data.name == '' || _send_data.message == '') {
				return false;
			}

			ret = _send(setUrl, _send_data, _sendMessageAfter);

			message.value = '';

			message_send = true;

			return ret;
		},
		'enterAfter': function () {
			if (message_send) {
				message.value = '';
			}
			message_send = false;
		}
	};

	_func.event.img = {
		'onLoad': function (e) {
			_this = EventUtility.prototype.GetCurrentElement (e, this);
//			_changeImgSize(_this);
		},
		'anchorMounseDown': function (e) {
			var _event = EventUtility.prototype.GetEvent(e);
			var _this = _event.srcElement;
			while (_this.tagName != 'A') {
				_this = _this.parentNode;
			}

			var _match = new String(_this.href).match(rs_up_regex.img);
			if (_match != null) {
				if (_this.temp_href == undefined) {
					_this.temp_href = _this.href;
				}
				else {
					_this.href = _this.temp_href;
				}
				_this.href = './rsupRedirect.php?url=' + _this.href;
			}
		},
		'anchorClick': function  (e) {
			var _event = EventUtility.prototype.GetEvent(e);
			var _this = _event.srcElement;

			if (_this.tagName != 'A' && _this.tagName != 'a') {
				return true;
			}

			if (_this.temp_href == undefined) {
				_this.temp_href = _this.href;
			}
			else {
				_this.href = _this.temp_href;
			}
			var href = _this.href;

			_this.href = './rsupRedirect.php?url=' + href;

			return true;
		}
	}

	_func.event.window = {
		'unLoad': function (e) {
			getAc.stop();
		}
	};

	function _sendTopic (topic) {
		var _send_data = {
			'name':		name.value,
			'topic':	topic
		};

		if (_send_data.name == '') {
			return false;
		}

		return _send(setTopicUrl, _send_data, _sendTopicAfter);
	}

	function imageThumbnail () {
		var _anchor_list = document.getElementsByTagName('A');
		var _anchor = null;
		var _match = null;

		for (var i in _anchor_list) {
			_anchor = _anchor_list[i];
			if (_anchor.href == null) {
				continue;
			}

			_match = new String(_anchor.href).match(rs_up_regex.archive);
			if (_match != null) {
				EventUtility.prototype.AddEventListener(_anchor, 'click', _func.event.img.anchorClick, event_listener_type);
			}
			else {
				_match = new String(_anchor.href).match(/((?:h{0,1}ttps{0,1}):\/\/[a-zA-Z0-9\._\-]+(?::[1-9][0-9]*){0,1}[\/a-zA-Z0-9\.%_\?%\-+=~!]+(?:\.jpg|\.jpeg|\.gif|\.png|\.bmp))/);
				if (_match != null) {
					EventUtility.prototype.AddEventListener(_anchor, 'mouseover', _viewImg, event_listener_type);
					EventUtility.prototype.AddEventListener(_anchor, 'mousedown', _func.event.img.anchorMounseDown, event_listener_type);
				}
			}

			_match = new String(_anchor.href).match(/#([0-9]+)$/);
			if (_match != null) {
				EventUtility.prototype.AddEventListener(_anchor, 'mouseover', _viewMsg, event_listener_type);
			}
		}
	}


	//======================================================
	//Utility Functions
	//======================================================
	function _send (url, send_data, call_back_func) {
		sendAc.setExeccuter(4, call_back_func);
		sendAc.post(url, syncFlag, send_data);
		CookieUtility.prototype.save(cookie_name.user, send_data.name, cookie_domain);
		return false;
	}

	function _addAnchorAndBr (element, add_text) {
		add_text = add_text.replace(/\\r\\n|\\r|\\n/g, "<br />");
		add_text = add_text.replace(/\\"/g, "\"");
		add_text = add_text.replace(/\\'/g, "'");
		add_text_node = document.createTextNode(add_text);
		element.appendChild(add_text_node);
		element.innerHTML = element.innerHTML.replace(/\\t/g, "&nbsp;&nbsp;&nbsp;&nbsp;");

		element.innerHTML = element.innerHTML.replace(/&lt;br \/&gt;/g, "<br />\n");
		element.innerHTML = element.innerHTML.replace(/((?:http|https):\/\/[a-zA-Z0-9\._\-]+(?::[1-9][0-9]*){0,1}[\/a-zA-Z0-9,&\.%_\?%;\-+=~!#]*)/g,function (str, p1) {return '<a href="'+ p1 +'" target="_blank" class="outer_link">' + p1 + '</a>';});
		element.innerHTML = element.innerHTML.replace(/(?:^|[^h])((?:ttp|ttps):\/\/[a-zA-Z0-9\._\-]+(?::[1-9][0-9]*){0,1}[\/a-zA-Z0-9,&;\.%_\?%\-+=~!#]*)/g,function (str, p1) {return '<a href="h'+ p1 +'" target="_blank" class="outer_link">' + p1 + '</a>';});
		element.innerHTML = element.innerHTML.replace(/&gt;&gt;([1-9][0-9]*)/g,function (str, p1) {return '<a href="#'+ p1 +'">>>' + p1 + '</a>';});

		DomUtility.prototype.Init(element);

		return element;
	}

	function _convertDateTimeFormat (date_time_text) {
		return date_time_text.replace(/\-/g, '/');
	}

	function _changeImgSize (element) {
		var max_width = 400;
		var max_height = 300;
		var width_per = 0;
		var height_per = 0;
		var per = 0;

		if (element.width > max_width) {
			width_per = max_width / element.width;
		}
		if (element.height > max_height) {
			height_per = max_height / element.height;
		}

		if (width_per == 0 && height_per == 0) {
			return ;
		}

		if (height_per == 0 || width_per < height_per) {
			per = width_per;
		}
		else if (width_per == 0 || width_per > height_per) {
			per = height_per;
		}
		else {
			per = width_per;
		}

		element.width = element.width * per;
		element.height = element.height * per;
	}

	//======================================================
	//Dom Operation Functions
	//======================================================
	function _showTopicField () {
		topic_input.style.display = 'inline';
		topic_input.value = topic_field.innerText;
		topic_field.style.display = 'none';
	}

	function _hideTopicField () {
		var _temp_name = name.value;

		if (topic_input.value != topic_field.innerText) {
			if (_temp_name == '') {
				_temp_name = window.prompt('ユーザ名は必須項目です。', 'R-X774');
			}
			if (_temp_name != null && _temp_name != '') {
				name.value = _temp_name;
				_sendTopic(topic_input.value);
				if (topic_field != null) {
					topic_field.innerHTML = '反映されるまでお待ち下さい。';
				}
			}
		}

		topic_field.style.display = 'inline';
		topic_input.style.display = 'none';
	}

	function addChatLog (chat_log) {
		var span = document.getElementById('chat_log');

		if (span.lastChild != null) span.removeChild(span.lastChild);

		var ul = document.createElement('UL');
		span.appendChild(ul);

		var log_count = 0;

		var view_log_list = [];
		for (id in chat_log) {
			if (_log_max < ++log_count) {
				break;
			}
			view_log_list.push(chat_log[id]);
		}

		for (id in old_log_list) {
			if (_log_max < ++log_count) {
				break;
			}
			view_log_list.push(old_log_list[id]);
		}

		function log_sort (a, b) {
			return (b.id - a.id);
		}
		view_log_list.sort(log_sort);

		var _view_count = 0;
		for (i in view_log_list){
			if (_log_max < ++_view_count) {
				break;
			}
			var row = view_log_list[i];
			var chat_log_data = {
				'name': row.name,
				'write_datetime': row.insert_date,
				'comment': row.message,
				'id': row.id
			};
			var li = createLogLine(chat_log_data);
			ul.appendChild(li);
		}

		old_log_list = view_log_list;
	}

	function createLogLine (chat_log) {
		var li = document.createElement('LI');
		var br = document.createElement('BR');
		var name_span = document.createElement('SPAN');
		name_span.className = 'log-name';

		var write_time_text = document.createTextNode(' '+ _convertDateTimeFormat(chat_log.write_datetime));
		var nane_text = document.createTextNode(chat_log.name);
		var id_text = document.createTextNode(chat_log.id);

		name_span.appendChild(nane_text);

		li.id = chat_log.id;
		li.appendChild(id_text);
		li.appendChild(document.createTextNode(':'));
		li.appendChild(document.createTextNode('['));
		li.appendChild(name_span);
		li.appendChild(document.createTextNode(']'));
		li.appendChild(write_time_text);
		li.appendChild(br);

		var span = document.createElement('SPAN');
		span = _addAnchorAndBr(span, chat_log.comment);
		li.appendChild(span);

		return li;
	}

	function _viewPopUp (view_point, innerElement) {
		if (_viewFlg) {
			_closePopup();
		}

		_div.appendChild(innerElement);
		document.body.appendChild(_div);
		_div.style.top = view_point.pageY - 5 + 'px';
		_div.style.left = view_point.pageX - 5 + 'px';

		_viewFlg = true;
	}

	function _closePopup () {
		while (_div.lastChild) {
			_div.removeChild(_div.lastChild);
		}

		if (DomUtility.prototype.hasChild(document.body, _div)) {
			document.body.removeChild(_div);
		}
		_viewFlg = false;
	}

	function _hiddenPopup () {
		_hidden_time_out = setTimeout(_closePopup, 50);
	}

	function _viewImg (e) {
		var _event = EventUtility.prototype.GetEvent(e);
		var _currentViewElement = _event.srcElement;

		if (_currentViewElement.nodeName != 'A') {
			_clearTimeout();
			return false;
		}

		if (_imgCache[_event.srcElement.href] == null) {
			var img = new Image;
			var href = _event.srcElement.href;
			var _match = new String(href).match(rs_up_regex.img);
			if (_match != null) {
				href = './rsupProxy.php?url=' + href;
			}

			img.src = href;
			EventUtility.prototype.AddEventListener(img, 'load', _func.event.img.onLoad, event_listener_type);

			var a = document.createElement('A');
			a.href = _currentViewElement.href;
			a.appendChild(document.createTextNode(_currentViewElement.href));
			a.appendChild(img);
			a.target = '_blank';
			a.style.color = '#ffffff';
			EventUtility.prototype.AddEventListener(a, 'click', _func.event.img.anchorMounseDown, event_listener_type);

			_imgCache[_event.srcElement.href] = a;
		}

		

		_viewPopUp(_event, _imgCache[_event.srcElement.href]);
	}

	function _clearTimeout () {
		clearTimeout(_hidden_time_out);
	}

	function _viewMsg (_event) {
		_event = EventUtility.prototype.GetEvent(_event);
		var _currentViewElement = _event.srcElement;

		var target_id = new String(_event.srcElement.href).match(/#([0-9]+$)/);

		if (target_id == null) {
			return false;
		}

		target_id = target_id[1];

		target_element = document.getElementById(target_id);

		if (target_element == null) {
			if (_msgCache[target_id] != null) {
				_msgCache[target_id] = null;
			}
			return false;
		}

		if (_msgCache[target_id] == null) {
			_msgCache[target_id] = document.createElement('SPAN');
			_msgCache[target_id].innerHTML = target_element.innerHTML;
			EventUtility.prototype.AddEventListener(_msgCache[target_id], 'mouseover', _clearTimeout, event_listener_type);
		}
		_viewPopUp(_event, _msgCache[target_id]);
	}

	function _chngViewTopic (_event) {
		_event = EventUtility.prototype.GetEvent(_event);
		var src_element = _event.srcElement;

		var _topic_body = document.getElementById('topic_body');
		_topic_body.style.display = (_topic_body.style.display != 'none') ? 'none' : 'block';
		src_element.innerHTML = (_topic_body.style.display != 'none') ? '[-]' : '[+]';
	}

	function viewTopic (topic) {
		while (topic_field.lastChild) {
			topic_field.removeChild(topic_field.lastChild);
		}

		if (topic_from_time.lastChild != null) topic_from_time.removeChild(topic_from_time.lastChild);
		if (topic_writer_name.lastChild != null) topic_writer_name.removeChild(topic_writer_name.lastChild);

		topic_writer_name.appendChild(document.createTextNode(topic.name));
		topic_from_time.appendChild(document.createTextNode(' '+ _convertDateTimeFormat(topic.insert_time)));

		topic_field = _addAnchorAndBr(topic_field, topic.topic);

		topic_field = DomUtility.prototype.Init(topic_field);
	}

	function viewError (error_message) {
		var span = document.getElementById('chat_log');
		var text = document.createTextNode(error_message);
		if (span.lastChild != null) span.removeChild(span.lastChild);
		span.appendChild(text);
		span.innerHTML = span.innerHTML.replace(/\n/g, '<br />');
		span.style.color = '#ff0000';
	}

	//======================================================
	//Callback Functions
	//======================================================
	function viewMessage(responseObj){
		if (responseObj.responseText == 'null' || responseObj.responseText == ''){
			return;
		}

		function reboot() {
			getAc.stop();
			getAc.run();
		}

		if (to != null) {
			clearTimeout(to);
		}

		eval('var json = '+ responseObj.responseText +';');

		if (json.system.status == 'error') {
			viewError(json.system.message);
			getAc.stop();
			return;
		}

		if (json['chat_log'] != null) {
			addChatLog(json['chat_log']);
			imageThumbnail();
			last_id = json['last_id'];
		}

		if (json['topic'] != null) {
			viewTopic(json['topic']);
		}

		sendData = {
			'limit': limit,
			'last_id': last_id
		};
		getAc.setSendData(sendData);

		to = setTimeout(reboot, 20000);

		return ;
	}

	function _sendTopicAfter (responseObj) {
	}

	function _sendMessageAfter(responseObj){
	}

	//======================================================
	//Event Init
	//======================================================
	EventUtility.prototype.AddEventListener(message, 'keydown', _func.event.form.enter, event_listener_type);
	EventUtility.prototype.AddEventListener(message, 'keyup', _func.event.form.enterAfter, event_listener_type);
	EventUtility.prototype.AddEventListener(send_message, 'click', _func.event.form.sendMessage, event_listener_type);
	EventUtility.prototype.AddEventListener(send_message, 'focus', _func.event.form.noneFocus, event_listener_type);
	EventUtility.prototype.AddEventListener(inputForm, 'submit', _func.event.form.submitCancel, event_listener_type);
	EventUtility.prototype.AddEventListener(topic_edit, 'click', _func.event.anchor.changeTopicEdit, event_listener_type);
	EventUtility.prototype.AddEventListener(window, 'unload', _func.event.window.unLoad, event_listener_type);
	EventUtility.prototype.AddEventListener(_div, 'mouseover', _clearTimeout, event_listener_type);
	EventUtility.prototype.AddEventListener(_div, 'mouseout', _hiddenPopup, event_listener_type);
	EventUtility.prototype.AddEventListener(topic_view_mode, 'click', _chngViewTopic, event_listener_type);

	//======================================================
	//Commet Start
	//======================================================
	if (cookie.user_name != null) {
		name.value = unescape(cookie.user_name);
	}

	getAc.setExecute(viewMessage);

	sendData = {
		'limit': limit,
		'force': 'get'
	};

	getAc.setSendData(sendData);

	getAc.run();
}
);
