function viewHTML(query_url, where) {
	var position = "#multiarea_" + where;
	if($(position).is(":visible")) {
		$(position).hide("slide", { direction: "up" }, 300);
	}
	else {
		$.ajax({
			url: "./proxy/getHTML.php",
			type: "POST",
			data: "query_url=" + query_url,
			cache: false,
			success: function(res) {
				$(position).html(res);
				$(position).show("slide","", 300);
			}
		});
	}
}

var tabarr = ["#tab_total", "#tab_supporter", "#tab_photo", "#tab_item"];
var tabarr_on = ["./images/tab_total_on.png", "./images/tab_supporter_on.png", "./images/tab_photo_on.png", "./images/tab_item_on.png"];
var tabarr_off = ["./images/tab_total_off.png", "./images/tab_supporter_off.png", "./images/tab_photo_off.png", "./images/tab_item_off.png"];

function toggleTab(onTab) {
	$.each(tabarr, function(index, tabid) {
		if(index == onTab) $(tabid).css("backgroundImage", "url(" + tabarr_on[index]  + ")");
		else $(tabid).css("backgroundImage", "url(" + tabarr_off[index]  + ")");
	});

	getArticle(onTab);
}

function getItems(page) {
	var searchKey = $("#goodsSearchKey").val();
	if(searchKey.length < 2) return false;
	$("#itemListArea").html("");
	$("#itemListArea").html("<div style='text-align:center; width:100%; padding-top:50px;'><img src='./images/loading.gif' /><br/><br/>읽어 오고 있어요</div>");

	if(!page) page = 1;

	$.ajax({
		url: "./proxy/item/getItems.php",
		type: "POST",
		data: "searchkey=" + searchKey + "&page=" + page,
		cache: false,
		success: function(res) {
			$("#itemListArea").html(res);
			$("#itemListArea").fadeIn(999);
			$("#postArticleItemID").val("");
		}
	});
}

function viewItem(docid) {
	$("#itemListArea").html("");
	$("#itemListArea").html("<div style='text-align:center; width:100%; padding-top:50px;'><img src='./images/indicator.gif' /><br/><br/>읽어 오고 있어요</div>");

	$.ajax({
		url: "./proxy/item/viewItem.php",
		type: "POST",
		dataType: 'json',
		data: ({
			item: docid,
			json: true}),
		cache: false,
		success: function(res) {
			$("#itemListArea").html(res.text);
			$("#itemListArea").fadeIn(999);
			$("#postArticleItemID").val(docid);
			$("#postArticleItemIMG").val(res.imgurl);
		}
	});
}

function getArticle(tabid) {
	$("#articlearea").html("");
	$("#articlearea").html("<div style='text-align:center; width:100%; padding-top:50px;'><img src='./images/indicator.gif' /><br/><br/>읽어 오고 있어요</div>");

	$.ajax({
		url: "./proxy/getArticles.php",
		type: "POST",
		data: "tabid=" + tabid,
		cache: false,
		success: function(res) {
			$("#articlearea").html(res);
			$("#articlearea").fadeIn(999);
		}
	});
}

function imageClick() {
	$(".items img").click(function() {
		var ext = $(this).attr("alt"); 
		var skinid = $(this).attr("title");
		var url = $(this).attr("src").replace('thumb','').replace('.jpg', "." + ext); 
		var wrap = $("#image_wrap").fadeTo("medium", 0.5); 

		$("#postArticleSupporterSkinID").val(skinid);

		var img = new Image();
		img.onload = function() {
			wrap.fadeTo("fast", 1);
			wrap.find("img").attr("src", url);
		}; 
		img.src = url;
	}).filter(":first").click();
}

function showPostType(data) {
	if($('#PostTypeList').is(":visible")) {
		$("#PostTypeList").hide("slide", { direction: "up" }, 300);
	}
	else {
		$("#PostTypeList").show("slide", { direction: "up" }, 100);
	}
}

function selectPostType(data, mode) {
	$("#PostTypeList").hide("slide", { direction: "up" }, 100);
	$("#currentPostType").attr("src", data);

	$("#postPhotoOpt:visible").hide("slide", { direction: "up" }, 100);
	$("#postItemOpt:visible").hide("slide", { direction: "up" }, 100);
	$("#postSupporterOpt:visible").hide("slide", { direction: "up" }, 100)
		
	$("#postArticleType").val(mode);

	switch(mode) {
		case 1: // supporter
			$("#postSupporterOpt").show("slide", { direction: "up" }, 400, getSupporter(0,0,1));
			break;
		case 2: // photo
			$("#postPhotoOpt").show("slide", { direction: "up" }, 400);
			break;
		case 3: // item
			$("#postItemOpt").show("slide", { direction: "up" }, 400);
			break;
		default:
			break;
	}
}

