var QUESTSELECTFLAG = false;
var QRELOADREMAINTIME = 4;
var SRELOADREMAINTIME = 4;
var FILEPAGENUM = 0;
var TOTALPAGENUM = 0;
var PERPAGENUM = 20;
var LOADING = false;
var ANSWERMODE = false;
var QuestList = {
	setReplyMode : function (event)
	{
		if( !QUESTSELECTFLAG )
		{
			srcEl = getSrcElement(event);
			var qid = srcEl.getAttribute("qid");	
			if( qid != null && qid != "")
			{
				ANSWERMODE = true;
				var date = new Date();
				var rid = date.getTime();
				document.frmQuestInfo.action = "/answer/selectQuest";
				document.frmQuestInfo.method = "get";
				document.frmQuestInfo.inputQid.value = qid; 
				document.frmQuestInfo.target = "_self";
				QUESTSELECTFLAG = true; 
				document.frmQuestInfo.submit();
				showLoadingMsg();
			}	
		}
	},
	
	setSelectMode : function (event)
	{
		if( checkLowLevelSelect() )
			return;

		srcEl = getSrcElement(event);
		var qid = srcEl.getAttribute("qid");
		if( qid != null && qid != "")
		{
			ANSWERMODE = true;
			document.frmQuestInfo.action = "/answer/selectMode";
			document.frmQuestInfo.method = "post";
			document.frmQuestInfo.target = "_self";
			document.frmQuestInfo.inputQid.value = qid; 
			document.frmQuestInfo.submit();
			showLoadingMsg();
		}	
	}, 
	
	loadBeforeQuestList : function()
	{
		if( FILEPAGENUM == 0 )
			FILEPAGENUM = 0;
		else
			FILEPAGENUM--;
		setQuestListPageNumArea();
		QuestList.loadQuestList();	
	}, 
	
	loadNextQuestList : function()
	{
		if( TOTALPAGENUM == FILEPAGENUM )
			FILEPAGENUM = 0;
		else
			FILEPAGENUM ++;
		setQuestListPageNumArea();
		QuestList.loadQuestList();
	}, 
	
	loadNowQuestList : function(index)
	{
		FILEPAGENUM = index;
		setQuestListPageNumArea();
		QuestList.loadQuestList();
	},
	
	loadQuestList : function()
	{
		var url = "/answer/reloadQuest?page=" + FILEPAGENUM;
		var myAjax = new Ajax.Request( 
					url, 
					{
						method: 'get', 
						asynchronous: true,
						onComplete: function(xmlHttp)
						{
							QuestList.getResult(xmlHttp);
						},
						onFailure: function()
						{
						}
					}
					);
	}, 

	getResult : function (xmlHttp)
	{
		if( 200 == xmlHttp.status )
		{
			try{
				var doc = xmlHttp.responseXML.documentElement;
				TOTALPAGENUM = Math.floor(doc.getAttribute("totalCount")/PERPAGENUM);
				var divTop = document.createElement("div");
				var divMain = $("Qlist");	
				divTop.className = "questListTop";
 				if( doc.childNodes.length == 0 )
				{
					var txtNode = document.createTextNode("질문이 없습니다.");
					divTop.appendChild(txtNode);
				}			
				else
				{
					for( i=0; i< doc.childNodes.length; i++)
					{
						var quest = doc.getElementsByTagName("quest").item(i);
						var divSub = document.createElement("div");
						var spanCdata = document.createElement("span");
						var cdate = "";
						var cdata = "";
						var protect = "";
						var kcode = "";
						
						
						spanCdata.onmouseover = setFontClick;
						spanCdata.onmouseout = setFontNormal;
						spanCdata.onclick = QuestList.setReplyMode;
						
						for(j=quest.childNodes.length-1; j>=0; j--)
						{
							if( quest.childNodes[j].tagName == "delay" )
							{
								cdate = QuestList.getQstTime(quest.childNodes[j].firstChild.nodeValue);
							}
							if( quest.childNodes[j].tagName == "cdata")
							{
								cdata = quest.childNodes[j].firstChild.nodeValue;
							}
							if( quest.childNodes[j].tagName == "kcode")
							{
								kcode = quest.childNodes[j].firstChild.nodeValue;
								
								if (kcode != quest.childNodes[j].firstChild.nodeValue.toUpperCase())
									kcode = kcode + "1";	 																										  
							}
							if( quest.childNodes[j].tagName == "protect")
							{
								protect = quest.childNodes[j].firstChild.nodeValue;
							}
							else
							{
								spanCdata.setAttribute(quest.childNodes[j].tagName, quest.childNodes[j].firstChild.nodeValue);
							}
						}						
						
						// delay, icon, cdata 순서
						var spanIcon = document.createElement("span");
						var spanDelay = document.createElement("span");
						var txtDelay = document.createTextNode(cdate);
						
						spanDelay.className = "spanDelay";
						spanDelay.appendChild(txtDelay);
						divSub.appendChild(spanDelay);	// 1. delay insert

						spanIcon.className = "icon iconA icon" + kcode;	// icon code						
						divSub.appendChild(spanIcon);	// 2. icon insert

						var txtCdata = document.createTextNode(cdata);
						spanCdata.appendChild(txtCdata);	// 3. cdata insert
						divSub.appendChild(spanCdata);
						
						var spanProtect = document.createElement("span");
						spanProtect.className = "spanProtect";
						var txtprotect = document.createTextNode(getProtectMsg(protect));
						spanProtect.appendChild(txtprotect);
						divSub.appendChild(spanProtect);
						
						divTop.appendChild(divSub);
					}
				}
				
				clearChildAll(divMain);
				divMain.appendChild(divTop);
			}catch(e){		
			}
		}
	}, 
	
	loadSelectList : function()
	{
		var url = "/answer/xml/slist.xml";
		var myAjax = new Ajax.Request( 
					url, 
					{
						method: 'get', 
						asynchronous: true,
						onComplete: function(xmlHttp)
						{
							QuestList.getSlistResult(xmlHttp);
						},
						onFailure: function()
						{
						}
					}
					);
	}, 

	getSlistResult : function (xmlHttp)
	{
		if( 200 == xmlHttp.status )
		{
			try{
				var doc = xmlHttp.responseXML.documentElement;
				var divTop = document.createElement("div");
				var divMain = $("Slist");				
				
				divTop.className = "questListTop";
			
				if( doc.childNodes.length == 0 )
				{
					var txtNode = document.createTextNode("질문이 없습니다.");
					divTop.appendChild(txtNode);
				}			
				else
				{
					for( i=0; i< doc.childNodes.length; i++)
					{
						var quest = doc.getElementsByTagName("quest").item(i);
						var divSub = document.createElement("div");
						var spanCdata = document.createElement("span");
						var cdate = "";
						var cdata = "";
						
						
						spanCdata.onmouseover = setFontClick;
						spanCdata.onmouseout = setFontNormal;
						spanCdata.onclick = QuestList.setSelectMode;
						
						for(j=quest.childNodes.length-1; j>=0; j--)
						{
							if( quest.childNodes[j].tagName == "delay" )
							{
								cdate = QuestList.getQstTime(quest.childNodes[j].firstChild.nodeValue);
							}
							if( quest.childNodes[j].tagName == "cdata")
							{
								cdata = quest.childNodes[j].firstChild.nodeValue;
							}
							else
							{
								spanCdata.setAttribute(quest.childNodes[j].tagName, quest.childNodes[j].firstChild.nodeValue);
							}
						}
						// delay, icon, cdata 순서
						var spanIcon = document.createElement("span");
						var spanDelay = document.createElement("span");
						var txtDelay = document.createTextNode(cdate);
						
						spanDelay.className = "spanDelay";
						spanDelay.appendChild(txtDelay);
						divSub.appendChild(spanDelay);	// 1. delay insert
						
						spanIcon.className = "icon";						
						divSub.appendChild(spanIcon);	// 2. icon insert

						var txtCdata = document.createTextNode(cdata);
						spanCdata.appendChild(txtCdata);
						divSub.appendChild(spanCdata);	// 3. cdata insert
						
						divTop.appendChild(divSub);
					}
				}
				
				clearChildAll(divMain);
				divMain.appendChild(divTop);
			}catch(e){		
			}
		}
	}, 
	
	getQstTime : function (str)
	{
		var strTime = str.substring(0,2);
	
		if( strTime.substring(0, 1) == "0" )
			strTime = strTime.substring(1);
		
		return "(" + str + ")";
	}/*,
	
	checkLoading : function()
	{
        if( !LOADING )
		{
			return;
		}
		else if( event.clientY > 0 )
		{
			return;
		}
		else
		{
			ANSWERMODE = false;
			LOADING = false;
		}
			
		var url = "/answer/resetQstStatus?qid=" + document.frmQuestInfo.inputQid.value;
		var myAjax = new Ajax.Request( 
					url, 
					{
						method: 'get', 
						asynchronous: true,
						onComplete: function(xmlHttp)
						{
						},
						onFailure: function()
						{
						}
					}
					);
	}	
	
	*/ 
}

