$().ready(function(){
	// menu style
	$("#menu li").mouseover(function(){
		if(this.className != "open")
			this.className="hot";
	}).mouseout(function(){
		if(this.className != "open")
			this.className="";
	});
	
	$(window).resize(function(){
		var h = $(window).height();
		$("#contents").height((h - 101)+"px");
		$("#icontents").height($("#contents").height());		
	});
	$(window).resize();
	
	
	$('#newrating .star_rating').rating({
	cancel:'잘 모르겠어요~', 
	focus: function(value, link){
	$('#rating_tip').html(link.title); 
	}, 
	blur: function(value, link){
	$('#rating_tip').html("");
	} 
	});
	
	//$('#newrating .rating-cancel a').attr("title", "잘 모르겠어요~");
	
	google.setOnLoadCallback(OnLoad);
	
	/*
	if(jQuery.browser.msie){
		var settings = {tl: { radius: 6 },tr: { radius: 6 },bl: { radius: 6 },br: { radius: 6 },antiAlias: true};
		curvyCorners(settings, "#photoview");
	}
	*/
	
	$("#photo .thumb").mouseover(function(){
		$(this).addClass("hot");
	}).mouseout(function(){
		$(this).removeClass("hot");
	});
	
	if (g_member.length > 0) {
		g_uploader = new SWFUpload({
		flash_url: "../uploader/swfupload.swf",
		upload_url: "../uploader/uploadphoto.php",
		post_params: {uemail:g_member,store: g_store},
		file_size_limit: "2 MB",
		file_types: "*.jpg;*.png;*.gif",
		file_types_description: "이미지",
		file_upload_limit: 100,
		file_queue_limit: 0,
		// Button settings
		button_image_url: uploaderSetting.image,
		button_width: uploaderSetting.width,
		button_height: uploaderSetting.height,
		button_placeholder_id: "addphoto",			
		button_cursor: SWFUpload.CURSOR.HAND,
		// The event handler functions are defined in handlers.js
		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_start_handler : uploadStart,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete,
		queue_complete_handler : queueComplete
		});
	}
	if(IE6){
		pngfix('popup');		
	}	
});

