if(typeof(bugs.ui) == "undefined") bugs.ui = {};

bugs.ui.DEFAULT_POPUP_OPTION = {
	title : null,
	css : "",
	modal : true,
	alertButtons : true,
	onInit : function(popup) {},
	onOk : function(popup) {return true;},
	onCancel : function(popup) {return true;},
	onHide : function() {}
};

bugs.ui.modalLayer = {
	layer : null,
	show : function() {
		if(!this.layer) {
			this.layer = $("<div></div>").attr("id", "_modalLayer").css({
				"z-index" : "99",
				"filter" : "alpha(opacity=30)",
				"opacity" : "0.2",
				"-moz-opacity" : "0.2",
				"position" : "absolute",
				"top" : 0,
				"left" : 0,
				"background-color" : "black"
			}).appendTo("body");
		}

		var width = $(document).width();
		var height = $(document).height();
		if($.browser.msie) {
			var bodyHeight = $("body").height();
			var windowHeight = $(window).height();
			
			height = windowHeight > bodyHeight ? windowHeight : bodyHeight;
		}

		this.layer.css({width : "100%", height : height}).show();
	},
	
	hide : function() {
		if(this.layer) this.layer.hide();
	}
};

bugs.ui.TITLE_LOGO = "LOGO";

bugs.ui.popup = bugs.create();
bugs.ui.popup.prototype = {
	type : "popup",
	
	initialize : function(msg, option) {
		this.msg = msg;
		this.option = bugs.overed(bugs.clone(bugs.ui.DEFAULT_POPUP_OPTION), option || {}); 

		this.makeLayer();
	},
	
	makeLayer : function() {
		if(typeof(this.msg) == "string") {
			this.layer = $(this.getHtml()).appendTo("body");
		}
		else {
			// 이미 있는 dom object로 레이어 생성
			this.layer = $(this.msg).appendTo("body");
			if(this.layer.find("h1").length) {
				if(this.layer.find("h1 span.logo").length) this.option.title = bugs.ui.TITLE_LOGO;
				else this.option.title = this.layer.find("h1").html();
			}
			
			var css = new Array();
			this.layer.eachClass(function(index, item) {
				if(item == "layerPopup" || item == "layerAlert") return;
				
				css.push(item);
			}.bind(this));

			if(css.length == 1) this.option.css = css[0];
			else this.option.css = css;
		}
		
		this.layer.find("div.btnClose a").click(function() {
			this.hide();
			return false;
		}.bind(this));

		this.makeButtons();
		
		this.onInit();
	},
	
	makeButtons : function() {
		this.layer.find("a[type=ok]").unbind("click").click(function() {
			if(this.option.onOk(this)) this.hide();
			return false;
		}.bind(this));
		
		this.layer.find("button[btnType=ok]").unbind("click").click(function() {
			if(this.option.onOk(this)) this.hide();
		}.bind(this));
		
		this.layer.find("a[type=cancel]").unbind("click").click(function() {
			if(this.option.onCancel(this)) this.hide();
			return false;
		}.bind(this));
	},
	
	getHtml : function() {
		var html = "<div class=\"layerPopup " + (!this.option.title ? "noTitle " : "") + this.option.css + "\" style=\"display:none;\">";
		
		if(this.option.title) {
			if(this.option.title == bugs.ui.TITLE_LOGO)
				html += "<h1><span class=\"logo\"><img src=\"" + g_urlFile + "/common/header/logo_bugsLayer.gif\" alt=\"Bugs!\" /></span></h1>";
			else
				html += "<h1>" + this.option.title + "</h1>";
		}
			
		html += "<div class=\"content\">" + this.msg + 
			"<div class=\"btnClose\"><a href=\"#\"><span>닫기</span></a></div>" +
			"</div>";
			
		if(!this.option.title) html += "<div class=\"layerBg bgTL\"></div>";
			
		html += "</div>";
		
		return html;
	},
	innerHtml : function(html) {
		if(typeof html != "undefined") {
			$("div.content", this.layer).children().not("div.btnClose").remove();
			$("div.content", this.layer).prepend(html);
			//$("div.content", this.layer).html(html);
		}
	},
	onInit : function() {
		this.option.onInit(this);
	},

	show : function(msg, option) {
		if(msg) {
			if(this.type == "alert")
				this.layer.find("div.content > p").html(msg);
			else {
				this.innerHtml(msg);
				this.makeButtons();
			}
		}
		
		this.option = bugs.overed(this.option, option || {});
		var css = this.option.css;

		this.layer.eachClass(function(index, item) {
			if(item == "layerPopup" || item == "layerAlert") return;
			
			$(this).removeClass(item);
		}.bind(this.layer));
		
		if(typeof(this.option.css) == "object") {
			for(var i in this.option.css)
				this.layer.addClass(this.option.css[i]);
		}
		else this.layer.addClass(css);

		//----- modal dialog 처리 -----------------------------------------------
		if(this.option.modal) bugs.ui.modalLayer.show();
		//---------------------------------------------------------------------
		
		var left = $(window).scrollLeft() + (($(window).width() - this.layer.width()) >> 1);
		var top = $(window).scrollTop() + (($(window).height() - this.layer.height()) >> 1);

		this.layer.css({left : left, top : top}).show();
		
		return this;
	},
	
	hide : function() {
		if(this.option.modal) bugs.ui.modalLayer.hide();
		if(this.option.onHide)	this.option.onHide();
		this.layer.hide(
			//$.proxy(function() { this.remove(); }, this)
		);
		
	},
	
	addModalMsg : function(id, msg) {
		var html = "" +
			"<div class=\"layerModal\" style=\"top:0px;display:none;\">" +
			"	<div class=\"content\">" +
			"		<p>" + msg + "</p>" +
			"		<div class=\"btnArea\"><span class=\"button typeME\"><a href=\"#\">확인</a></span></div>" +
			"	</div>" +
			"	<div class=\"layerBg bgTR\"></div>" +
			"	<div class=\"layerBg bgTL\"></div>" +
			"</div>";
		
		this.modalMsgList[id] = $(html).appendTo(this.layer);
	},
	
	showModalMsg : function(msg) {
		if(!this.modalMsgLayer) {
			var html = "" +
				"<div class=\"layerModal\" style=\"top:0px;display:none;\">" +
				"	<div class=\"content\">" +
				"		<p></p>" +
				"		<div class=\"btnArea\"><span class=\"button typeME\"><a href=\"#\">확인</a></span></div>" +
				"	</div>" +
				"	<div class=\"layerBg bgTR\"></div>" +
				"	<div class=\"layerBg bgTL\"></div>" +
				"</div>";
			
			this.modalMsgLayer = $(html).appendTo(this.layer).find("div.btnArea a").click(function() {
				this.modalMsgLayer.hide();
				return false;
			}.bind(this)).end();
		}
		
		var left = (this.modalMsgLayer.parent().width() - this.modalMsgLayer.width()) >> 1;
		var top = (this.modalMsgLayer.parent().height() - this.modalMsgLayer.height()) >> 1;
		
		this.modalMsgLayer.find("div.content p").html(msg).end().css({top : top, left : left}).show();
	},
	
	getLayer : function() {
		return this.layer;
	},
	
	reposition : function() {
		var left = $(window).scrollLeft() + (($(window).width() - this.layer.width()) >> 1);
		var top = $(window).scrollTop() + (($(window).height() - this.layer.height()) >> 1);

		this.layer.css({left : left, top : top});
	},
	remove : function() {
		if(this.layer) this.layer.remove();
		this.layer == null;
	}
};