function banReload(){
 
 	if( LOADING )
 	{
		if (event.keyCode  == 8 || event.keyCode  ==116 ) 
		{
			event.keyCode=0;
			event.cancelBubble=true;
			event.returnValue=false;
			return false;	
		}		
	}
}

new PeriodicalExecuter(function(pe) {

	if( UID == "" || UID == null )
		return;
		
	$("spanQRemainTime").update(QRELOADREMAINTIME + "초후 ");
	$("spanSRemainTime").update(SRELOADREMAINTIME + "초후 ");

	if( $("reloadOption").checked )
	{
		if( QRELOADREMAINTIME == 0 )
		{ 
			QuestList.loadQuestList();
			QRELOADREMAINTIME = 4;
		}
		else
			QRELOADREMAINTIME--;
	}
	else
	{
		QRELOADREMAINTIME = 4; 	
	}
	
	if( $("reloadOptionSelect").checked )
	{
		if( SRELOADREMAINTIME == 0 )
		{ 
			QuestList.loadSelectList();
			SRELOADREMAINTIME = 4;
		}
		else
			SRELOADREMAINTIME--;
	}
	else
	{
		$("spanSRemainTime").style.display = "none";
		SRELOADREMAINTIME = 4; 	
	}
}, 1);


var UID = "";
var LEVEL = "";
function initListPage(uid, level, totalcount)
{
	if( uid == null || uid == "" )
	{
		UID = "";
		$("spanQRemainTime").style.display = "none";
		$("spanSRemainTime").style.display = "none";
	}
	else
	{
		UID = uid;
		LEVEL = level;
		
		if( getCookie("reloadquest") == "no" )
		{
			$("spanQRemainTime").style.display = "none";
			$("reloadOption").checked = false;
		}
		else
		{
			$("spanQRemainTime").style.display = "inline";
			$("reloadOption").checked = true;
		}

		if( getCookie("reloadquestselect") == "no" )
		{
			$("spanSRemainTime").style.display = "none";
			$("reloadOptionSelect").checked = false;
		}
		else
		{
			$("spanSRemainTime").style.display = "inline";
			$("reloadOptionSelect").checked = true;
		}
	}
	TOTALPAGENUM = Math.floor(totalcount/PERPAGENUM);
	setQuestListPageNumArea();
}