function submitReview(store){
	if(g_savingComment) return;
	var comment = $("#review .item.add textarea[name='comment']").val();	
	var rating = $("#review .item.add input[name='rating']:checked").val();
	if(rating == undefined) rating=0;

	if (comment.length == 0) {
		alert("내용을 입력해주세요.");
		return;
	}	
	g_savingComment = true;
	
	$("#review .item.add img").hide();
	$("#review .item.add .detail").append("<img id=\"savingComment\" src=\"../images/loading.gif\" style=\"margin:24px 0 0 42px\" />");
			
	$.ajax({
	type:"POST",
	url:"../services/add_comment.php",
	data:{store:store,rating:rating,comment:comment},
	dataType:"json",
	cache:false,
	success:function(data){
		g_savingComment = false;
		if (data.result) {
			$("#review .item.add textarea[name='comment']").val("");
			$("#review .item.add input[name='rating']").rating('select', '');
			refreshReviewList(store, 1);
		} else 
			alert("등록 중 문제가 발생했네요. 불편을 드려 죄송합니다. 조금 후에 다시 한 번 시도해봐주세요~.");
				
		$("#savingComment").remove();
		$("#review .item.add img").show();
	},
	error:function(){
		g_savingComment = false;
		$("#savingComment").remove();
		$("#review .item.add img").show();
	}
	});
}
function ratingStar(id, level)
{
	var result = "";
	if(!level || level == 0) return result;
	for(var i = 1; i <= 5; i++)
	{
		if(i == level)
			result += "<input type=\"radio\" name=\"rating"+id+"\" class=\"star\" disabled=\"disabled\" checked=\"checked\" value=\""+i+"\" />";
		else 	
			result += "<input type=\"radio\" name=\"rating"+id+"\" class=\"star\" disabled=\"disabled\" value=\""+i+"\" />"; 	
	}
	return result;
}
function refreshReviewList(store,page){
	if(store == undefined || !store) store = g_store;
	if(page == undefined || !page) page=1;
	$.ajax({
	type:"GET",
	url:"../services/get_comments.php?store="+store+"&p="+page,
	dataType:'json',
	cache:false,
	success:function(data){
//		$("#review .list").html('');
		var html = '';
		g_reviewPage = data.page;
		
		// list
		var list = data.list;
		for(var i=0;i<list.length;i++){
			var ratingHTML = ratingStar(list[i].id, list[i].rating);
			var className = ((i % 2 != 0) ? ' even' : '');
			html += "<div id=\"review"+list[i].id+"\" class=\"item clearfix"+className+"\">\
			<div class=\"info\">"+list[i].nickname+"<br /><div class=\"time\">"+list[i].time+"</div><div class=\"actions\">";
			if(list[i].owner)
				html += "<a href=\"javascript:editReview('"+list[i].id+"')\" title=\"수정\">EDIT</a> | <a href=\"javascript:delReview('"+list[i].id+"')\" title=\"삭제\">DEL</a>";
			html += "</div></div><div class=\"detail\">"+ratingHTML+"<div class=\"clear\"></div><div class=\"text\">"+list[i].comment+"</div></div></div>";
		}
		$("#review .list").html(html);
		$("#review .list .star").rating();
		
		//paging
		html = '';
		var bp = data.page - 4;
		if(bp < 1) bp = 1;
		var ep = bp + 8;
		if(ep > data.totalpage) ep = data.totalpage;
		for(var i=bp; i<=ep; i++){
			if(i == data.page)
				html += "<span class=\"pagenum curr\" onclick=\"refreshReviewList(null,"+i+")\">"+i+"</span>";
			else
				html += "<span class=\"pagenum\" onclick=\"refreshReviewList(null,"+i+")\">"+i+"</span>";
		}
		$("#review .paging").html(html);
		
		$("#review .sectiontitle .count").html(data.totalcount);
		
		var st = $("#icontents").scrollTop();
		$("#icontents").scrollTop($("#review .list").offset().top + st - $("#icontents").offset().top - 40);
	}
	});	
}
function delReview(id){
	if(!confirm("정말 지우실건가요?")) return;
	
	var actions = $("#review"+id+" .info .actions").html();
	$("#review"+id+" .info .actions").html("<img src=\"../images/loading.gif\" />");	
	
	$.ajax({
	type:"GET",
	url:"../services/del_comment.php?id="+id,
	dataType:'json',
	cache:false,
	success:function(data){
		if(data.result)
			refreshReviewList(g_store, g_reviewPage);
		$("#review"+id+" .info .actions").html(actions);		
	},
	error:function(){
		$("#review"+id+" .info .actions").html(actions);		
	}
	});
}
var g_editingReview = -1;
var g_savedReview = '';
function editReview(id){
	if(g_editingReview == id) return;
	if(g_editingReview != -1){
		if(confirm("다른 리뷰를 수정 중인데, 그건 취소할까요?")) 
			cancelEditReview();
		else
			return;
	}		
	g_editingReview = id;
	g_savedReview = $("#review"+id+" .detail").html();
	var rating = $("#review"+id+" .star:checked").val();
	var orgtext = $("#review"+id+" .detail .text").html().split("\n").join("");
	var text = orgtext.split("<br>").join("\n").split("<BR>").join("\n");

	var editHtml = "<div id=\"erating\">\
	<input name=\"erating\" type=\"radio\" class=\"star_rating\" value=\"1\" title=\"여긴 별루!!\" />\
	<input name=\"erating\" type=\"radio\" class=\"star_rating\" value=\"2\" title=\"좀, 그다지..\" />\
	<input name=\"erating\" type=\"radio\" class=\"star_rating\" value=\"3\" title=\"그냥그냥 보통! 무난!\" />\
	<input name=\"erating\" type=\"radio\" class=\"star_rating\" value=\"4\" title=\"오, 좋음\" />\
	<input name=\"erating\" type=\"radio\" class=\"star_rating\" value=\"5\" title=\"완전 좋음, 강추!!\"/>\
	</div><div id=\"rating_tip\"></div>\
	<div class=\"clear\"></div>\
	<textarea name=\"comment\">"+text+"</textarea><img src=\"../images/store/savereview.gif\" class=\"submit\" onclick=\"editReviewSave('"+id+"')\" /><img src=\"../images/store/cancel.gif\" class=\"cancel\" onclick=\"cancelEditReview()\" /></td></tr>";
	
	$("#review"+g_editingReview).addClass("edit");
	$("#review"+id+" .detail").html(editHtml);
	$("#erating .star_rating").rating().rating("select", rating-1);
	
	$("#review"+id+" .detail textarea").keydown(function(evt){
		switch(evt.keyCode){
		case 27:
			cancelEditReview();
			break;	
		}
	}).focus();
}
function cancelEditReview(){
	if(g_editingReview==-1) return;
	
	$("#review"+g_editingReview).removeClass("edit");
	$("#review"+g_editingReview+" .detail").html(g_savedReview);
	
	g_editingReview = -1;
	g_savedReview = '';
}
function editReviewSave(){
	if(g_savingComment) return;
	var comment = $("#review"+g_editingReview+" .detail textarea").val();	
	var rating = $("#review"+g_editingReview+" .detail input[name='erating']:checked").val();
	if(rating == undefined) rating=0;

	if (comment.length == 0) {
		alert("내용을 입력해주세요.");
		return;
	}
	var id = g_editingReview;
	g_savingComment = true;
	$("#review .item.edit img").hide();
	$("#review .item.edit .detail").append("<img id=\"savingComment\" src=\"../images/loading.gif\" style=\"margin:24px 0 0 42px\" />");

	$.ajax({
	type:"POST",
	url:"../services/update_comment.php?id="+id,
	data:{id:id,rating:rating,comment:comment},
	dataType:"json",
	cache:false,
	success:function(data){
		g_savingComment = false;
		if (data.result) {
			cancelEditReview();
			$("#review"+id+" .detail .text").html(data.comment);
			if ($("#review" + id + " input").length == 0 && rating > 0) {
				$("#review" + id + " .detail").prepend(ratingStar(id, rating));
				$("#review" + id + " .detail .star").rating();
			} else {
				$("#review" + id + " .detail .star").remove();
				if (rating > 0) {
					$("#review" + id + " .detail").prepend(ratingStar(id, rating));
					$("#review" + id + " .detail .star").rating();
				}
			}
		} else 
			alert("등록 중 문제가 발생했네요. 불편을 드려 죄송합니다. 조금 후에 다시 한 번 시도해봐주세요~.");
			
		$("#savingComment").remove();
		$("#review .item.edit img").show();
	},
	error:function(){
		g_savingComment = false;
		$("#savingComment").remove();
		$("#review .item.edit img").show();
	}
	});	
}