bugs.ui.loadingLayer = bugs.create();
bugs.ui.loadingLayer.prototype = {
	html : '<div class="layerAlert layerLoading" style="left: 250px; top: 300px; display: none; border-width:1px; ">' +
		'<div class="content">' + 
		'<p><%=obj.title%></p>' + 
		'</div>' + 
		'<div class="layerBg bgTR"></div>' + 
		'<div class="layerBg bgTL"></div>' + 
		'</div>',
	initialize : function(title, option) {
		this.title = title;
		var tmp = new bugs.template(this.html, {title : title});
		this.layer = $(tmp.html()).appendTo("body");
		
	},
	show : 	function(css) {
		if(typeof css == "undefined") {
			css = {position : "absolute", left : "50%", top : 316, "margin-left" : -146};
		}	
		this.layer.css(css).show();
		
	},
	hide : function() {
		this.layer.hide();
	},
	remove : function() {
			this.layer.remove();
	}
}

bugs.ui.alert = bugs.create();
bugs.ui.alert.prototype = {
	getHtml : function() {
		var _layerClass = "layerAlert";
		if(typeof this.option.layerClass !="undefined") _layerClass = this.option.layerClass;
		
		var html = "<div class=\""+_layerClass+" " + this.option.css + "\" style=\"display:none;\">" + 
			"<div class=\"content\"><p></p>";
		
		if(this.option.alertButtons) {
			html +=
				"<div class=\"btnArea\">" +
				"<span class=\"button typeME\"><a href=\"javascript:void(0);\">확인</a></span>" + 
				"</div>";					
		}
		
		html += "</div>";
		
		if(this.option.alertButtons)
			html += "<div class=\"btnClose\"><a href=\"#\"><span>닫기</span></a></div>";
		
		html +=
			"<div class=\"layerBg bgTR\"></div>" +
			"<div class=\"layerBg bgTL\"></div>" +
			"</div>";
		
		return html;
	},
	
	onInit : function() {
		this.type = "alert";
		
		this.layer.find("div.content > p").html(this.msg);
		
		this.layer.find("span.button a").click(function() {
			this.hide();
			if(typeof(this.option.onOk) == "function") this.option.onOk(this);
			return false;
		}.bind(this));
		
		this.layer.find(".btnClose a").click(function() {
			this.hide();
			if(typeof(this.option.onCancel) == "function") this.option.onCancel(this);
			return false;
		}.bind(this));
		
		
		if(typeof this.option.onInit == "function") {
			this.option.onInit(this);
		}
	}
};
bugs.extend(bugs.ui.alert, bugs.ui.popup);