function deleteSkin(skinid) {
	var bConfirmed = confirm('스킨 넘버 [' + skinid + '] 을 삭제하실건가요 ?');
	if (bConfirmed){
		$.ajax({
			url: "./proxy/supporter/deleteSkin.php",
			type: "POST",
			dataType: 'json',
			data: "skinid=" + skinid,
			cache: false,
			success: function(res) {
				if(res.result) {
					alert("삭제 성공 : " + res.message);
					$("#skinMyCategory").click();
				}
				else alert("삭제 실패 : " + res.message);
			}
		});
	}
}

function viewComment(postid) {
	var position = "#comment_" + postid;
	if($(position).is(":visible")) {
		$(position).hide("slide", { direction: "up" }, 300);
	}
	else {
		$(position).html("");
		$(position).html("<div style='text-align:center; width:100%; padding-top:50px;'><img src='./images/indicator.gif' /><br/><br/>읽어 오고 있어요</div>");

		$.ajax({
			url: "./proxy/getComments.php",
			type: "POST",
			data: "postid=" + postid,
			cache: false,
			success: function(res) {
				$(position).html(res);
				$(position).show("slide", { direction: "up" }, 100);
			}
		});
	}
}

var messageHelp = ["☜ 왼쪽 물음표 \"?\" 버튼을 클릭하고 종류를 선택해 주세요!", "태그를 쓰세요 (공백으로 구분)"];

function clearDefault(el, bools) {
	var txtIdx = 0;
	if(el.id == "postTextBox") txtIdx = 0;
	else if(el.id == "postTagBox") txtIdx = 1;
	if(bools) {
		if (messageHelp[txtIdx] == el.value) el.value = "";
	}
	else {
		if(trim(el.value).length <= 0)
			el.value = messageHelp[txtIdx];
	}
}

function watchDog() {
	var textValue = $("#postTextBox").val();
	$("#previewArea").text(textValue);

	if(hasExpression(textValue)) {
		$("#previewArea").html(replaceAll(textValue));
	}

	textValue = $("#previewArea").html().replace(/<[^>]+>/g, "").replace(/<\/[^>]+>/g, "");
	leftLength = 150 - textValue.length;

	$("#limit_cal").html(leftLength);
	
	$("#loadingArea").html("");
}