function addPaginationLinks() {
  // The cursor object has all things to do with pagination
  var cursor = imageSearch.cursor;
  var curPage = cursor.currentPageIndex; // check what page the app is on
  var pagesDiv = document.createElement('div');
  pagesDiv.className = "paging";
  
  for (var i = 0; i < cursor.pages.length; i++) {
    var page = cursor.pages[i];
    if (curPage == i) { // if we are on the curPage, then don't make a link
      var label = document.createTextNode(' ' + page.label + ' ');
      pagesDiv.appendChild(label);
    } else {
      // If we aren't on the current page, then we want a link to this page.
      // So we create a link that calls the gotoPage() method on the searcher.
      var link = document.createElement('a');
      link.href = 'javascript:imageSearch.gotoPage('+i+');';
      link.innerHTML = page.label;
      link.style.marginRight = '2px';
      pagesDiv.appendChild(link);
    }
  }
  var contentDiv = document.getElementById('googleresult');
  contentDiv.appendChild(pagesDiv);
}
function searchComplete(searcher) {
  // Check that we got results
  if (searcher.results && searcher.results.length > 0) {
    // Grab our content div, clear it.
    var contentDiv = document.getElementById('googleresult');
    contentDiv.innerHTML = '';
	
//	document.getElementById("googletitle").innerHTML = "<a href=\"http://www.google.co.kr/images?q="+ encodeURIComponent("<?=$searchQuery?>") +"\" target=\"_blank\"><img src=\"./images/google_logo.gif\" style=\"margin-bottom:10px\" /></a>";
	
    // Loop through our results, printing them to the page.
    var results = searcher.results;
    for (var i = 0; i < results.length; i++) {
      // For each result write it's title and image to the screen
		var result = results[i];
		var imgContainer = document.createElement('div');
		var imgBox = document.createElement('div');
		
		imgContainer.className = "imgbox";
		
		//var url = result.unescapedUrl;
		imgBox.className = 'storephotobox';
		imgBox.style.width = result.tbWidth + "px";
		imgBox.style.height = result.tbHeight + "px";
		imgBox.style.backgroundImage = "url('"+result.tbUrl+"')";
		imgBox.style.marginLeft = "auto";
		imgBox.style.marginRight = "auto";
		imgBox.style.marginTop = parseInt((150 - result.tbHeight) / 2) + "px";
		
		imgBox.onclick = new Function("clickImage('"+result.unescapedUrl+"')");
		imgBox.title = result.titleNoFormatting;

		var siteShort = document.createElement('div');
		var anchor2 = document.createElement('a');
		siteShort.className = "imgsite";
		anchor2.href = result.originalContextUrl;
		anchor2.target = "_blank";
		anchor2.appendChild(document.createTextNode(result.visibleUrl));
		siteShort.appendChild(anchor2);
		
		imgContainer.appendChild(imgBox);
	  	imgContainer.appendChild(siteShort);  
		contentDiv.appendChild(imgContainer);
    }
	addPaginationLinks(imageSearch);
	
	var settings = {tl: { radius: 5 },tr: { radius: 5 },bl: { radius: 5 },br: { radius: 5 },antiAlias: true};
	//curvyCorners(settings, ".storephotobox");
  }
}