bugs.ui.showPopup = function(msg, option) {
	if(!bugs.ui._popup) bugs.ui._popup = new bugs.ui.popup(msg, option).show();
	else bugs.ui._popup.show(msg, bugs.overed(bugs.clone(bugs.ui.DEFAULT_POPUP_OPTION), option || {}));
};

bugs.ui.showAlert = function(msg, option) {
	if(!bugs.ui._alert) bugs.ui._alert = new bugs.ui.alert(msg, option).show();
	else bugs.ui._alert.show(msg, bugs.overed(bugs.clone(bugs.ui.DEFAULT_POPUP_OPTION), option || {}));
};

bugs.ui.showLoginAlert = function(code, option) {
	var opt = bugs.overed({
		msrl : "", 
		layerLogin : true,
		css : "layerLoginMsg"
	}, option || {});
	
	if (code != "OK") {
		switch (code) {
			case "VSTATC" : 
				if (!bugs.object.empty(opt.msrl)) {
					var popUp = window.open(g_urlMember + "/join/parentAgreeEmail/popup/" + opt.msrl, "parentAgree", "width=582,height=492,resizable=0");
					popUp.focus();
				}
				else {
					bugs.ui.showAlert("잘못된 로그인 정보입니다.", opt);
				}
				break;
			case "CHECK_NAME_SSN" : 
				var msg = "<p>"
						+ "	현재 회원님은 회원 가입 시 입력한 정보 중<br />" 
						+ "	로그인시 반드시 필요한 정보에 문제(누락)가 있어<br />" 
						+ "	로그인이 불가능합니다.<br /> "
						+ "	정상적으로 로그인을 하시려면<br />" 
						+ "	<a href=\"http://helpdesk.bugs.co.kr\">벅스고객센터</a>로 문의해 주시기 바랍니다."  
						+ "	</p> "
						+ "	<div class=\"btnArea\"><span class=\"button typeME\"><a href=\"javascript:void(0);\">확인</a></span></div>";
				bugs.ui.showPopup(msg, {title : "로그인 불가 안내", css : "layerLoginError", onInit : function(popup) {
					popup.getLayer().find("span.typeME a").click(function() {
						popup.hide();
						if(typeof(popup.option.onOk) == "function") popup.option.onOk();
						return false;
					});
				}});
				break;
			case "PAUSE" : 
				bugs.ui.showAlert("일시 정지된 아이디입니다.", opt);
				break;
			case "ALREADY_LOGGED" : 
				bugs.ui.showAlert("이미 로그인 되어 있습니다.", opt);
				break;			
			default :
				if(opt.layerLogin) {
					bugs.ui.showLoginLayer();
				}
				bugs.ui.showAlert("올바른 아이디/비밀번호를 찾아<br />입력하여 주세요.", opt);
				break;			
		}
	}
}