function writePost() {
	var postType = parseInt($("#postArticleType").val());
	var postTag = $("#postTagBox").val();
	var postText = $("#postTextBox").val();
	
	$("#loadingArea").html("<img src='./images/loading.gif' /><br/>포스팅중입니다");

	if(postText == messageHelp[0] || trim(postText).length <= 0) {
		alert("글을 입력해 주세요");
		$("#writepostnone").one("click", function() { writePost(); });
		return false;
	}

	if(parseInt($("#limit_cal").html()) < 0) {
		alert("글은 150자를 넘을 수 없습니다");
		$("#writepostnone").one("click", function() { writePost(); });
		return false;
	}

	if(postTag == messageHelp[1]) { postTag = ""; }

	switch(postType) {
		case 0:
			alert("글 종류를 선택해 주세요");
			$("#writepostnone").one("click", function() { writePost(); });
			$("#currentPostType").click();
			break;
		case 1: // Supporter
			var supporterID = $("#postArticleSupporterID").val();
			var supporterSkinID = $("#postArticleSupporterSkinID").val();
			var displaymode = $('input[name=sup_select]:checked').val();
			var isPhoto = $('#madePhoto').attr('checked');

			if(isPhoto) $supUrl = "./proxy/supporter/postPhotoSupporter.php";
			else $supUrl = "./proxy/supporter/postSupporter2.php";

			$.ajax({
				url: $supUrl,
				type: "POST",
				dataType: 'json',
				data: ({
					postArticleType: postType,
					postArticleTag: postTag,
					postArticleText: postText,
					displayMode: displaymode,
					supid: supporterID,
					skinid: supporterSkinID
				}),
				cache: false,
				success: function(resjson) {
					if(resjson.result) {
						$("#postArticleType").val(0);
						$("#currentPostType").attr("src", "./images/post_question_btn.png");
						$("#postSupporterOpt:visible").hide("slide", { direction: "up" }, 100);
						$("#postTagBox").val("");
						$("#postTextBox").val("");
						watchDog();
						toggleTab(1);
					}
					else
						alert(resjson.res_msg + "\n\n - 해당 오류는 me2day.net 에 문의바랍니다.");
					$("#writepostnone").one("click", function() { writePost(); });
				},
				error: function(resjson) {
					alert("지지자 포스팅 실패" + resjson);
					$("#writepostnone").one("click", function() { writePost(); });
				}
			});
			break;
		case 2: // Photo
			var photoName = $("#postArticlePhotoName").val();

			if(photoName.length <= 0) {
				alert("업로드할 사진파일을 선택하세요");
				$("#writepostnone").one("click", function() { writePost(); });
				return false;
			}
			else {
				$.ajax({
					url: "./proxy/photo/postPhoto.php",
					type: "POST",
					dataType: 'json',
					data: ({
						postArticlePhotoName: photoName,
						postArticleType: postType,
						postArticleTag: postTag,
						postArticleText: postText 
					}),
					cache: false,
					success: function(resjson) {
						$("#uploadedPhotoArea").find("img").attr("src", "./images/noimages.png");
						$("#uploadedPhotoArea").find("img").removeAttr('width');
						$("#uploadedPhotoArea").find("img").removeAttr('height');
						$("#postArticlePhotoName").val("");
						if(resjson.result) {
							if(resjson.res_msg.code)
								alert(resjson.res_msg.code + " : " + resjson.res_msg.message);
							else {
								$("#postArticleType").val(0);
								$("#currentPostType").attr("src", "./images/post_question_btn.png");
								$("#postPhotoOpt:visible").hide("slide", { direction: "up" }, 100);
								$("#postTagBox").val("");
								$("#postTextBox").val("");
								watchDog();
								toggleTab(2);
							}
						}
						else alert(resjson.res_msg);
						$("#writepostnone").one("click", function() { writePost(); });
					}
				});
			}
			break;
		case 3: // Item
			var itemid = $("#postArticleItemID").val();
			var itemimg = $("#postArticleItemIMG").val();

			if(itemid.length <= 0) {
				alert("같이 포스팅할 아이템을 선택하세요");
				$("#writepostnone").one("click", function() { writePost(); });
				return false;
			}
			if(itemimg.length <= 0) {
				alert("같이 포스팅할 아이템을 선택하세요");
				$("#writepostnone").one("click", function() { writePost(); });
				return false;
			}

			else {
				$.ajax({
					url: "./proxy/item/postItem.php",
					type: "POST",
					dataType: 'json',
					data: ({
						postArticleType: postType,
						postArticleTag: postTag,
						postArticleText: postText,
						itemid: itemid,
						itemimg: itemimg
					}),
					cache: false,
					success: function(resjson) {
						if(resjson.result) {
							if(resjson.res_msg.code)
								alert(resjson.res_msg.code + " : " + resjson.res_msg.message);
							else {
								$("#postArticleType").val(0);
								$("#currentPostType").attr("src", "./images/post_question_btn.png");
								$("#postItemOpt:visible").hide("slide", { direction: "up" }, 100);
								$("#postTagBox").val("");
								$("#postTextBox").val("");
								$("#postArticleItemID").val(0);
								$("#postArticleItemIMG").val("");
								watchDog();
								toggleTab(3);
							}
						}
						else alert(resjson.res_msg);
						$("#writepostnone").one("click", function() { writePost(); });
					},
					error: function(resjson) {
						alert("아이템  포스팅 실패");
						$("#writepostnone").one("click", function() { writePost(); });
					}
				});
			}
			break;
		default:
			alert("헉..여길 어떻게?");
			break;
	}
}

function getSkins(type) {
	// 1 my
	// 0 all
	// 2 favorite
	$.ajax({
		url: "./proxy/supporter/getSupporterSkin.php",
		data: "type=" + type,
		cache: false,
		success: function(res) {
			var resObj;
			if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function') resObj = JSON.parse(res);
			else resObj = eval('(' + res + ')');

			var api = $("div.scrollable").scrollable();
			api.getItemWrap().html("");
			$.each(resObj.skinlist, function(skin_order, skin) {
				var deleteButton = "";
				if(type == 1) deleteButton = "<div class='skindel' id='deleteSkin' onclick='deleteSkin(" + skin.id + "); return false;'></div>";
				else deleteButton = "";
				api.getItemWrap().append(
					"<div class='skin'>" +
						"<a href='http://me2day.net/" + skin.creatorid + "' target='_blank'>" + skin.creatornick + "</a>님" + deleteButton +
						"<img src='./skins/skin" + skin.id + "thumb.jpg' alt='" + skin.extension + "' title='" + skin.id + "'/>" +
					"</div>");
				});

				if(api.getSize() <= 5) api.getItemWrap().css("left","0px");
				api.setPage(0);
				api.move(0);
				api.reload();
				imageClick();
			}
		});
}