function clickImage(url){
	var wnd = window.open(url, "googleimage","resizable=1,scrollbars=1,toolbar=0,height=550,width=650",false);
}

function addPaginationLinks2(total,curr, display) {
  // The cursor object has all things to do with pagination
  var pagesDiv = document.createElement('div');
  pagesDiv.className = "paging";
  var bp, ep;
  
  bp = curr - 4;
  if(bp < 1)  bp = 1;
  ep = bp + 7;
  if(ep > total) ep = total;
  
  for (var i = bp; i <= ep ; i++) {
    if (curr == i) { // if we are on the curPage, then don't make a link
      var label = document.createTextNode(' ' + i + ' ');
      pagesDiv.appendChild(label);
    } else {
      // If we aren't on the current page, then we want a link to this page.
      // So we create a link that calls the gotoPage() method on the searcher.
      var link = document.createElement('a');
      link.href = 'javascript:naverSearch('+i+');';
      link.innerHTML = i;
      link.style.marginRight = '2px';
      pagesDiv.appendChild(link);
    }
  }
  var contentDiv = document.getElementById('naverresult');
  contentDiv.appendChild(pagesDiv);
}

function searchFrameLoaded(){
	var f = document.getElementById("isearchresult");
	//f.style.width=(f.contentWindow.document.body.scrollWidth)+"px";
	f.style.height=((f.contentWindow.document.body.scrollHeight) + 50) +"px"	
	document.getElementById("searchresult").style.height = f.style.height; 
}

function goTo(name){
	var st = $("#icontents").scrollTop();
	$("#icontents").animate({scrollTop:$("#"+name).offset().top + st - $("#icontents").offset().top - 20}, 300);
	//$("#icontents").scrollTop($("#"+name).offset().top + st - $("#icontents").offset().top - 30);
	
//	location.href = "#"+name;
}
function goToTop(){
	$("#icontents").animate({scrollTop:0}, 300);	
}
function showMap(area, store){
	if (opener && opener.showStore) {
		if (store != undefined && store > 0) opener.showStore(area, store);
		else opener.showMap(area);
		opener.focus();
	} else if (!opener) {
		if (store != undefined && store > 0)
			window.open("http://www.playstreet.net/?store="+store, "playstreet");
		else
			window.open("http://www.playstreet.net/?area="+area , "playstreet");
	}
}

