/**
 * @fileoverview
 * rainTail Version 2.00 (2008.11.11)
 * ´ç ÇÁ·Î±×·¥ÀÇ ÀúÀÛ±ÇÀº http://cafen.net (outmind@cafen.net)¿¡ ÀÖ½À´Ï´Ù
 * ´ç ÇÁ·Î±×·¥ÀÇ ¼öÁ¤ ÈÄ Àç ¹èÆ÷´Â ÀúÀÛ±ÇÀÚÀÇ Çã¶ôÀ» µæÇÑ ÈÄ Àç¹èÆ÷ ÇÒ¼ö ÀÖ½À´Ï´Ù. 
 * ´ç ÇÁ·Î±×·¥ÀÇ ÀÌ¿ëÀº ºñ »ó¾÷ÀûÀÎ ¸ñÀûÀÇ °æ¿ì ¹«·á·Î ÀÌ¿ëÇÒ ¼ö ÀÖ½À´Ï´Ù.
 * ´ç ÇÁ·Î±×·¥ÀÇ ÀÌ¿ëÀº »ó¾÷ÀûÀÎ ¸ñÀûÀÇ °æ¿ì ÀúÀÛ±ÇÀÚÀÇ Çã¶ôÀ» µæÇÑ ÈÄ ÀÌ¿ëÇÒ ¼ö ÀÖ½À´Ï´Ù.
 * ´ç ÇÁ·Î±×·¥ÀÇ ¼³Ä¡ÈÄ °ü¸®ÀÚ´Â outmind@cafen.net À¸·Î ¼³Ä¡ÇÏ¿´´Ù´Â Åëº¸ ¸ÞÀÏÀ» ¹ß¼ÛÇÏ¿©¾ß ÇÕ´Ï´Ù.
 * ´ç ÇÁ·Î±×·¥¾È¿¡ ÀÖ´Â ¸ðµç ÀúÀÛ±Ç Ç¥½Ã ¿µ¿ªÀº ¼öÁ¤ÇÒ¼ö ¾ø½À´Ï´Ù.
 *
 * ------------------------------------------------
 * ¼³Ä¡ ¹æ¹ýÀº ÇÔ²² ¹èÆ÷µÈ README ÆÄÀÏ ÂüÁ¶ ¹Ù¶ø´Ï´Ù.
 * ------------------------------------------------
 *
 * @author Kimjonggab(outmind@cafen.net)
 * @copyright Copyright (c) 2004 Cafen.net (http://cafen.net)
 */


function rainTail() {}

rainTail.prototype = {
	render : function() {
		for (var i = 0; i < arguments.length; i++) {
			var element = arguments[i];
			if (typeof element == 'string')
				element = document.getElementById(element);
			if (element != null)
				this._renderElement(element);
		}
	},
	renderElement : function() {
		for (var i = 0; i < arguments.length; i++) {
			var element = arguments[i];
			if (typeof element == 'string')
				element = document.getElementById(element);
			if (element != null)
				this._renderElement(element);
		}
	},
	_renderElement : function(editorObj) {
		var textAttribObj = new rainAttribute(editorObj);
		var options = {
			siteid : textAttribObj.getString('siteid'),
			pageid :textAttribObj.getString('pageid')
		}
		new rain.ajaxTail(editorObj, options);
	},
	/**
	* render Elements by className
	* @param {string}  className The class name of the Object to do render
	*/
	renderElementsByClassName : function(className) {
		var objs = document.getElementsByTagName('div');
		var editorObjs = [];
		for(var i =0; i < objs.length; i++) {
			var child = objs[i];
			if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))) 
				editorObjs.push(child);
		}
		for(var i=0; i < editorObjs.length; i++) 
			this.renderElement(editorObjs[i]);
	},
	/**
	* render Elements by id
	* @param {string}  id The id of the Object to do render
	*/
	renderElementsById : function(id) {
		if (document.getElementById(id) != null) {
			var editorObjs = [];
			var objs = document.getElementsByTagName(document.getElementById(id).tagName);
			for(var i=0;i<objs.length;i++){
				if(objs[i].id==id) 
					editorObjs.push(objs[i]);
			}
			for(var i=0; i < editorObjs.length; i++) 
				this.renderElement(editorObjs[i]);
		}
	},
	/**
	* render Elements by className
	* @param {string}  className The class name of the Object to do render
	*/
	renderElementsByName : function(objName) {
		var objs = document.getElementsByTagName('div');
		var editorObjs = [];
		for(var i =0; i < objs.length; i++) {
			var child = objs[i];
			if (child.getAttribute('name') == objName) 
				editorObjs.push(child);
		}
		for(var i=0; i < editorObjs.length; i++) 
			this.renderElement(editorObjs[i]);
	}
}