function setQuestListPageNumArea()
{
	var obj = $("divQuestListPageNumberArea");
	var str = "<span style='cursor:pointer' onclick='QuestList.loadBeforeQuestList()'>이전 </span>";
	
	for( index=0; index<=TOTALPAGENUM; index++)
	{
		if( FILEPAGENUM == (index) )
			str += "<span onclick='QuestList.loadNowQuestList("+index+")' style='cursor:pointer;font-weight:bold'>"+(index+1)+"</span> ";
		else
			str += "<span onclick='QuestList.loadNowQuestList("+index+")' style='cursor:pointer'>"+(index+1)+"</span> ";
	}
	str += "<span style='cursor:pointer' onclick='QuestList.loadNextQuestList()'>다음</span>";
	obj.update(str);
}

function showLoadingMsg()
{
	LOADING = true;
	var ran = Math.round(Math.random() * 10, 0);
	var ran = ran%3;
	$("divLoadingMsg").style.backgroundImage = "url('/answer/res/loading1.gif')";
	$("divLoadingMsg").style.display = "block";
}

function checkLowLevel()
{
	if( parseInt(LEVEL) <= 10 )
	{
		alert("전문지식맨 만 답변 할 수 있습니다.");
		return true;
	}
	else
		return false;
}
function checkLowLevelSelect()
{
	if( parseInt(LEVEL) <= 10 )
	{
		alert("전문지식맨 만 검증 할 수 있습니다.");
		return true;
	}
	else
		return false;
}

