var searchSkinAdver = null; // 스킨 광고 관련 추가
// Copyright 2000 . All rights reserved.
var searchKeyword = null;	// dynamic include
var oSearch = Class.create();
oSearch.prototype = {
	_oDiv : null,
	_imgPath : null,
	oHtml : null,
	_keyword : null,
	_jsonTryCnt : 0,
	inputAdver : null,
	searchLink : null,
	akc_orgquery: "",// 자동 완성
	akc_yn: null,// 자동 완성
	akc_pointerNum: -1,// 자동 완성
	akcJson: null,// 자동 완성
	popup : false, // 팝업 공지 여부 확인 변수

	reqSkinAdver : 0,	// 스킨 광고 요청 회수(재요청시 요청에 대한 응답 디텍트 회수)

	initialize : function() {},
	set : function() {
		if (arguments[0]) {
			this.popup = true;
		}
		this.akc_yn = (oCookie.get("akcYN") == "y" || !oCookie.get("akcYN") ? "y" : null);
		this.akcJson = {"QUERY":"", "LIST":""};

		this.inputAdver = false;
		var strURL = location.search.toQueryParams();
		this._keyword = strURL['query'] || "";
		this._keyword = this._keyword.replace(/\+/, ' ');

		this.searchLink = variable.getChild('searchHost').toString();
		this._oDiv = $('searchDiv');
		this._imgPath = variable.getChild('defaultImg').toString();

		// 자동 완성
		this.ack_yn = chInfoJson.ack_yn;

		this.akcNoUse = new pandora.util.StringBuffer();
		this.akcNoUse.append('<table width="100%" border="0" cellspacing="0" cellpadding="0" style="background-color: #FFFFFF; border:1px solid #CCCCCC;">');
		this.akcNoUse.append('<tr>');
		this.akcNoUse.append('	<td style="padding: 2px 0px 0px; color: #999999;" height="40" align="center" valign="middle">검색어 자동완성 기능을 사용해 보세요.<br/>검색어 입력이 보다 편리해 집니다.<strong></td>');
		this.akcNoUse.append('</tr>');
		this.akcNoUse.append('<tr>');
		this.akcNoUse.append('	<td height="1" bgcolor="d8d8d8"></td>');
		this.akcNoUse.append('</tr>');
		this.akcNoUse.append('<tr>');
		this.akcNoUse.append('	<td bgcolor="f2f2f2">');
		this.akcNoUse.append('	<table width="100%" cellspacing="5" cellpadding="0" border="0">');
		this.akcNoUse.append('		<td style="padding: 2px 0px 0px;"><strong>검색어 자동완성</strong> </td>');
		this.akcNoUse.append('		<td align="right"><a style="font-size: 12px; color: #333333;" id="akcUse" onfocus="this.blur();" onclick="oSearch.akc_setCookie(\'y\');">사용하기</a> </td>');
		this.akcNoUse.append('	</tr>');
		this.akcNoUse.append('	</table>');
		this.akcNoUse.append('	</td>');
		this.akcNoUse.append('</tr>');
		this.akcNoUse.append('</table>');

		this.akcUse = new pandora.util.StringBuffer();
		this.akcUse.append('<table width="100%" border="0" cellspacing="0" cellpadding="0" style="background-color: #FFFFFF; border:1px solid #CCCCCC;">');
		this.akcUse.append('<tr>');
		this.akcUse.append('	<td style="padding: 2px 0px 0px; color: #999999;" height="40" align="center" valign="middle">현재 자동 완성 기능을 사용하고 계십니다.</td>');
		this.akcUse.append('</tr>');
		this.akcUse.append('<tr>');
		this.akcUse.append('	<td height="1" bgcolor="d8d8d8"></td>');
		this.akcUse.append('</tr>');
		this.akcUse.append('<tr>');
		this.akcUse.append('	<td bgcolor="f2f2f2">');
		this.akcUse.append('	<table width="100%" cellspacing="5" cellpadding="0" border="0">');
		this.akcUse.append('		<td style="padding: 2px 0px 0px;"><strong>검색어 자동완성</strong> </td>');
		this.akcUse.append('		<td align="right"><a style="font-size: 12px; color: #333333;" id="akcUse" onfocus="this.blur();" onclick="oSearch.akc_setCookie(\'n\');">사용안함</a> </td>');
		this.akcUse.append('	</tr>');
		this.akcUse.append('	</table>');
		this.akcUse.append('	</td>');
		this.akcUse.append('</tr>');
		this.akcUse.append('</table>');

		this.akcList = new pandora.util.StringBuffer();
		this.akcList.append('<table width="100%" border="0" cellspacing="0" cellpadding="0" style="background-color: #FFFFFF; border:1px solid #CCCCCC;">');
		this.akcList.append('<tr>');
		this.akcList.append('	<td>');
		this.akcList.append('	<DIV id=AKCIDiv style="OVERFLOW-Y: auto; OVERFLOW-X: hidden; WIDTH: 100%; display:inline" name="AKCIDiv"></DIV>');
		this.akcList.append('	</td>');
		this.akcList.append('</tr>');
		this.akcList.append('<tr>');
		this.akcList.append('	<td height="1" bgcolor="d8d8d8"></td>');
		this.akcList.append('</tr>');
		this.akcList.append('<tr>');
		this.akcList.append('	<td bgcolor="f2f2f2">');
		this.akcList.append('	<table width="100%" cellspacing="5" cellpadding="0" border="0">');
		this.akcList.append('		<td style="padding: 2px 0px 0px;"><strong>검색어 자동완성</strong> </td>');
		this.akcList.append('		<td align="right"><a style="font-size: 12px; color: #333333;" id="akcUse" onfocus="this.blur();" onclick="oSearch.akc_setCookie(\'n\');">사용안함</a> </td>');
		this.akcList.append('	</tr>');
		this.akcList.append('	</table>');
		this.akcList.append('	</td>');
		this.akcList.append('</tr>');
		this.akcList.append('</table>');

		this.storage = cStorageMgr.getInstance();

		this.viewSearch();
	},

	viewSearch : function () {
		var popularText = "";
		var searchText = "";
		var tabText = [];
		var radioText = [];

		switch (chInfoJson['clientLang']) {
			case "gb" :
				searchText = "Search";
				popularText = "Hot Search";
				tabText = {program:"Videos", channel:"Channels", allS:"All", kOnly:"Korea"};
					radioText = {"ko":"Korean", "en":"English", "gb":"English", "jp":"Japan", "cn":"China"};
				break;
			case "ko" :
				searchText = "검색";
				popularText = "인기검색";
				tabText = {program:"프로그램", channel:"채널", allS:"전체", kOnly:"한국만"};
					radioText = {"ko":"한국어", "en":"영어", "gb":"영어", "jp":"일본어", "cn":"중국어"};
				break;
			case "en" :
				searchText = "Search";
				popularText = "Hot Search";
				tabText = {program:"Videos", channel:"Channel", allS:"All", kOnly:"Korean"};
					radioText = {"ko":"Korean",  "en":"영어","gb":"English", "jp":"Japan", "cn":"China"};
				break;
			case "cn" :
				searchText = "搜索";
				popularText = "人気検索";
				tabText = {program:"视频", channel:"频道", allS:"全部", kOnly:"中文"};
					radioText = {"ko":"韩国语", "en":"英语", "gb":"英语", "jp":"日语", "cn":"中文"};
				break;
			case "jp" :
				searchText = "検索";
				popularText = "热门搜索";
				tabText = {program:"動画", channel:"チャンネル", allS:"全体", kOnly:"日本語"};
					radioText = {"ko":"韓国語", "en":"英語", "gb":"英語", "jp":"日本語", "cn":"中国語"};
				break;
		}

		if (chInfoJson['tab'] == "program" || chInfoJson['tab'] == undefined || !chInfoJson['tab']) {
			var sTab1Bold = "bold";
			var sTab2Bold = "";
		} else {
			var sTab1Bold = "";
			var sTab2Bold = "bold";
		}

		if ((chInfoJson['langsort'] == "" || chInfoJson['langsort'] == "all") || chInfoJson["currMenu"] != "PSEARCH") {
			var langsort1 = " checked";
			var langsort2 = "";
		} else {
			var langsort1 = "";
			var langsort2 = " checked";
		}

		this.oHtml = new pandora.util.StringBuffer();
		this.oHtml.append('<div class="vsearch_left"></div>');
		this.oHtml.append('<div class="vsearch_logo" id="sBarLeft">');
		if (oCookie.get("clientLang") == "ko" || chInfoJson["clientLang"] == "ko") {
			// 광고 영역으로 활용 : smith - 2008-12-04
//			this.oHtml.append('<a href="http://event.pandora.tv/?eventMode=unicef-kr" target="_blank" onfocus="javascript:this.blur();"><img src="http://imgcdn.pandora.tv/ptv_img/search/banner_v.gif" border="0"></a>');
			// 광고 영역으로 활용 : smith - 20081125 -> 27일 링크 변경
			//this.oHtml.append('<a href="http://blog.pandora.tv/kor/42" target="_blank" onfocus="javascript:this.blur();"><img src="http://imgcdn.pandora.tv/pan_img/event/banner/081125_2.gif" width="161" height="44" border="0"></a>');
			// 광고 영역으로 활용 : alan - 20080822
			//this.oHtml.append('<a href="http://event.pandora.tv/?eventMode=2008dokdo" target="_blank" onfocus="javascript:this.blur();"><img src="http://imgcdn.pandora.tv/gimg/banner/banner_dokdo.gif" width="161" height="44" border="0"></a>');
		}
		this.oHtml.append('</div>');
		this.oHtml.append('<div class="search popular">');
		this.oHtml.append('<form id="searchFrm" method="get" style="margin:0px;" onsubmit="javascript:return false;">');
		this.oHtml.append('<input type="hidden" name="tab" id="tab" value="' + ((chInfoJson['tab'] != "channel") ? "program" : "channel") +'">');
		this.oHtml.append('<div style="width:400px;">');
		//this.oHtml.append('<div style="float:right"><input name="tab" type="radio" value="program"'+tabProgram+'>'+tabText['program']+' &nbsp;<input name="tab" type="radio" value="channel"'+tabChannel+'>'+tabText['channel']+'</div>');
		this.oHtml.append('<div style="float:right;display:none;"><input name="langsort" id="langsortAll" type="radio" '+langsort1+' value="">' + tabText['allS'] + ' &nbsp;<input name="langsort" id="langsort" type="radio" value="' + oCookie.get("browserLang") + '" '+langsort2+'>' + radioText[oCookie.get("browserLang")] + '</div>');
		this.oHtml.append('<div style="padding-top:4px;"><a id="sTab1" class="'+sTab1Bold+'">'+tabText['program']+'</a> &nbsp;l&nbsp; <a id="sTab2" class="'+sTab2Bold+'">'+tabText['channel']+'</a></div>');
		this.oHtml.append('</div>');
		this.oHtml.append('<table border="0" cellspacing="0" cellpadding="0" style="margin-top:1px;"><tr><td id="akcArea">');
		this.oHtml.append('<div style="position:relative">');

		this.oHtml.append('<div><input name="query" id="query" type="text" accesskey="s" class="s_input" value="'+this._keyword+'" autocomplete="off"></div>');

		if (oCookie.get("clientLang") == "ko" || chInfoJson["clientLang"] == "ko") {
			// 자동 완성 화살표
			this.oHtml.append('<div style="POSITION:absolute; width: 9px; right:7px; top:10px; z-index:500;" id="AKCArrow"><IMG id="AKCArrowImg" style="CURSOR: pointer;" onfocus=this.blur() src="http://imgcdn.pandora.tv/ptv_img/search/icon_org_down.gif"></div>');

			// 자동 완성 레이어
			this.oHtml.append('<DIV ID="AKCResult" style="display:none;position:absolute; left:1px; top:24px; z-index:999; width:100%"></DIV>');
		}

		this.oHtml.append('</div></td><td><input id="searchBtn" type="button" class="vsearch_btn" value="' + searchText + '">');
		this.oHtml.append('</td></tr></table>');
		this.oHtml.append('</form>');

		this.oHtml.append('</div>');
		this.oHtml.append('<div class="vsearch_right"></div>');
		this.oHtml.append('<div style="float:right; margin-top:6px;" id="sTopAdverId"></div>');

		this._oDiv.update(this.oHtml.toString());
		try {
			$("logoDiv").up().style.zIndex = "10";
		} catch(e) {}

		this._oDiv.style.zIndex = "10";

		/* -- 인기 검색어 관련 start updated by ryan.lee 080613 -- */
		if (chInfoJson["currMenu"] == "PSEARCH" && chInfoJson["clientLang"] == "ko") {
			// 인기 검색어 관련
			//var obj = Object.toJSON({"userid":oCookie.get("glb_mem[userid]")});
			new Ajax.Request( "/data/keyword/keyword_40001.js" , {
				method : 'post',
				onSuccess	: function (res) {
					this.displayKeyword(res.responseText.evalJSON());
				}.bind(this),
				onFailure	: function() {}
			});
		}

		Event.observe("query", "keydown", this.formSubmit.bind(this));
		Event.observe("query", "keyup", this.formSubmit.bind(this));
//		Event.observe("query", "keypress", this.formSubmit.bind(this));
		Event.observe("query", "click", this.formSubmit.bind(this));

		Event.observe("searchBtn", "click", this.formSubmit.bind(this));

		if (chInfoJson["currMenu"] == "PSEARCH") {
			Event.observe("sTab1", "click", this.formSubmit.bind(this));
			Event.observe("sTab2", "click", this.formSubmit.bind(this));
		} else {
			Event.observe("sTab1", "click", this.changeSelect.bind(this));
			Event.observe("sTab2", "click", this.changeSelect.bind(this));
		}

		// 자동 완성 화살표 이벤트
		if (oCookie.get("clientLang") == "ko" || chInfoJson["clientLang"] == "ko") {
			Event.observe("AKCArrow", "click", this.arrowClick.bind(this));
		}
/*
		Event.observe("sTopAdver", "load", function() {
			adverView("sTopAdver");
		});
*/
		switch(true) {
			case (chInfoJson["currMenu"] == "SIGNUP") : break;	// 로그인 페이지
			case (chInfoJson["currMenu"] == "index" && oCookie.get("popCupi") != "1" && oCookie.get("browserLang") == "ko" && oCookie.get("glb_mem[userid]") != null && oCookie.get("glb_mem[userid]").length > 0  && oCookie.get("glb_mem[userid]") != "") :
				break;	// 팝업 띄울때
			case (chInfoJson["prgid"] != "" && chInfoJson["prgid"] > 0) :	break;	// 카테고리 랭킹 페이지
			case (location.href.substr(location.href.length-14, 14) == "pandora.tv/?r1") : break;	// 메인페이지 reflash
			case (this.popup == true) : break; // 팝업 공지가 있을때 포커스 안가게 작업 하는 거 oSearch.set('1') 이런식으로 호출 하면 됨
			default : Event.observe(window, "load", function(){if(chInfoJson["currMenu"] == 'index') $("query").focus();} );
		}
/*
		if (chInfoJson["currMenu"] != "SIGNUP" && !chInfoJson["prgid"]) {
			Event.observe(window, "load", function() {
				$("query").focus();
			});
		}
*/

		// 광고 스크립트 동적 호출
		if (oCookie.get("clientLang") == "ko" || chInfoJson["clientLang"] == "ko") {

			if(this._keyword == ""){
				var oScript = document.createElement("SCRIPT");
				with(oScript) {
					setAttribute("type", "text/javascript");
					setAttribute("language", "javascript");
					setAttribute("charset", "utf-8");
					setAttribute("src", variable.getChild('mainHost')+"adver.ptv?mode=skeyword&type=loadjs");
				}
				document.getElementsByTagName('head')[0].appendChild(oScript);
			}
		}

		if (searchSkinAdver == undefined || searchSkinAdver == null) {
			$("sTopAdverId").innerHTML = '<iframe src="'+variable.getChild('mainHost')+'adver.ptv?mode=sTop" id="sTopAdver" name="sTopAdver" topmargin="0" leftmargin="0" marginwidth="0" marginheight="0" frameborder="0" scrolling="no" width="170" height="60" allowTransparency="true" style="display:"></iframe>';
			if (chInfoJson["clientLang"] == "ko"||chInfoJson["clientLang"] == "jp") {
				Event.observe(window, "load", this.searchbarLeftAdver.bind(this));
			}
		} else {
			this.skinChange();
		}
	},

	searchbarLeftAdver : function() {
		$("sBarLeft").update('<iframe src="'+variable.getChild('mainHost')+'adver.ptv?mode=sBarLeft" topmargin="0" leftmargin="0" marginwidth="0" marginheight="0" frameborder="0" scrolling="no" width="161" height="44" allowTransparency="true" style="display:"></iframe>');
	},

	skinChange : function() {
		with (this._oDiv.style) {
			position='relative';
			width='974px';
			height='77px';
			margin='auto';
			background='url(\''+searchSkinAdver.skinImg+'\') no-repeat';
		}

		with (this._oDiv.down().style) {
			background='url(\'http://imgcdn.pandora.tv/static/blank.gif\') 0px -101px no-repeat';
			styleFloat = 'left';
			width = '21px';
			height = '77px';
			display = 'block';
		}
		this._oDiv.down().clsaaName = "";

		with (this._oDiv.down().next(0).style) {
			background='url(\'http://imgcdn.pandora.tv/static/blank.gif\') 0px -57px no-repeat';
			styleFloat='left';
			width='161px';
			height='44px';
			display='block';
			marginTop='18px';
			marginLeft='15px';
		}
		this._oDiv.down().next(0).clsaaName = "";

		this._oDiv.down().next(0).innerHTML = "<a href=\"" + searchSkinAdver.link + "\" onfocus=\"this.blur()\" " + (searchSkinAdver.target ? "target=\""+searchSkinAdver.target+"\"" : "") + "><img src=\"http://imgcdn.pandora.tv/static/blank.gif\" width=\"161\" height=\"44\" border=\"0\" alt=\"\" /></a>";

		with (this._oDiv.down().next(1).style) {
			styleFloat = 'left';
			marginTop  ='8px';
			fontColor = searchSkinAdver['color'].toString();
			color = searchSkinAdver['color'].toString();
			textDecoration = 'none';
		}

		this._oDiv.down().next(1).clsaaName = "";

		$("sTab1").className = "";
		with ($("sTab1").style) {
			fontColor=searchSkinAdver.color.toString();
			color=searchSkinAdver.color.toString();
			textDecoration="none";
		}

		with ($("sTab2").style) {
			fontColor=searchSkinAdver.color.toString();
			color=searchSkinAdver.color.toString();
			textDecoration="none";
		}

		with ($("query").style) {
			width='400px';
			fontSize='16px';
			fontWeight='bold';
			background=searchSkinAdver['bgcolor'].toString();
		}

		$("searchBtn").className = "";
		with ($("searchBtn").style) {
			height='25px';
			background='url(\''+searchSkinAdver['btnImg'].toString()+'\') repeat';
			fontWeight='bold';
			fontSize='14px';
			marginLeft='3px';
			border='1px solid ' + searchSkinAdver['inputColor'].toString();
		}

		with (this._oDiv.down().next(2).style) {
			background='url(\'http://imgcdn.pandora.tv/static/blank.gif\') -21px -101px no-repeat';
			styleFloat = 'right';
			width = '21px';
			height='77px';
			display = 'block';
		}
		this._oDiv.down().next(2).clsaaName = "";

		with ($("sTopAdverId").style) {
			marginTop="0";
		}
		$("sTopAdverId").innerHTML = "<a href=\"" + searchSkinAdver.link + "\" onfocus=\"this.blur()\" " + (searchSkinAdver.target ? "target=\""+searchSkinAdver.target+"\"" : "") + "><img src=\"http://imgcdn.pandora.tv/static/blank.gif\" width=\"255\" height=\"70\" border=\"0\" alt=\"\" /></a>";

		setTimeout(function(){this.reloadSkinAdver();}.bind(this), 1000*60*3);
	},

	reloadSkinAdver : function() {
		if(this.reqSkinAdver == 0) {
			//this._oDiv.style.background = "";
			searchSkinAdver = null;	// 스킨 광고 정보 초기화
			this.reqSkinAdver = 1;
			$('advScript').src = $('advScript').src;
			setTimeout(function(){this.reloadSkinAdver()}.bind(this), 100);
		} else {
			this.reqSkinAdver++;	// detect 회수 증가
			if(searchSkinAdver != null) {	// 스킨 광고 정보가 갱신 되었으면...
				this.reqSkinAdver = 0;	// detect 회수 초기화
				this.skinChange();	// 스킨 광고 변경
			} else {
				if(this.reqSkinAdver > 20) {	// detect 회수가 일정 회수를 초과 하면
					this.reqSkinAdver = 0;	// 초기화 하고 끝...
					this.reloadSkinAdver();	// 다시 재요청
				} else {
					setTimeout(function(){this.reloadSkinAdver()}.bind(this), 100);	// 스킨 광고 정보 detect
				}
			}
		}
	},

	getJSON : function() {
		//var dummy = new Date().getTime().toString();
		var url = "/main_json/keyword_" + chInfoJson.langCode + ".js";
		new Ajax.Request(url, {
			method : 'get',
			onSuccess : function(res){
				this.displayKeyword(res.responseText.evalJSON());
			}.bind(this),

			onFailure : function() {}
		});
	},

	ranArray : function (ranArr) {
		var loopNum = ranArr.length;
		var randNum = 0;
		for(var i=0 ; i < loopNum ; i++){
			randNum = Math.floor((Math.random() * loopNum)) % loopNum;
			var tmp = ranArr[i];
			ranArr[i] = ranArr[randNum];
			ranArr[randNum] = tmp;
		}
		return ranArr;
	},

	displayKeyword : function (res) {
		this.oKeyword = new pandora.util.StringBuffer();

		keyArr = this.ranArray(res.fSearch);
		for(var i=0; i<res.sView; i++){
			if(keyArr[i].mode == "s"){
				this.oKeyword.append('<a href="' + variable.getChild("searchHost") + '?ref=famouse&amp;query='+ keyArr[i].Kwd +'">'+ keyArr[i].txt +'</a>		<img src="'+this._imgPath+'/space.gif" width="5" height="2" alt="" />');
			}else if(keyArr[i].mode == "ad"){
				this.oKeyword.append('<a href="'+ keyArr[i].Kwd +'">'+ keyArr[i].txt +'</a>		<img src="'+this._imgPath+'/space.gif" width="5" height="2" alt="" />');
			}
		}

		$('popularKeyword').update(this.oKeyword.toString());
	},

	changeSelect : function(evt) {
		var el = Event.element(evt);
		switch (el.id) {
			case "sTab1" :
				$("sTab1").className = "bold";
				$("sTab2").className = "";
				$("tab").value = "program";
				break;
			case "sTab2" :
				$("sTab1").className = "";
				$("sTab2").className = "bold";
				$("tab").value = "channel";
				break;
		}
	},

	formSubmit : function(evt) {
		if (Prototype.Browser.IE == true && evt.type == "keyup") {
			return;
		}
		var code = "";

		try {
			code = evt.keyCode;
		}
		catch (e) {
			code = evt.charCode;
		}

		var el = Event.element(evt);
		/*
		if (code == 9 && evt.type == "keydown") {
//			window.status = 's , ';
		} else if (evt.type == "keydown" && this.keyupCnt > 0) {
			return;
		}
		*/
		var sbm = false;
		if ( (chInfoJson["currMenu"] == "PSEARCH") && (el.id == "sTab1" || el.id == "sTab2") ) {
			this.changeSelect(evt);
			sbm = true;
		}

		if ( (el.type == "button" && evt.type == "click") || (code == 13) || sbm == true) {
			if (this.inputAdver == false) { // no Adver
				/*
				Event.stopObserving("query", "keydown", this.formSubmit.bind(this));
				Event.stopObserving("query", "keyup", this.formSubmit.bind(this));
//				Event.stopObserving("query", "keypress", this.formSubmit.bind(this));
				Event.stopObserving("query", "click", this.formSubmit.bind(this));

				Event.stopObserving("searchBtn", "click", this.formSubmit.bind(this));
				Event.stopObserving("sTab1", "click", this.changeSelect.bind(this));
				Event.stopObserving("sTab2", "click", this.changeSelect.bind(this));
				Event.stopObserving("sTopAdver", "load", function() {
					adverView("sTopAdver");
				});
				*/

				// 자동 완성 화살표 이벤트
				if (oCookie.get("clientLang") == "ko" || chInfoJson["clientLang"] == "ko") {
					Event.stopObserving("AKCArrow", "click", this.arrowClick.bind(this));
				}

				Event.stopObserving(window, "load", function(){$("query").focus();} );

				var langv = "";
				for (var i=0; i<document.getElementsByName("langsort").length; i++) {
					if (document.getElementsByName("langsort")[i].checked == true) {
						langv = document.getElementsByName("langsort")[i].value;
					}
				}

				/*
				if ($("langsortAll").checked == false) {
					langv = "ko";
				}*/

				var url = variable.getChild('searchHost').toString() + "?query="+encodeURIComponent($('query').value) + "&tab=" + $("tab").value + "&langsort=" + langv + "&sq="+oCookie.get("ipCountry");

				document.location.href = url;
			} else {
				document.location.href = this.searchLink;
			}
		} else { //
//			console.log('input empty');

			if (this.searchClick < 1) {
				this.searchClick++;
				if (chInfoJson['keyword'].length == 0) {
					$('query').value = "";
				}
			}
			this.inputAdver = false;

//			if (evt.type == "keydown" || evt.type == "keyup" || evt.type == "click") {
			// 자동 완성 시작
			if ( (evt.type == "keyup" || evt.type == "keydown" || evt.type == "click" || evt.type == "keypress") && oCookie.get("ipCountry") == "KR") {
				Event.stopObserving(document.body, "click", function(evt) {
					var el = Event.element(evt);
					if (el.id != "query" && el.id != "AKCArrow " && el.id != "AKCArrowImg" && !Position.within($("AKCResult"), Event.pointerX(evt), Event.pointerY(evt))) {
						this.akc_hide();
					}
				}.bind(this));
				Event.observe(document.body, "click", function(evt) {
					var el = Event.element(evt);
					if (el.id != "query" && el.id != "AKCArrow " && el.id != "AKCArrowImg" && !Position.within($("AKCResult"), Event.pointerX(evt), Event.pointerY(evt))) {
						this.akc_hide();
					}
				}.bind(this));

//				$('query').focus();
				var sendQuery = $('query').value;
				sendQuery = sendQuery.replace(/^ +/g, "");
				sendQuery = sendQuery.replace(/ +$/g, " ");
				sendQuery = sendQuery.replace(/ +/g, " ");

				if (evt.type == "click" || evt.type == "keydown" || evt.type == "keyup") {
					$('query').style.backgroundImage = "";
				}

				switch(code) {
					case 9: // 탭
						if (evt.type == "keyup") {
							return;
//							alert('d');
						}

						if(sendQuery != "" && $("AKCResult").style.display != "none") {
							$('query').style.backgroundImage = "";
							try {
								evt.returnValue = false;
							} catch(e) {
								try {
									evt.preventDefault();
								}
								catch (e) { }
							}

							if(evt.shiftKey) {
								this.akc_up(); // shieft + tab 위로 올리자
							} else {
								this.akc_down(); // tab 만 하면 아래로 내리자
							}
						}

					break;

					case 13: // 엔터
	//					this.akc_hide(); // 레이어 숨기기
					break;

					case 38:	// 위쪽 화살표
						$('query').style.backgroundImage = "";
						this.akc_up(); // 위로 올리기
					break;

					case 40:	// 아래쪽 화살표
						$('query').style.backgroundImage = "";
						this.akc_down();
					break;

					default:

						if(code == 9 || code == 16 || code == 27 || code == 37 || code == 38 || code == 40 || code == 18) {
							return;
						}


						if (sendQuery.length > 0 || code == 8) {
							if (this.akc_yn == "y") {
								$("query").style.backgroundImage = ""; //akc_rmbackimg();
								this.akc_pointerNum = -1;
								if ( this.storage.isKey("akcStorage_" + sendQuery ) ) {
									this.loadAkc( this.storage.getChild("akcStorage_" + sendQuery) );
								} else {
									loadJS("http://search.pandora.tv/akc/akc_utf.ptv?q="+encodeURIComponent(sendQuery));
								}
							}
						} else {
							this.akc_hide();
						}
					break;
				}
			}
		}
	},

	loadAkc : function(json) {
		this.akc_orgquery = $("query").value;
		this.akcJson = json;
		if (this.akcJson["LIST"].length <= 0) {
//			return;
		}

		var inHtml = this.akcNoUse.toString();

		if (this.akc_yn == "y") {
			inHtml = this.akcList.toString();
		}

		if ($("AKCIDiv") == "undefined" || !$("AKCIDiv")) {
			$("AKCResult").update(inHtml);
		}

		if (this.akc_yn == "y") {
			if (this.akcJson["LIST"].length == 0) {
				var obj = "{'akcStorage_" + this.akcJson["QUERY"] + "':"+Object.toJSON(this.akcJson)+"}";
				this.storage.appendData(obj.evalJSON());
				this.akc_hide();
			} else {
				if( !this.storage.isKey("akcStorage_"+this.akcJson["QUERY"]) ) {
					var obj = "{'akcStorage_" + this.akcJson["QUERY"] + "':"+Object.toJSON(this.akcJson)+"}";
					this.storage.appendData(obj.evalJSON());
				}

				this.akc_show();
			}
		}
	},

	akc_setCookie : function(flag) {
		switch (flag) {
			case "y":
				oCookie.set("akcYN", "y", 0);
				this.akc_yn = "y";
				this.akc_show();
			break;
			case "n":
				oCookie.set("akcYN", "n", 0);
				this.akc_yn = "n";
				this.akc_hide();
			break;
		}
	},

	arrowClick : function() {
		if ($("AKCResult").style.display == "inline" || $("AKCResult").style.display == "") {
			this.akc_hide();
		} else {
			this.akc_show();
		}
	},

	akc_up : function() {
		if(this.akc_pointerNum <= 0 || this.akcJson["LIST"].length == 0) {
			$("query").value = this.akc_orgquery;
			this.akc_hide();
			this.akc_pointerNum = -1;
			return;
		}

		var choicNum = this.akc_pointerNum - 1;
		$("query").value = this.akcJson["LIST"][choicNum]["KEYWORD"];

		this.akc_show(); // 레이어 보여 주고 이미지 처리
		this.akc_curstyle(choicNum, this.akc_pointerNum);
		this.akc_pointerNum = choicNum;
//		alert(this.akc_pointerNum);
	},

	akc_down : function() {
		if (this.akc_pointerNum >= this.akcJson["LIST"].length || this.akcJson["LIST"].length == 0) {
			return;
		}

		var choicNum = this.akc_pointerNum + 1;
		$("query").value = this.akcJson["LIST"][choicNum]["KEYWORD"];

		this.akc_show(); // 레이어 보여 주고 이미지 처리
		this.akc_curstyle(choicNum, this.akc_pointerNum);
		this.akc_pointerNum = choicNum;
	},

	akc_hide : function() {
		try {
			if($("AKCResult").style.display == "inline") {
				$("AKCResult").style.display = "none";
				this.akc_chgbtn(0);
			}
		} catch (e) {
		}

		// 카테고리 언어 셀렉트 박스 none으로 변경
		try {
			$("contentsLang").style.display = "inline";
		} catch (e) { }
	},

	akc_show : function() {
		if($("AKCResult").style.display == "none") {
			$("AKCResult").style.display = "inline";
		}

		if (this.akc_yn != "y" || $("AKCIDiv") == "undefined" || !$("AKCIDiv") || $("query").value == "" || this.akcJson["LIST"].length == 0) {
			var inHtml = this.akcUse.toString();
			if (this.akc_yn != "y") {
				inHtml = this.akcNoUse.toString();
			}
			$("AKCResult").update(inHtml);
		} else {
			$("AKCIDiv").innerHTML = "";
			$("AKCIDiv").style.textAlign = "left";
			try {
				$("akcUL").style.height = "";
			} catch (e) { }


			var akcText = "";
			var akcHtml = "<ul style=\"list-style-type:none; padding:0; margin:0; overflow-y:auto; overflow-x:hidden;\" id=\"akcUL\">";
			for (var i=0; i<this.akcJson["LIST"].length; i++) {
				akcText = this.akcJson["LIST"][i]["KEYWORD"].replace(this.akcJson["QUERY"], "<font color='#fd5001'>" + this.akcJson["QUERY"] + "</font>");

				akcHtml += "<li id='akcKwd_"+i+"' style=\"list-style-type:none; margin:0; padding: 5px 10px 2px; cursor:pointer;\" onclick=\"top.location.href='http://search.pandora.tv/?ref=akc&amp;query=" + encodeURIComponent(this.akcJson["LIST"][i]["KEYWORD"]) + "'\" onmouseover=\"this.style.backgroundColor='#f2f2f2'\" onmouseout=\"this.style.backgroundColor='#FFFFFF'\">" + akcText + "<a href=\"javascript:;\" id='a_"+i+"'></a></li>";
			}
			akcHtml += "</ul>";

			if (akcHtml) {
				$("AKCIDiv").update(akcHtml);
				if (this.akcJson["LIST"].length > 5) {
					$("akcUL").style.height = "120px";
				}
			} else {
				$("AKCIDiv").update(this.akcUse.toString());// = akcHtml;
			}

			this.akc_chgbtn(1);
		}

		// 카테고리 언어 셀렉트 박스 none으로 변경
		try {
			$("contentsLang").style.display = "none";
		} catch (e) { }
	},

	akc_chgbtn : function(bool) {
		if(this.akc_yn=="y") {
			if(bool) {
				$("AKCArrowImg").src = "http://imgcdn.pandora.tv/pan_img/search/icon_org_up.gif";
			} else {
				$("AKCArrowImg").src = "http://imgcdn.pandora.tv/pan_img/search/icon_org_down.gif";
			}
		} else {
			if(bool) {
				$("AKCArrowImg").src = "http://imgcdn.pandora.tv/pan_img/search/icon_org_up.gif";
			} else {
				$("AKCArrowImg").src = "http://imgcdn.pandora.tv/pan_img/search/icon_org_down.gif";
			}
		}
	},

	akc_curstyle : function(pos, oldpos) {
		try {
			$("akcKwd_"+oldpos).style.backgroundColor="#FFFFFF";
		} catch(e) { }

		try {
			$("akcKwd_"+pos).style.backgroundColor="#f2f2f2";

	//		$("akcKwd_"+pos).focus();
			$("a_"+pos).focus();
			$("query").focus();
		} catch (e) { }
	},

	// 인풋 박스 광고 디스플레이
	displayAdverInput : function () {
		if (arguments[0] && arguments[1]) { // && chInfoJson['keyword'] == "") {
			var imgSource = arguments[0];
			this.searchLink = arguments[1];

			$("query").value = "";

			$("query").style.backgroundImage="url('" + imgSource + "')";
//			$("query").style.backgroundImage='url(' + imgSource + ')';
			$("query").style.backgroundRepeat = "no-repeat";
			$("query").style.backgroundPosition = "left";

			this.inputAdver = true;
		}
	}
}

var oSearch = new oSearch();
//Event.observe(window, "load", oSearch.set.bindAsEventListener(oSearch));
//--------------- LOCALIZEABLE GLOBALS ---------------

//---------------   GLOBAL VARIABLES   ---------------

//---------------     API FUNCTIONS    ---------------

//---------------    LOCAL FUNCTIONS   ---------------