if (typeof rain == 'undefined')
	var rain = new Object();


rain.ajaxTail = function(id, options) {
	this.obj = id;
	this.options = rain.nodeUtil.extendObj({cline : 0, width : 650, line : '#d0d0d0'}, options);
	this.init();
}

rain.ajaxTail.prototype = {
	init : function() {
		this.style_class = new rain.Popup.style({});
		this.drawTail();
		rain.ajaxTailParser.checkSWFAjax();
		this.getDataBind = this.setData.bind(this);
		rain.ajaxTailParser.getFlashXml(this.options.siteid, this.options.pageid, this.options.cline, this.getDataBind);
	},
	drawTail : function() {
		this.obj.innerHTML = '';
		var inputobj = this.getInputObj(this.options.width, 'center');
		this.obj.appendChild(inputobj.obj);
		if (inputobj.text.onAppend)
			inputobj.text.onAppend();
		this.obj_nameobj = inputobj.name;
		this.obj_nameobj.value = this.getName();
		this.obj_passwdobj = inputobj.passwd;
		this.obj_textareaobj = inputobj.text;
		this.obj_trackobj = inputobj.track;
		inputobj.button.onclick = this.addTail.bind(this);
		this.obj_areadisplay = this.obj.appendChild(rain.nodeUtil.getDiv({}, {width : this.options.width +'px'}));
	},
	getInputObj : function(base_width, base_align) {
		var divobj = rain.nodeUtil.getDiv({},{width : this.options.width +'px', height:'135px', textAlign: base_align});
		var tableobj = rain.nodeUtil.extendObj(document.createElement('table'), {width : base_width , border : '0', cellPadding :'0', cellSpacing :'2' , align: base_align});
		divobj.appendChild(tableobj);
		var tr_obj = tableobj.insertRow(-1);
		var td_obj = rain.nodeUtil.extendObj(tr_obj.insertCell(-1), {innerHTML : '', align :'left', colSpan : '2'});
		var nameobj = td_obj.appendChild(document.createElement('input'));
		nameobj.title = 'Name';
		nameobj.maxlength = 10;
		Element.setStyle(nameobj, {width : '90px', border : '1px solid ' + this.options.line});
		var obj =document.createElement('input');
		obj.setAttribute('type', 'password',0);
		obj.maxlength = 10;
		var passwdobj = td_obj.appendChild(obj);
		passwdobj.title = 'Password';
		Element.setStyle(passwdobj, {width : '90px', border : '1px solid ' + this.options.line, marginLeft: '4px'});
		var trackobj = td_obj.appendChild(document.createElement('input'));
		trackobj.title = 'TrackBack';
		trackobj.maxlength = 50;
		Element.setStyle(trackobj, {width : '250px', border : '1px solid ' + this.options.line, marginLeft: '4px'});

		var tr_obj = tableobj.insertRow(-1);
		var td_obj = rain.nodeUtil.extendObj(tr_obj.insertCell(-1), {innerHTML : '', Align :'center'});
		var textareaobj = td_obj.appendChild(document.createElement('textarea'));
		Element.setStyle(textareaobj, {width : (base_width - 60) +'px', height : '100px', border : '1px solid ' + this.options.line});
		var td_obj = rain.nodeUtil.extendObj(tr_obj.insertCell(-1), {innerHTML : '', Align :'center' , vAlign:'top'});
		var submitobj = td_obj.appendChild(rain.nodeUtil.getImgButton({}, _rain_service_url +'images/ajaxtails/btn_submit.gif',60,50));
		if (typeof rainEditorS != 'undefined' && typeof rainEditorS_HTC != 'undefined') {
			textareaobj.setAttribute('width', (base_width - 60) +'',0);
			textareaobj.setAttribute('height', '70',0);
			textareaobj.setAttribute('resize', 'false',0);
			textareaobj.setAttribute('topmenu', 'OFF',0);
			textareaobj.setAttribute('onloadfocus', 'false',0);
			textareaobj.onAppend = function() {
				rainEditorS_HTC.render(this);
			}
		} 
		return {obj : divobj , name : nameobj, passwd : passwdobj, text : textareaobj, button : submitobj, track : trackobj}
	},
	addTail : function() {
		if (this.isNull(this.obj_nameobj.value)) {
			this.showMsg(rainMsg.get('tail_0001'));
			this.obj_nameobj.focus();
		} else if (this.isNull(this.obj_passwdobj.value)) {
			this.showMsg(rainMsg.get('tail_0002'));
			this.obj_passwdobj.focus();
		} else if (this.obj_textareaobj.parse != null && !this.obj_textareaobj.parse()) {

		} else if (this.obj_textareaobj.parse == null && this.isNull(this.obj_textareaobj.value)) {
			this.showMsg(rainMsg.get('tail_0003'));
			this.obj_textareaobj.focus();
		} else {
			var isHTML = (this.obj_textareaobj.parse) ? '1' : '0'; 
			var track = (this.obj_trackobj.value.indexOf('http://') == 0 && this.obj_trackobj.value.length > 10) ?  this.obj_trackobj.value : '';
			rain.ajaxTailParser.getFlashXml(this.options.siteid, this.options.pageid, this.options.cline, this.getDataBind, {contents : this.obj_textareaobj.value, ishtml : isHTML, name : this.obj_nameobj.value, pass : this.obj_passwdobj.value, track : track});
			this.obj_textareaobj.value = '';
			if (this.obj_textareaobj.insertHTML)
				this.obj_textareaobj.insertHTML('',3);
			this.setName(this.obj_nameobj.value);
		}
	},
	addReply : function() {
		if (this.isNull(this.reply_nameobj.value)) {
			this.showMsg(rainMsg.get('tail_0001'));
			this.reply_nameobj.focus();
		} else if (this.isNull(this.reply_passwdobj.value)) {
			this.showMsg(rainMsg.get('tail_0002'));
			this.reply_passwdobj.focus();
		} else if (this.reply_textareaobj.parse != null && !this.reply_textareaobj.parse()) {

		} else if (this.reply_textareaobj.parse == null && this.isNull(this.reply_textareaobj.value)) {
			this.showMsg(rainMsg.get('tail_0003'));
			this.reply_textareaobj.focus();
		} else  {
			var isHTML = (this.obj_textareaobj.parse) ? '1' : '0'; 
			var track = (this.obj_trackobj.value.indexOf('http://') == 0 && this.obj_trackobj.value.length > 10) ?  this.obj_trackobj.value : '';
			rain.ajaxTailParser.getFlashXml(this.options.siteid, this.options.pageid, this.options.cline, this.getDataBind, {contents : this.reply_textareaobj.value, ishtml : isHTML, name : this.reply_nameobj.value, pass : this.reply_passwdobj.value, id : this.lastSelectedID, track : track});
			this.reply_textareaobj.value = '';
			if (this.reply_textareaobj.insertHTML)
				this.reply_textareaobj.insertHTML('',3);
			this.setName(this.reply_nameobj.value);
			this.lastSelectedID = null;
		}
	},
	setName : function(cookieValue) {
		if (cookieValue != this.getName()) {
			this.userName = cookieValue;
			var today = new Date();
			var expire = new Date();
			expire.setTime(today.getTime() + 3600000*24*7);
			document.cookie = 'rainTailName'+"="+escape(cookieValue)+";expires="+expire.toGMTString() +";path=/;";
		}
	},
	getName : function() {
		if (this.userName == null) {
		    var dc = document.cookie;
		    var prefix = 'rainTailName' + "=";
		    var begin = dc.indexOf("; " + prefix);
		    if (begin == -1) {
		        begin = dc.indexOf(prefix);
		        if (begin != 0) return this.userName = '';
		    } else {
		        begin += 2;
		    }
		    var end = document.cookie.indexOf(";", begin);
		    if (end == -1) end = dc.length;
		    return this.userName = unescape(dc.substring(begin + prefix.length, end));
		 } else
		 	return this.userName;
	},
	isNull : function(val) {
		return (val.split(' ').join('') == '') ? true : false;
	},
	setData : function(result, msg) {
		this.result = result;
		this.dataObjs = {};
		if (this.reply_obj != null && this.reply_obj.obj.parentNode != null )
			this.reply_obj.obj.parentNode.removeChild(this.reply_obj.obj);
		this.obj_areadisplay.innerHTML = '';
		if (this.result != null && this.result.length > 0) {
			for(var i = 0; i < this.result.length; i++) {
				var currObj = this.result[i];
				var obj = this.obj_areadisplay.appendChild(rain.nodeUtil.getDiv({}, {width : this.options.width +'px'}));
				var childobj = obj.appendChild(rain.nodeUtil.getDiv({}, {borderLeft : '2px solid ' + this.options.line, borderBottom : '1px solid ' + this.options.line, marginTop : ((currObj.depth > 0) ? '0px' : '5px'), marginLeft : (currObj.depth *20) + 'px'}));
				childobj.appendChild(rain.nodeUtil.getDiv({className: 'rainEditorContents',innerHTML : currObj.contents}, {textAlign:'left', padding : '3px'}));
				childobj.appendChild(rain.nodeUtil.getDiv({innerHTML : currObj.wdate + ' <i>writen by</i> <b>' +currObj.name +'</b>'}, {textAlign:'right', padding : '3px'}));
				var button_area = childobj.appendChild(rain.nodeUtil.getDiv({}, {textAlign:'right', padding : '1px'}));
				button_area.appendChild(rain.nodeUtil.getImgButton({onclick : this.setReply.bind(this,currObj.id)}, _rain_service_url +'images/ajaxtails/btn_reply.gif',37,13));
				button_area.appendChild(rain.nodeUtil.getImgButton({onclick : this.setDelete.bind(this,currObj.id)}, _rain_service_url +'images/ajaxtails/btn_delete.gif',37,13));
				this.dataObjs[currObj.id] = obj;
			}
		}
		if (msg != null && msg != '')
			this.showMsg(msg);
	},
	getPopupClass : function() {
		if (this.popup_class == null) {
			this.popup_class = new rain.Popup(this.style_class, {zIndex: '1000'});
		}
		return this.popup_class;
	},
	showMsg : function(msg) {
		this.getPopupClass().add(
			new rain.Popup.alert(
				msg,
				this.style_class
			)
		,{is_scrollable:true});
	},
	setReply : function(id) {
		if (this.lastSelectedID == id) {
			if (this.reply_obj != null )
				this.reply_obj.obj.parentNode.removeChild(this.reply_obj.obj);
			this.lastSelectedID = null;
		} else {
			this.lastSelectedID = id;
			if (this.reply_obj == null) {
				this.reply_obj = this.getInputObj(this.options.width -70, 'right');
				this.reply_nameobj = this.reply_obj.name;
				this.reply_nameobj.value = this.getName();
				this.reply_passwdobj = this.reply_obj.passwd;
				this.reply_textareaobj = this.reply_obj.text;
				this.reply_trackobj = this.reply_obj.track;
				this.reply_obj.button.onclick = this.addReply.bind(this);
			}
			var findObj = null;
			for (var i =0; i < this.obj_areadisplay.childNodes.length; i++) {
				var currObj = this.obj_areadisplay.childNodes[i];
				if (this.dataObjs[this.lastSelectedID] == currObj) {
					if (i+1 <= this.obj_areadisplay.childNodes.length)
						findObj = this.obj_areadisplay.childNodes[i +1];
					else
						findObj = null;
					break;
				}
			}
			if (findObj != null)
				this.obj_areadisplay.insertBefore(this.reply_obj.obj, findObj);
			else
				this.obj_areadisplay.appendChild(this.reply_obj.obj);
			if (this.reply_textareaobj.onAppend)
				this.reply_textareaobj.onAppend();
		}
	},
	setDelete : function(id) {
		this.lastSelectedID = id;
		if (this.getpass_class == null)
			this.getpass_class = new rain.Popup.prompt(rainMsg.get('tail_0004'), this.deleteTail.bind(this), {type : 'password'}, this.style_class);
		this.getPopupClass().add(this.getpass_class,{is_scrollable:true});
	},
	deleteTail : function(passwd) {
		rain.ajaxTailParser.getFlashXml(this.options.siteid, this.options.pageid, this.options.cline, this.getDataBind, 
			{mode : 'delete', id : this.lastSelectedID, pass : passwd}
		);
		this.lastSelectedID = null;
	}
}