bugs.ui.showLoginLayer = function(option) {
	var opt = bugs.overed({
		rUrl : location.href,
		openWindow : false
	}, option || {});
	
	var saveId = bugs.cookie.get('saveId');
	if(!bugs.ui._loginLayer) {
		var msg = "" +
			"<div id=\"login\">" +
			"	<p class=\"msg\">로그인 하신 후 이용해주세요.</p>" +
			"	<fieldset>" +
			"	<legend>로그인</legend>" +			
			"	<form method=\"post\" id=\"frmLoginLayer\" name=\"frmLoginLayer\" action=\"" + g_urlMember + "/login/process\" onSubmit=\"return false;\">" +
			"		<input type=\"hidden\" id=\"rUrl\" name=\"rUrl\" value=\"" + opt.rUrl + "\"  />" +
			"		<div class=\"enterIDPW\">" +
			"			<label for=\"아이디\">아이디</label> <input type=\"text\" id=\"user_id\" name=\"user_id\" class=\"text default\" tabindex=\"101\" />" +
			"			<label for=\"비밀번호\">비밀번호</label><input type=\"password\" id=\"passwd\" name=\"passwd\" class=\"password default\" tabindex=\"102\" />" +
			"		</div>" +
			"		<button type=\"button\" class=\"btnLogin\" tabindex=\"103\">로그인</button>" +
			"		<div class=\"check\">" +
			"			<input type=\"checkbox\" class=\"checkbox\" id=\"checkSaveId\" name=\"checkSaveId\" value=\"1\" /><label for=\"keepUid\">아이디저장</label>" +
			"			<input type=\"checkbox\" class=\"checkbox\" id=\"checkSsl\" name=\"checkSsl\" value=\"1\" checked=\"checked\" disabled /><label for=\"security\">보안접속</label>" +
			"		</div>" +
			"	</form>" +
			"	</fieldset>" +			
			"	<span class=\"signup\"><a href=\"" + g_urlMember + "/join/memberMain\">회원가입</a></span>" +
			"	<span class=\"forgot\"><a href=\"" + g_urlMember + "/find/id\">아이디</a>/<a href=\"" + g_urlMember + "/find/pw\">비번 찾기</a></span>" +
			"</div>";
		
		bugs.ui._loginLayer = new bugs.ui.popup(msg, {title : bugs.ui.TITLE_LOGO, css : "layerLogin", onInit : function(popup) {
			var id = popup.layer.find("input.text");
			var passwd = popup.layer.find("input.password");
			
			bugs.focusNblur($("#user_id,#passwd"));
			$(id).focus(function () {
				if (!bugs.object.empty($(this).val())) $(this).removeClass("text");
				else $(this).addClass("text");
			}).blur(function () {
				if (!bugs.object.empty($(this).val())) $(this).removeClass("text");
				else $(this).addClass("text");
			});
			$(passwd).focus(function () {
				if (!bugs.object.empty($(this).val())) $(this).removeClass("password");
				else $(this).addClass("password");
			}).blur(function () {
				if (!bugs.object.empty($(this).val())) $(this).removeClass("password");
				else $(this).addClass("password");
			});
			
			if (!bugs.valid.empty(saveId)) {
				id.val(saveId).focus();
				$("#checkSaveId").attr("checked","checked");
			}
			$("#checkSaveId").click(function() {
				if ($(this).is(":checked")) {
					popup.showModalMsg( "<p><strong>현재 사용하시는 PC에<br />아이디를 저장하시겠습니까?</strong></p>" +
										"<p>PC방 등 공공장소에서는 개인정보가<br />유출될 수있으니 주의해 주시기 바랍니다.</p>");
				}
			});
			
			var _submitFunc = function() {
				if(bugs.valid.empty(id.val())) {
					popup.showModalMsg("아이디를 입력해주세요!");
					return false;
				}
				if(bugs.valid.empty(passwd.val())) {
					popup.showModalMsg("비밀번호를 입력해주세요!");
					return false;
				}

				var oDate = new Date();
				if ($("#checkSaveId").is(":checked")) {
					oDate.setDate(oDate.getDate() + 30);	
					bugs.cookie.set("saveId", id.val(), oDate, "/", "bugs.co.kr");
				}
				else {
					oDate.setDate(oDate.getDate() - 1);
					bugs.cookie.set("saveId", "", oDate, "/", "bugs.co.kr");
				}

				$("#frmLoginLayer").submit();
			};
			
			popup.layer.find("button.btnLogin").click(_submitFunc);
		 	popup.layer.find("input:text, input:password").keypress(function(event) {
				if (event.keyCode == '13') {
					_submitFunc();
				}
			});
		 	
		 	if(opt.openWindow) {
		 		popup.layer.find("span.signup a").openWindow(function() {
		 			popup.hide();
		 		});
		 		popup.layer.find("span.forgot a").openWindow(function() {
		 			popup.hide();
		 		});
		 	}
		}}).show();
	}
	else {
		bugs.ui._loginLayer.layer.find("#rUrl").val(opt.rUrl);
		bugs.ui._loginLayer.show();
	}
};


