function gotoSite(id,url){
	if(setting) return;
	
//	if(id==67){
//		alert('사이트가 다운된 듯 합니다 ㅠㅜ.');
//		return;
//	}
	if(openmode==1)
		window.open("redirect2.php?id="+id+"&om="+openmode+"&url="+encodeURIComponent(url),'xiles');
	else
		location.href="redirect2.php?id="+id+"&om="+openmode+"&url="+encodeURIComponent(url);
}
function changeEngine(e){
hideSuggest();
if(e == 'naver'){  // naver
document.getElementById("searchbutton").innerHTML = '<img src="images/bt_sc.png" />';
document.getElementById("searchbutton").className = "naver";
document.getElementById("searchbox").className = "naver";
document.getElementById("naver_logo").style.opacity = 1.0;
document.getElementById("google_logo").style.opacity = 0.3;
document.getElementById("daum_logo").style.opacity = 0.3;
engine = 'naver';
setCookie("searchengine", 'naver', 90);
}else if(e == 'google'){ // google
document.getElementById("searchbutton").innerHTML = '';
document.getElementById("searchbutton").className = "google";
document.getElementById("searchbox").className = "google";
document.getElementById("naver_logo").style.opacity = 0.3;
document.getElementById("google_logo").style.opacity = 1.0;
document.getElementById("daum_logo").style.opacity = 0.3;
engine = 'google';
setCookie("searchengine", 'google', 90);
}else if(e == 'daum'){ // daum
document.getElementById("searchbutton").innerHTML = '<img src="images/daumbtn.gif" />';
document.getElementById("searchbutton").className = "daum";
document.getElementById("searchbox").className = "daum";
document.getElementById("naver_logo").style.opacity = 0.3;
document.getElementById("google_logo").style.opacity = 0.3;
document.getElementById("daum_logo").style.opacity = 1.0;
engine = 'daum';
setCookie("searchengine", 'daum', 90);
}
$("#searchbox").focus();
}
function search(query){
hideSuggest();
$("#searchbox").blur();
var q;
if(query!=undefined && query.length > 0)
	$("#searchbox").val(query);
q = $("#searchbox").val();
if(q.length == 0) return;
smartSearch(q);
//location.href="search.php?e="+engine+"&q="+encodeURIComponent(q);
}
function search2(){
hideSuggest();
var q = document.getElementById("searchbox").value;
if(q.length == 0) return;
location.href="search.php?e="+engine+"&q="+encodeURIComponent(q);
}
function searchKeyDown(evt){
	if(evt.keyCode == 13)
		search();
}
/*
function setOpenMode(obj){
	openmode = obj.checked ? 1 : 0;
	setCookie("openmode", openmode, 90);
}
*/
function setWArea(){
	location.href="choosearea.html";
}
function openKeywordSearch(idx){
	if(idx < 0 || idx > 9) return;
	location.href="search.php?r=1&e="+engine+"&q="+encodeURIComponent(naverRanks[idx].keyword);
}
function getNaverRank(updatelist){
  var src;
  clearTimeout(timerid);
  document.getElementById("keywordrank").innerHTML='<img src="images/loading.gif" alt="" />';
  if(updatelist)
  	document.getElementById("rankList").innerHTML='<img src="images/loading.gif" alt="" style="margin:30px" />';
  request = GetRequestObject();
  request.onreadystatechange = function(){
    if(request.readyState == 4){
        if(request.status == 200){		        
		   	var xmlDoc = request.responseXML;
		    var item = xmlDoc.getElementsByTagName("item");
			if(!item) return;
			updateNaverRank(item,updatelist);
        }
    }else if(request.readyState >= 1 && request.readyState < 4)	{
		document.getElementById("keywordrank").innerHTML='<img src="images/loading.gif" alt="" />';
	}  	
  };
  src = "naver_queryrank.php"; 
  request.open("GET", src, true);
  request.send(null);
}
function GetRequestObject(){
var req = null;
if (typeof XMLHttpRequest != "undefined") req = new XMLHttpRequest();
if (!req && typeof ActiveXObject != "undefined"){
	try{req=new ActiveXObject("Msxml2.XMLHTTP");}
	catch (e){
		try	{req=new ActiveXObject("Microsoft.XMLHTTP");}
		catch (e2){
			try {req=new ActiveXObject("Msxml2.XMLHTTP.4.0");}
			catch (e3){req=null;}
		}
	}
}
if(!req && window.createRequest) req = window.createRequest();
return req;
}
function updateNaverRank(item,updatelist){
	var ritem;  
	for (var i = 1; i <= 10; i++) {
	ritem = item[0].getElementsByTagName("R" + i)[0];
	K = ritem.getElementsByTagName("K")[0].childNodes[0].nodeValue;
	S = ritem.getElementsByTagName("S")[0].childNodes[0].nodeValue;
	V = ritem.getElementsByTagName("V")[0].childNodes[0].nodeValue;
	naverRanks[i-1]={keyword:K,upnew:S,upnum:V};
	}
	var html='';
	for(var i=0;i<naverRanks.length;i++){
		html+='<li onclick="openKeywordSearch(\''+i+'\')">'+(i+1)+'. '+naverRanks[i].keyword+'</li>';
	}
	document.getElementById("rankList").innerHTML=html;
	
	var d = new Date();	
	document.getElementById("nrankBottom").innerHTML="Updated: "+d.getFullYear()+"."+(d.getMonth()+1)+"."+d.getDate()+" "+(d.getHours()+1)+":"+d.getMinutes();
	rollingRank();
	if(updatelist) showNaverRank();
}
function rollingRank(){
	if(naverRanks.length < 10) return;
	document.getElementById("keywordrank").innerHTML=(currRank+1)+'. '+naverRanks[currRank].keyword;
	if(currRank == 9) currRank = 0;
	else currRank++;
	timerid=setTimeout("rollingRank()",3000);
}
function showNaverRank(){
	if(naverRanks.length < 10) return;
	document.getElementById("naverRank").style.display='';
}
function hideNaverRank(){
	document.getElementById("naverRank").style.display='none';
}
function updateNewList(){
	if(newlist.length == 0) return;
	var html='<div class="sectiontitle" rel="fixed">새로 추가된 사이트</div><div class="section">';
	for(var i=0; i < newlist.length; i++){
		var l = newlist[i];
		html += '<div class="site">\
<a href="#" onclick="javascript:gotoSite('+l.id+',\''+l.url+'\');return false;"><div class="icon"><img src="images/icons/'+l.alias+'.png"/></div></a>\
<div class="label">'+l.title+'</div>\
</div>';
	}
	html += "</div>";
	$("#newlist").html(html);
}
function updateMostUsedList(){
	if(mostusedlist == undefined || mostusedlist.length == 0) return;
	var html='<div class="sectiontitle" rel="fixed">자주 가는 사이트</div><div class="section">';
	for(var i=0; i < mostusedlist.length; i++){
		var l = mostusedlist[i];
		html += '<div class="site">\
<a href="#" onclick="javascript:gotoSite('+l.id+',\''+l.url+'\');return false;"><div class="icon"><img src="images/icons/'+l.alias+'.png"/></div></a>\
<div class="label">'+l.title+'</div>\
</div>';
	}
	html += "</div>";
	$("#mostusedlist").html(html);
}
function updateList(){
	var html='';
	var currcat = -1;
	for(var i=0; i < list.length; i++){
		var l = list[i];
		if(currcat != l.cat){
			currcat = l.cat;
			if(html.length > 0) html += "</div>";
			html += '<div class="sectiontitle" rel="'+l.cat+'">'+clist[l.cat]+'</div><div class="section" style="display:none">';	
		}
		html += '<div class="site" id="site'+l.id+'">\
<a href="#" onclick="gotoSite('+l.id+',\''+l.url+'\');return false;"><div class="icon"><img src="images/icons/'+l.alias+'.png"/></div></a>\
<div class="label">'+l.title+'</div>\
<div class="del" style="display:none" onclick="hideSite('+l.id+');"><img src="images/del.png" /></div>\
</div>';
	}
	$("#list").html(html);
}
function updateList2(){
	var html='';
	var currcat = -1;
	for(var i=0; i < list.length; i++){
		var l = list[i];
		if(currcat != l.cat){
			currcat = l.cat;
			if(html.length > 0) html += "</ul>";
			html += '<div class="sectiontitle2" rel="'+l.cat+'">'+clist[l.cat]+'</div><ul class="section" style="display:none">';	
		}
		html += '<li class="site2" id="site'+l.id+'">\
<a href="#" onclick="gotoSite('+l.id+',\''+l.url+'\');return false;">\
<div class="label">'+l.title+'</div>\
<div class="desc">'+l.desc+'</div>\
</a>\
<div class="del" style="display:none" onclick="hideSite('+l.id+');"><img src="images/del.png" /></div>\
</li>';
	}
	if(html.length > 0) html == '</ul>';
	$("#list").html(html);
}