function showLoginPopup(ret){
	if(!ret || ret == 'undefined')
		ret = location.href;
	showPopup('로그인',320,180,'../plogin.html?ret='+encodeURIComponent(ret)+"&path=../");
}
function textInputFocus(o,f){	
	o.className=f?"tinputFocused":"tinput";
}
function showPopup(title, width, height, url){
	var ww=getWindowWidth();
	var wh=getWindowHeight();
	var p=el("popup");
	var pc=el("p_contents");
	el("ptitle").innerHTML = title;
	pc.src=url;
	pc.style.width=width+"px";
	pc.style.height=height+"px";
	p.style.left=((ww - (width+31))/2) +"px";
	p.style.top=((wh - (height+50))/2) +"px";

	if(g_popupVisible == false)
	{
		el("film").style.width=ww+"px";
		el("film").style.height=wh+"px";
		el("film").style.display="";
	}
	p.style.display="";	
	
	g_popupVisible=true;
}
function hidePopup(){
	el("popup").style.display="none";
	el("film").style.display="none";
	el("p_contents").src="";
	
	g_popupVisible=false;
}
function updatePopupPos(){
	var ww=getWindowWidth();
	var wh=getWindowHeight();
	el("film").style.width=ww+"px";
	el("film").style.height=wh+"px";
	var w=parseInt(el("p_contents").style.width);
	var h=parseInt(el("p_contents").style.height);
	el("popup").style.left=((ww - (w+31))/2) +"px";
	el("popup").style.top=((wh - (h+50))/2) +"px";
}
function popupPageLoaded(width, height){
//	alert(width+" x "+height);
	if(width == undefined || !width) width = 0;
	if(height == undefined || !height) height = 0;
	var ww=getWindowWidth();
	var wh=getWindowHeight();
	var p=el("popup");
	var pc=el("p_contents")
	
	if(width > 0)
		pc.style.width = width + "px";
	else
		pc.style.width=(pc.contentWindow.document.body.scrollWidth)+"px";
	if(height > 0)
		pc.style.height = height + "px";
	else
		pc.style.height=(pc.contentWindow.document.body.scrollHeight)+"px"

	p.style.width = (parseInt(pc.style.width)+31) + "px";
	p.style.height = (parseInt(pc.style.height)+50) + "px";
	p.style.left=((ww - (parseInt(pc.style.width)+31))/2) +"px";
	p.style.top=((wh - (parseInt(pc.style.height)+50))/2) +"px";
}

function viewPhoto(id,area,store,filename,del){
	$("#photoview").css("background", "url(../files/storephoto/"+area+"/"+store+"/"+filename+") no-repeat center center");
	var html = "";
	if(del){
		html += "<a href=\"javascript:delPhoto("+id+")\">삭제</a>";
	}
	html += " &nbsp;<a href=\"../files/storephoto/"+area+"/"+store+"/"+filename+"\" target=\"_blank\">원본보기</a>";
	$("#photoaction").html(html);	
	
	$("#photo .thumb").removeClass("curr");
	$("#photo"+id).removeClass("hot");
	$("#photo"+id).addClass("curr");
}

function delPhoto(id){
	if(!confirm("정말 삭제하시겠습니까?"))
		return;
	$.ajax({
		type:"GET",
		url:"../services/store_photo_delete.php?id="+id,
		success:function(text){
			if(text == 'OK'){
				var thumbs = $("#photo .thumb");
				var idx = thumbs.index($("#photo"+id));
				if(thumbs.length == 1)
				{
					$("#photoview").css("background","");
					$("#photoaction").html("");
					
				}else if(idx < thumbs.length - 1)
					thumbs.eq(idx+1).click();
				else if(idx == thumbs.length - 1)
					thumbs.eq(idx - 1).click();

				$("#photo"+id).remove();
				$("#photo .sectiontitle .count").html(thumbs.length - 1);
			}else
				alert(text);
		}
	});	
}

function showCopyURL(){
	$("#pu_urltext").val("http://"+location.host+"/store/"+g_store);
	$("#p_url").show();
	$("#pu_urltext").focus();
	$("#pu_urltext").select();
	$(document).bind("keydown",hideCopyURL2);
}
function hideCopyURL(){
	$("#p_url").hide();		
}
function hideCopyURL2(event){
	if(event.keyCode == 27){
		hideCopyURL();
		$(document).unbind("keydown",hideCopyURL2);
	}
}
