//<![CDATA[
function hotTagItem() {
	this.stid = -1;
	this.tag = null;
	this.tagcontent = null;
	this.writedate = null;	
	this.msgcnt = 0;
}

function minPollItem() {
	this.mpid = -1;
	this.title = null;
	this.content = null;
	this.assentCnt = 0;
	this.blackballCnt = 0;
	this.media = null;
	this.visibleDateBegin = null;
	this.visibleDateEnd = null;
	this.writedate = null;
	this.isActive = false;
	this.isModified = false;	
}

function widgetItem() {
	this.wgid = -1;
	this.title = null;
	this.link = null;
	this.isLinkNewWin = false;
	this.media = null;
	this.visibleDateBegin = null;
	this.visibleDateEnd = null;
	this.content = null;
	this.widgetCount = null;
	this.isActive = false;
	this.isModified = false;
}

var HotTag = {
	blocker: new LayerBlocker(0.7),
	contextPath: '',
	stid: -1,
	seTag: '',				//태그 검색어
	userid: '',
	mainTag: '',			//메인에 노출되는 태그의 선택값
	wrTag: '',				//이야기 작성시 주제의 태그가 삭제되지 않도록 유지용이다
	isCallBack: 'false',	//최초에만 핫태그 5개를 보여주고 그 외의 검색이나 클릭시에 핫태그가 변동되지 않도록 한다
	items: new Array(),
	deleteItems: new Array(),
	today: new Date(),	
	
	loadInitialList: function(action) {	
		new Ajax.Request(this.contextPath + '/servlet/index/hotTag', {
			method: 'get',
			parameters: 'action='+action+'&searchTag='+this.seTag,
			onSuccess: function(transport) {
				var r = xml2json(transport.responseXML, '').evalJSON();
				if (r.result['@error'] == 'true') {
					alert(r.result.message['#cdata']);
					return;
				}
				HotTag.processChange(r.result, action);
			}
		});
	},
	
	//프로세서 분기
	processChange: function(result, action) {
		if(action == "main"){
			//핫태그 검색 메인
			HotTag.displayItemsAsTagGroup(result);
			HotTag.displayItems(result);
		}
	},
	
	convertStrToDate: function(dateStr) {
		var date = new Date();
		
		var year = parseInt(dateStr.substring(0,4), 10);
		var month = parseInt(dateStr.substring(5,7), 10);
		var day = parseInt(dateStr.substring(8,10), 10);
		var hour = parseInt(dateStr.substring(11,13), 10);
		var minutes = parseInt(dateStr.substring(14,16), 10);
		
		date.setFullYear(year, month-1, day);
		date.setHours(hour, minutes, 0, 0);
		
		return date;
	},
	
	convertDateToString: function(dateObj) {
		var dateStr = '';
		
		dateStr += dateObj.getFullYear().toPaddedString(4);
		dateStr += '-' + (dateObj.getMonth() + 1).toPaddedString(2);
		dateStr += '-' + dateObj.getDate().toPaddedString(2);
		
		dateStr += ' ' + dateObj.getHours().toPaddedString(2);
		dateStr += ':' + dateObj.getMinutes().toPaddedString(2);
		
		return dateStr;
	},
	
	//핫태그 정보를 아이템값에 넣는다
	createItem: function(hottagInfo) {
		var item = new hotTagItem();
		item.stid			= parseInt(hottagInfo['@stid'], 10);
		item.writedate		= parseInt(hottagInfo['@writedate'], 10);
		item.msgcnt			= parseInt(hottagInfo['@msgcnt'], 10);
		item.tag 			= hottagInfo.tagWord['#cdata']; 
		if(hottagInfo.tagContent != null)
			item.tagcontent		= hottagInfo.tagContent['#cdata'];
		return item;
	},
	
	//받아온 핫태그 아이템(xml)을 파싱해서 보여준다
	displayItems: function(result) {		
		var tLavelObj1 = $('cTagList');	//태그 위치 1
		//removeAllChildren(tLavelObj1);
		var tmpTagInfo = "";
		if (result.tagInfo != null) {
			if (typeof(result.tagInfo.size) != 'function')
				result.tagInfo = [result.tagInfo];
			
			var rand_no = Math.random();
			rand_no = rand_no * (result.tagInfo.length);
			rand_no = Math.floor(rand_no);

			for (var i = 0; i < result.tagInfo.length; i++) {
				var tagInfo = result.tagInfo[i];
				var item = this.createItem(tagInfo);
				var tagNameView = new Element('dt', {"id" : "dt_"+i});

				//alert(rand_no);
				if(i == rand_no){
					//태그 포스트를 불러온다
					g_addtionalVar01 = item.tag;					
					getMessageList(0, 10, 10);
					
					$('tagName').innerHTML = item.tag;

					// 프레이임 삭제되면 여기서 스크립트 오류가 발생하여, 아래쪽 코드는 실행되지 않는다.
					//아이프레임을 동작시킨다
					/*
					if(item.tagcontent != null && item.tagcontent != ""){
						$('ifrm').style.display = '';
						var encodeTag = encodeURIComponent(item.tag);						
						$('tagIfrm').src  = this.contextPath+"/hotissue/hottagIframe.jsp?stid="+item.stid+"&tag="+encodeTag;
					}else
						$('ifrm').style.display = 'none';
					
					//this.wrTag = "#"+item.tag+" ";	//메시지 창에 태그를 넣는다
					//$('messageBox').value = this.wrTag;
					$('restLength').innerHTML = 140 - $('messageBox').value.length;
					
					
					tagNameView.addClassName('selected');
					tagNameView.appendChild(new Element('a', {'href': 'JavaScript:HotTag.searchTag("'+item.tag+'", "dt_'+i+'")'}).update('#'+item.tag));
					*/
				}else{
					//나머지 태그를 넣는다.
					/*
					tagNameView.appendChild(new Element('label').update(" | "));
					tagNameView.appendChild(new Element('a', {'href': 'JavaScript:HotTag.searchTag("'+item.tag+'", "dt_'+i+'")'}).update('#'+item.tag));
					*/
				}
				if(this.isCallBack == "false"){
					//tLavelObj1.appendChild(tagNameView);
				}
			}
			
			if(this.isCallBack == "true"){
				//다른태그를 클릭이나 검색시 해당 태그에 포커스를 주기위해서
				var tagNode1 = $('cTagList');
				var tagNode = tagNode1.firstChild;
				while(tagNode){					
					if(tagNode.nodeName == "DT"){
						if(tagNode.className == "selected"){
							tagNode.className = "";
						}
					}
					tagNode = tagNode.nextSibling;
				}
				if(this.mainTag != ""){
					$(this.mainTag).className = "selected";
				}				
			}
			
			//핫태그값을 변동하지 않도록 값을 변경한다
			this.isCallBack = "true";							
			
		} else {
			alert("검색된 태그가 없습니다.");
		}
	},

	//받아온 핫태그 아이템(xml)을 파싱해서 보여준다
	displayItemsAsTagGroup: function(result) {
		var tLavelObj1 = $('cTagIfm');	//태그 위치 1
		removeAllChildren(tLavelObj1);
		var tmpTagInfo = "";
		if (result.tagInfo != null) {
			if (typeof(result.tagInfo.size) != 'function')
				result.tagInfo = [result.tagInfo];			
			for (var i = 0; i < result.tagInfo.length; i++) {
				var tagInfo = result.tagInfo[i];
				var item = this.createItem(tagInfo);
				var tagNameView = new Element('a', {'href': 'JavaScript:HotTag.searchTagAsGroup("'+item.tag+'")'}).update(item.tag);
				
				//태그를 넣는다.
				if(item.msgcnt < 10){
					tagNameView.addClassName('t1');
				}
				else if(item.msgcnt >= 10 && item.msgcnt < 20){
					tagNameView.addClassName('t2');
				}
				else if(item.msgcnt >= 20 && item.msgcnt < 50){
					tagNameView.addClassName('t3');
				}
				else if(item.msgcnt >= 50 && item.msgcnt < 90){
					tagNameView.addClassName('t4');
				}
				else if(item.msgcnt >= 90){
					tagNameView.addClassName('t5');
				}
				
				//if(i != 0)
				//	tagNameView.appendChild(new Element('label').update(" , "));
				//tagNameView.appendChild(new Element('a', {'href': 'JavaScript:HotTag.searchTagAsGroup("'+item.tag+'")'}).update(item.tag));

				if(this.isCallBack == "false"){
					tLavelObj1.appendChild(tagNameView);
				}
			}
		} else {
			alert("검색된 태그가 없습니다.");
		}
	},
	
	//핫태그 검색
	searchTag: function(tagName, tagId) {
		$('tagSch').value = tagName;
		var encodeTag = encodeURIComponent(tagName);
		this.seTag = encodeTag;		
		this.mainTag = tagId;
		this.loadInitialList('main');
	},

	//태그 검색 페이지로
	searchTagAsGroup: function(tagName, tagId) {
		$('tagSch').value = tagName;
		fnSearch();
	},
	
	//민폴 정보를 가져온다
	minpoll: function() {
		new Ajax.Request(this.contextPath + '/servlet/index/minPoll', {
			method: 'get',
			parameters: 'action=lastMinpoll',
			onSuccess: function(transport) {
				var r = xml2json(transport.responseXML, '').evalJSON();
				if (r.result['@error'] == 'true') {
					alert(r.result.message['#cdata']);
					return;
				}
				HotTag.displayMinpollItems(r.result);
			}
		});
	},
	
	displayMinpollItems: function(result) {		
		var tDivObj = $('sPoll');
		tDivObj.innerHTML = "";
		if (result.minpollInfo != null) {			
			if (typeof(result.minpollInfo.size) != 'function')
				result.minpollInfo = [result.minpollInfo];
			for (var i = 0; i < result.minpollInfo.length; i++) {
				var minpollInfo = result.minpollInfo[i];

				var item = this.createMinpollItem(minpollInfo);
				
				this.createRow(item);
				//tDivObj.appendChild(rowObj);
			}
		} else {
			var row = new Element('dl');
			var cell = new Element('dd');
			cell.update('<br />등록된 민폴이 없습니다.');
			row.appendChild(cell);
			
			tDivObj.appendChild(row);
		}
	},
	
	
	//민폴 정보를 아이템값에 넣는다
	createMinpollItem: function(minpollInfo) {
		var item = new minPollItem();
		
		item.mpid	 		= parseInt(minpollInfo['@id'], 10);
		item.visibleDateBegin= this.convertStrToDate(minpollInfo['@visibleBegin']);
		item.visibleDateEnd = this.convertStrToDate(minpollInfo['@visibleEnd']);
		item.writedate		= minpollInfo['@writedate'];
		item.title 			= minpollInfo.title['#cdata'];
		item.content 		= minpollInfo.content['#cdata'];
		item.media			= minpollInfo.media['#cdata'];
		item.assentCnt		= parseInt(minpollInfo['@assentCnt'], 0);
		item.blackballCnt	= parseInt(minpollInfo['@blackballCnt'], 0);
		item.isActive 		= (item.visibleDateBegin <= this.today && this.today <= item.visibleDateEnd);
		item.isModified 	= false;
		
		return item;
	},
	
	createRow: function(item) {
		//찬성반대 퍼센트 계산
		var toCount = item.assentCnt + item.blackballCnt;
		if(toCount != 0){
			var assentPer = parseInt(item.assentCnt * 100 / toCount);
		}else{
			var assentPer = 50;
		}
		
		//찬성반대 넓이 계산(글자때문에 최소한의 공간을 확보해 준다)
		if(assentPer > 95){
			assentWidth = 95;
		}else if(assentPer < 5){
			assentWidth = 5;
		}else{
			assentWidth = assentPer;
		}
		
		var divCell = $('sPoll');
		var appCell = new Element('h3').appendChild(new Element('img', {src: this.contextPath+'/images/common/side_minpoll_h3.gif', alt: 'Minpoll'}));
		divCell.appendChild(appCell);
		appCell = new Element('a', {href: this.contextPath+'/hotissue/minpoll.jsp'});
		appCell.appendChild(new Element('img', {src: this.contextPath+'/images/common/btn_more.gif', alt: '더보기'}));
		appCell.addClassName('more');
		divCell.appendChild(appCell);
		
		var dlCell = new Element('dl');
		var dtCell = new Element('dt').appendChild(new Element('a', {href: this.contextPath+'/hotissue/minpoll.jsp?mpid='+item.mpid}).update(item.title));
		dlCell.appendChild(dtCell);
		
		var perCell = new Element('dd');

		widthValue = (100-assentWidth);
		var tmpCell = new Element('span');
		var tableCell  = "";
			tableCell += "<table cellspacing='2' cellpadding='0' border='0'>";
			tableCell += "  <tr> ";
			tableCell += "		<td id='pollYes' width='"+assentWidth+"%'>"+assentPer+"%</td>";
			tableCell += "		<td id='pollNo' width='"+widthValue+"'>"+(100 - assentPer)+"%</td>";
			tableCell += "	</tr> ";
			tableCell += "	<tr> ";
			tableCell += "		<td><img src='"+this.contextPath+"/images/common/side_poll_title_yes.gif' alt='찬성'></td> ";
			tableCell += "		<td align='right'><img src='"+this.contextPath+"/images/common/side_poll_title_no.gif' alt='반대'></td> ";
			tableCell += "	</tr> ";
			tableCell += "</table> ";
		tmpCell.innerHTML = tableCell;
		
		perCell.appendChild(tmpCell);
		dlCell.appendChild(perCell);
		divCell.appendChild(dlCell);
		
		//return divCell;
	},
	
	//위젯 정보를 가져온다
	widget: function() {
		new Ajax.Request(this.contextPath + '/servlet/index/widget', {
			method: 'get',
			parameters: 'action=randomWidget',
			onSuccess: function(transport) {
				var r = xml2json(transport.responseXML, '').evalJSON();
				if (r.result['@error'] == 'true') {
					alert(r.result.message['#cdata']);
					return;
				}
				HotTag.displayWidgetItem(r.result);
			}
		});
	},
	
	displayWidgetItem: function(result) {
		var tbodyObj = $('sWidget');
		tbodyObj.innerHTML = "";
		
		if (result.bannerInfo != null) {
			if (typeof(result.bannerInfo.size) != 'function')
				result.bannerInfo = [result.bannerInfo];
			
			for (var i = 0; i < result.bannerInfo.length; i++) {
				var bannerInfo = result.bannerInfo[i];
				var item = this.createWidgetItem(bannerInfo);
				this.items.push(item);
				item.widgetCount = result.widgetCount['@count'];				
				var rowObj = this.createWidgetRow(item);
				tbodyObj.appendChild(rowObj);
			}
		} else {
			var row = new Element('tr');
			var cell = new Element('td', {colspan: 6});
			cell.addClassName('emptyRow');
			cell.update('등록된 위젯이 없습니다.');
			row.appendChild(cell);
			
			tbodyObj.appendChild(row);
		}
	},
	
	createWidgetItem: function(widgetInfo) {
		var item = new widgetItem();
		
		item.wgid = parseInt(widgetInfo['@id'], 10);
		item.visibleDateBegin = this.convertStrToDate(widgetInfo['@visibleBegin']);
		item.visibleDateEnd = this.convertStrToDate(widgetInfo['@visibleEnd']);
		item.content = widgetInfo.content['#cdata'];
		item.title = widgetInfo.title['#cdata'];
		item.link = widgetInfo.link['#cdata'];
		item.isLinkNewWin = widgetInfo.link['@linkNewWindow'] == 'true';
		item.media = widgetInfo.media['#cdata'];
		item.isActive = (item.visibleDateBegin <= this.today && this.today <= item.visibleDateEnd);
		item.isModified = false;
		
		return item;
	},
	
	createWidgetRow: function(item) {
		var divCell = new Element('fieldset');
		var pCell = new Element('p');
		if(item.isLinkNewWin){
			var imgCell = new Element('a', {'href': item.link, 'target': '_blank'});
			imgCell.appendChild(new Element('img', {'src': this.contextPath+'/image/view/index/widget/'+item.media, "alt": item.title}));
			pCell.appendChild(imgCell);
		}else{
			var imgCell = new Element('a', {href: item.link});
			imgCell.appendChild(new Element('img', {'src': this.contextPath+'/image/view/index/widget/'+item.media, 'alt': item.title}));
			pCell.appendChild(imgCell);
		}
		
		divCell.appendChild(pCell);
		
		if(item.widgetCount > 1){
			var appCell = new Element('a', {href: this.contextPath+'/hotissue/widget.jsp'});
			appCell.appendChild(new Element('img', {src: this.contextPath+'/images/common/btn_more.gif', 'alt': '더보기'}));
			appCell.addClassName('more');
			divCell.appendChild(appCell);
		}		
		return divCell;
	},
	
	chkMessageBoxinTag: function(tagword) {
		//var chkTag = tagword.value.indexOf(this.wrTag);
		//if(chkTag == -1){
		//	alert('태그를 삭제하시면 안됩니다.');
		//	tagword.value = this.wrTag;
		//	$('restLength').innerHTML = 140 - $('messageBox').value.length;
		//}
	}, 
	
	//리스트를 보여주고 나서 다시 태그를 메세지 박스에 넣어준다
	reMessageBoxinTag: function(){
		//$('messageBox').value = this.wrTag;
		$('restLength').innerHTML = 140;// - $('messageBox').value.length;
		$('messageBox').focus();
	}

};
//]]>