function hideSite(id){
	if(!confirm('정말 선택한 사이트를 안보이도록 할까요?')) return;
	$.ajax({
		type:'GET',
		url:'services/set_hidesite.php?id='+id,
		dataType:'json',
		success:function(data){
			$("#site"+id).remove();
		},error:function(a,b){
			alert("인터넷 연결이 잘 되어 있나요?");
		}
	});
}
function toggleSettingMode(){
	if(setting){
		$(".site .del").hide();
		$(".site2 .del").hide();
		$("#setsite").removeClass("on");
		$("#setsite").html('편집');
	}else{
		$(".site .del").show();
		$(".site2 .del").show();
		$("#setsite").addClass("on");
		$("#setsite").html('완료');
	}
	setting = !setting;
}
function showJoinForm(){
	hideLoginForm();
	window.scrollTo(0,1);
	$("#joinform").show();
	$("#joinform input[name='userid']").focus();
}
function hideJoinForm(){
	if($.browser.opera)
		document.getElementById("joinform").style.display="none";
	else
		$("#joinform").hide();
}
function submitLogin(){
	var userid = $("#loginform input[name='userid']").val();
	var pw = $("#loginform input[name='userpw']").val();
	$.ajax({
		type:'POST',
		url:'services/set_login.php',
		data:{user:userid,pw:pw},
		dataType:'json',
		success:function(data){
			if(data.result){
				location.reload();
			}else{
				alert(data.msg);
			}
		},error:function(a,b){
			alert("인터넷 연결이 잘 되어있나요?");
		}
	});
}
function submitJoin(){
	var userid = $("#joinform input[name='userid']").val();
	var pw1 = $("#joinform input[name='userpw1']").val();
	var pw2 = $("#joinform input[name='userpw2']").val();
	if(pw1 != pw2){
		alert('삐~~!!! 비밀번호 두번 입력한게 달라요!');
		return;
	}
	$.ajax({
		type:'POST',
		url:'services/set_join.php',
		data:{user:userid,pw1:pw1,pw2:pw2},
		dataType:'json',
		success:function(data){
			if(data.result){
				alert(userid+'로 가입되었고,\n자동으로 로그인되었습니다.');
				location.reload();
			}else{
				alert(data.msg);
			}
		},error:function(a,b){
			alert("인터넷 연결이 잘 되어있나요?");
		}
	});	
}
function showLoginForm(){
	hideJoinForm();
	window.scrollTo(0,1);
	$("#loginform").show();
	$("#loginform input[name='userid']").focus();
}
function hideLoginForm(){
	$("#loginform").hide();
}
function logout(){
	if(!confirm('로그아웃 할까요?')) return;
	setCookie('nx001','');
	location.reload();
}
function restoreSite(){
	location.href='restore.php';
}
function hideURLBar(){if($(window).scrollTop() == 0) window.scrollTo(0,1);}
function smartSearch(query){
	$("#sloading").show();
	$.ajax({
		type:'GET',
		url:'services/get_smartsearch.php?q='+encodeURIComponent(query),
		dataType:'json',
		success:function(data){
			if(data.length == 0)
				search2();
			else{
				var html='';
				var type,subtext;
				for(var i=0; i < data.length; i++){
					if (data[i].content.indexOf('tel:') != -1) {
						type = '전화걸기';
						subtext = '('+data[i].subtext+')';
					}else if (data[i].content.indexOf('http://') != -1) {
						type = '바로가기';
						subtext = '('+data[i].content+')';
					}else{
						type = '';
						subtext = '';
					}
					if(type.length > 0)
						html += '<li><a href="'+data[i].content+'"><span class="type">'+type+': </span>'+data[i].title+'<span class="subtext"> '+subtext+'</span></a></li>';
					else
						html += '<li>'+data[i].content+'</li>';
				}
				html += '<li class="btn"><a href="javascript:search2();">일반 검색 결과 보기</a></li>';
				$("#smartsearch").css('top',$("#topbar").offset().top);
				$("#smartsearch").css('min-height',$(document).height() - $("#topbar").offset().top);
				$("#smartsearch ul").html(html);
				$("#smartsearch").show();
				/*$("#smartsearch ul li").click(function(){
					hideSmartSearch();
				});*/
			}
			$("#sloading").hide();

		},error:function(a,b){
			search2(query);
			$("#sloading").hide();
		}
	});
}
function hideSmartSearch(){
	$("#smartsearch").hide();
}
function loadSectionOpen(){
	var str = getCookie('sectionopen');
	if(str.length == 0) return;
	var l = str.split("|");
	for(var i=0;i<l.length;i++){
		var c = l[i].split(':');
		sectionopen[c[0]] = c[1];
	}
}
function saveSectionOpen(){
	var so = [];
	var c;
	for(c in sectionopen){
		so.push(c+':'+sectionopen[c]);
	}
	setCookie('sectionopen',so.join('|'));
}
function initSectionOpen(){
	loadSectionOpen();
	$(".sectiontitle2").each(function(){
		var so = sectionopen[$(this).attr('rel')];
		if(so != undefined && so == 1)
			$(this).next().show();
	});	
	$(".sectiontitle").each(function(){
		var so = sectionopen[$(this).attr('rel')];
		if(so != undefined && so == 1)
			$(this).next().show();
	});	
}
function autosuggest(){
	var q = $("#searchbox").val();
	if(q.length == 0){
		hideSuggest();
		return;
	}
	$.ajax({
		type:'GET',
		url:'naver_recmd.php?q='+encodeURIComponent(q),
		dataType:'xml',
		success:function(data){
			if(q != asquery) return;
			var list = data.getElementsByTagName("item");
			var html ='';
			if (list.length == 0 || $("#smartsearch").css('display') != 'none') {
				hideSuggest();
			}else {
				for (var i = 0; i < 4 && i < list.length; i++) {
					html += '<div class="item" onclick="suggestClick(this);">' + list[i].childNodes[0].nodeValue + '</div>';
				}
				html += '<div class="item close" onclick="hideSuggest();">닫기</div>';
				$(".suggest").html(html);
				$(".suggest").css({top:$("#searchbox").offset().top + $("#searchbox").outerHeight(),left:$("#searchbox").offset().left, width:$("#searchbox").outerWidth()-2});
				$(".suggest").show();
				$(window).scrollTop($("#searchbox").offset().top - 15);
			}
		}
	});
}
function suggestClick(el){
	search($(el).html());
}
function hideSuggest(){
	$(".suggest").hide();
}