rain.ajaxTailParser = {
	ajaxObj : null,
	ajaxObjReady : false,
	ajaxOnLoad : [],
	isunderRequest : false,
	checkAPI : function() {
	},
	checkSWFAjax : function() {
		if (this.ajaxObj == null) {
			var flash_url  = _rain_service_url+'images/rainajax.swf';
			var targetElement = document.getElementsByTagName("body")[0];
			var container = document.createElement("div");
			container.style.width = "1px";
			container.style.height = "1px";
			targetElement.appendChild(container);
			container.innerHTML = this.getFlashHTML(flash_url);
			this.ajaxObj = document.getElementById('_rainTailAjaxSwf');
		}
	},
	setFlashReady : function() {
		this.ajaxObjReady = true;
		this.ajaxObj = document.getElementById('_rainTailAjaxSwf');
		if (this.ajaxOnLoad.length > 0) {
			var currObj  = this.ajaxOnLoad[0];
			this.ajaxOnLoad.shift();
			this.getFlashXml(currObj.siteId, currObj.pageId, currObj.cline, currObj.callBack, currObj.options);	
		}
	},
	getFlashXml : function(siteid, pageid, cline, callBack, options) {
		if (this.ajaxObjReady) {
			this.last_callBack = callBack;
			this.isunderRequest = true;
			var dat = rain.nodeUtil.extendObj({
				siteid : siteid,
				pageid : pageid,
				cline : cline	
			}, options);
			var _url = 'http://openapi.cafen.net/IMAGES/raintail.html';
			this.ajaxObj.setObject({
				'url'  : _url,
				'type' : 'post',
				'data' : dat,
				'charset' : 'UTF-8',
				'callback'     : 'rain.ajaxTailParser.onloadXML'
			});
		} else
			this.ajaxOnLoad.push({siteId : siteid, pageId :pageid, cline : cline, callBack : callBack, options : options});		
	},
	onloadXML : function(success, data) {
		if (success &&  typeof data != 'undefined') {
			var responseText = decodeURIComponent(data);
			var result = [];
			var msg = '';
			var item, channel, xml = new rain.xmlParser(responseText);
			if (channel = xml.getNext()) {
				msg = channel.getNode('message');
				while(item = channel.getNext()) {
					result.push({contents : item.getNode('description'), name : item.getNode('name'), wdate : item.getNode('date'), id : item.getNode('id'), depth : parseInt(item.getNode('depth'))});
				}
			}
			this.last_callBack(result,msg);
		} else {
			this.last_callBack(null);
		}
		this.isunderRequest = false;
		if (this.ajaxOnLoad.length > 0) {
			var currObj  = this.ajaxOnLoad[0];
			this.ajaxOnLoad.shift();
			this.getFlashXml(currObj.siteId, currObj.pageId, currObj.cline, currObj.callBack, currObj.options);	
		}
	},
	getFlashVars : function() {
		var flashvars = [];
		flashvars.push('flashReady=' + encodeURIComponent('rain.ajaxTailParser.setFlashReady'));
		flashvars.push('debugEnabled=false');
		return flashvars.join('&amp;');
	},
	getFlashHTML : function (flash_url) {
		return ['<object id="_rainTailAjaxSwf" type="application/x-shockwave-flash" data="', flash_url, '" width="1" height="1" style="-moz-user-focus: ignore;">',
					'<param name="movie" value="', flash_url , '" />',
					'<param name="bgcolor" value="#FFFFFF" />',
					'<param name="quality" value="high" />',
					'<param name="menu" value="false" />',
					'<param name="allowScriptAccess" value="always" />',
					'<param name="flashvars" value="' + this.getFlashVars() + '" />',
					'</object>'].join("");
	}
}