bugs.ui.alertAdultNotice = function() {
	var msg = "해당곡은 청소년 유해매체물로서 정보통신망<br />"+ 
				"이용 촉진 및 정보보호 등에 관한 법률 및<br />"+
				"청소년보호법의 규정에 의하여<br />"+ 
				"19세 미만의 청소년이 이용할 수 없습니다. ";
	var _alert = new bugs.ui.showAlert(msg, {css : "layerAdultNotice"});
	_alert.show();
}

//----- clipboard 카피 버튼 -------------------------------------------------------
bugs.ui.clipboardButtonManager = {
	id : 1,
	
	buttons : {},
	
	getUniqueId : function() {
		return bugs.ui.clipboardButtonManager.id++;
	},

	handleEvent : function(event, id) {
		if(this.buttons[id]) this.buttons[id].handleEvent(event);
	}
};

bugs.ui.clipboardButton = bugs.create();
bugs.ui.clipboardButton.prototype = {
	containerId : "BugsClipboardUtilContainer",
	
	id : 0,

	initialize : function(selector, option) {
		this.id = bugs.ui.clipboardButtonManager.getUniqueId();
		bugs.ui.clipboardButtonManager.buttons[this.id] = this;
		
		this.button = $(selector).mouseover(this.reposition.bind(this));
		this.option = bugs.overed({
			copyData : "",
			addClass : "",
			zIndex : 100,
			onComplete : function() {}
		}, option || {});
		
		if($("#" + this.containerId).length > 0) {
			this.container = $("#" + this.containerId);
			this.swf = $("#BugsClipboardUtil")[0];
			if(this.swf.tagName == "DIV") this.swf = null;
		}
		else {
			// firefox에서는 일단 화면에 플래쉬가 보여야 ExternalInterface.addCallback()이 되기 때문에
			// 일단 화면에 보이게끔 scrollTop으로 container를 생성함
			var top = $(document).scrollTop();
			this.container = $("<div id=\"" + this.containerId + "\"><div id=\"BugsClipboardUtil\"></div></div>").appendTo("body").css({position : "absolute", width : 10, height : 10, top : top, "z-index" : this.option.zIndex});
			
			var flashvars = {
				id : this.id,
				copyData : this.option.copyData,
				eventHandler : "bugs.ui.clipboardButtonManager.handleEvent"
			};
			
			var params = {
				wmode : "transparent",
				allowScriptAccess : "always" 
			};
			
			var attr = {
				id : "BugsClipboardUtil"
			};
			
			swfobject.embedSWF(g_urlSwf + "/BugsClipboardUtil.swf", "BugsClipboardUtil", "100%", "100%", "9.0.0", "expressInstall.swf", flashvars, params, attr, function(e) {
				if(e.success) this.swf = e.ref;
			}.bind(this));
		}
	},
	
	reposition : function() {
		if(!this.swf) {
			var swf = $("#BugsClipboardUtil")[0];
			if(!swf || swf.tagName == "DIV") return false;
			
			this.swf = swf;
		}
		
		var offset = this.button.offset();
		var width = this.button.outerWidth();
		var height = this.button.outerHeight();

		this.container.offset(offset).width(width).height(height);
		if(this.swf.setId) {
			this.swf.setId(this.id);
			this.swf.setCopyData(this.option.copyData);
		}
	},
	
	setCopyData : function(copyData) {
		this.option.copyData = copyData;
		
		if(!this.swf) {
			var swf = $("#BugsClipboardUtil")[0];
			if(!swf || swf.tagName == "DIV") return false;
			
			this.swf = swf;
		}
		
		if(this.swf.setCopyData)
			this.swf.setCopyData(this.option.copyData);
	},
	
	handleEvent : function(e) {
		//alert(e);
		switch(e) {
			case "mouseOver" :
				this.button.addClass(this.option.addClass);
				break;
			case "mouseOut" :
				this.button.removeClass(this.option.addClass);
				break;
			case "complete" :
				this.option.onComplete();
				break;
			case "mouseDown" :
				break;
			case "mouseUp" :
				break;
		}
	}
};
//-----------------------------------------------------------------------------