function setReloadOption()
{
	if( $("reloadOption").checked )
	{
		$("spanQRemainTime").style.display = "inline";
		setCookie("reloadquest", "yes", 10);
	}
	else
	{
		$("spanQRemainTime").style.display = "none";
		setCookie("reloadquest", "no", 10);
	}
}

function setReloadOptionSelect()
{
	if( $("reloadOptionSelect").checked )
	{
		$("spanSRemainTime").style.display = "inline";
		setCookie("reloadquestselect", "yes", 10);
	}
	else
	{
		$("spanSRemainTime").style.display = "none";
		setCookie("reloadquestselect", "no", 10);
	}
}

function getCookie( cookieName )
 {
  var search = cookieName + "=";
  var cookie = document.cookie;

  // 현재 쿠키가 존재할 경우
  if( cookie.length > 0 )
  {
   // 해당 쿠키명이 존재하는지 검색한 후 존재하면 위치를 리턴.
   startIndex = cookie.indexOf( cookieName );

   // 만약 존재한다면
   if( startIndex != -1 )
   {
    // 값을 얻어내기 위해 시작 인덱스 조절
    startIndex += cookieName.length;

    // 값을 얻어내기 위해 종료 인덱스 추출
    endIndex = cookie.indexOf( ";", startIndex );

    // 만약 종료 인덱스를 못찾게 되면 쿠키 전체길이로 설정
    if( endIndex == -1) endIndex = cookie.length;

    // 쿠키값을 추출하여 리턴
    return unescape( cookie.substring( startIndex + 1, endIndex ) );
   }
   else
   {
    // 쿠키 내에 해당 쿠키가 존재하지 않을 경우
    return false;
   }
  }
  else
  {
   // 쿠키 자체가 없을 경우
   return false;
  }
 }
 function setCookie( cookieName, cookieValue, expireDate )
 {
  var today = new Date();
  today.setDate( today.getDate() + parseInt( expireDate ) );
  document.cookie = cookieName + "=" + escape( cookieValue ) + "; path=/; expires=" + today.toGMTString() + ";";
 }

function toggleChat(type) {	
	if(type == '1') {
		setCookie("chatHide", "yes", 10);
		document.location.reload();
		//$("chatMsg1").hide();
		//$("chatMsg2").show();
	}
	else {
		setCookie("chatHide", "no", 10);
		document.location.reload();
	}
}
function getProtectMsg(msg)
{
	if( msg == "" || msg == null )
		return "";
	if( msg == "YES" )
		return "  [답변보호가능]";
	return "";
}

