﻿/*
 * CjMenuUI 객체
 * 
 * Template의 상태를 현재 메뉴에 맞게 유지시켜주는 역할을 함.
 * 그외 공통적으로 모든화면에서 보여지는 Template의 각종 기능을 제어함.
 * 
 * Lee Won-Gyoon <richscript@gmail.com>, <@richscript>, <www.richscript.net>
 * e-motion Corp.
*******************************************************************************/

var CjMenuUI = {
	instanceName : "CjMenuUI",
	menuInstanceName : "CjMenu",
	userSession : {},
	event : new $js.lib.ObjectEvent(),
	currentMenu : null,
	currentSectionCode : "",
	currentSectionIndex : -1,
	msg : {
		  BAD_FRAME : "올바른 프레임 구조로 접근하지 않았습니다.\n올바른 경로로 접근해 주시기 바랍니다."
		, NO_CURRENT_MENU : "메뉴코드가 누락되었거나, 잘못된 메뉴코드입니다.\n다시 시도해 주십시오.\n\n※ 올바른 프레임 구조로 접근하지 않은 경우일 수 있습니다."
	},
	path : {
		  subMenuData : "/template/submenu.asp"
		  , sitemapData : "/template/sitemap.asp"
	},
	section : [],
	func : [],
	config : {
		  contentsHeight : 600
		, gnbSectionWidth : 150
		, gnbSectionHeight : 75
		, maxStandByTime : 5000
	},
	vars : {
		prevOverSectionIndex : 0
		, gnbTimer : null
		, gnbInitTimer : null
		, gnbCloseTimer : null
		, loadingTimer : null
		, resizeTimer : null
		, sitemapIndex : -1
	},
	nextResetParam : {
		menu : null
		, option : null
	},
	status : {
		isHeaderClosed : true
		, isSubMenuHeightChecked : false
		, isLoading : false
	},
	ids : {
		header : "#header"
		, headerBody : "#header-body"
		, headerOpenButton : "#header-open-button"
		, headerCloseButton : "#header-close-button"
		, gnbCurrent : "#gnb-current"
		, gnbCurrentSectionTitle : "#gnb-current-section-title"
		, gnbCurrentMenu : "#gnb-current-menu"
		, gnbCurrentMenuTitle : "#gnb-current-menu-title"
		, gnbSectionBg : "#gnb-section-bg"
		, gnbSectionFocus : "#gnb-section-focus"
		, gnbSectionMenu : "#gnb-section-menu"
		, gnbSub : "#gnb-sub"
		, gnbSubMenu : "#gnb-sub-menu"
		, gnbUtil : "#gnb-util"
		, footerHistoryMenu : "#footer-history-menu"
		, contents : "#contents"
		, mainCover : "#main-cover"
		, mainCoverLoading : "#main-cover-loading"
		, footer : "#footer"
		, userSessionBefore : ".user-session-before"
		, userSessionAfter : ".user-session-after"
		, sitemap : "#sitemap"
		, sitemapSectionContents : ".sitemap-section-contents"
		, footerCopyright : "#footer-copyright"
	},

	/**
	* CjMenuUI 객체가 생성되었는지 여부를 알려준다.
	* 프레임을 잘못찾거나 객체가없으면 Exception을 발생시킨다.
	* @return boolean
	*/
	isExist : function() {
		return true;
	},

	/**
	* CjMenu 객체를 가져온다.
	* @return ShMenu 객체
	*/
	getMenuInstance : function() {
		return window[this.menuInstanceName];
	},

	/**
	* Menu 객체를 가져온다.
	* @param _menuCode 메뉴코드
	* @return Menu 객체
	*/
	getMenuFromMenuCode : function(_menuCode) {
		return this.getMenuInstance().getMenuFromMenuCode(_menuCode);
	},
	
	/**
	* Menu 객체를 가져온다.
	* @param _skinCode 메뉴코드
	* @return Menu 객체
	*/
	getMenuFromSkinCode : function(_skinCode) {
		return this.getMenuInstance().getMenuFromSkinCode(_skinCode);
	},

	/**
	* 하위메뉴를 탐색하여 URL이 존재하는 메뉴가 나올면 리턴한다.
	* @param _menu 메뉴객체
	* @return Menu 메뉴객체
	*/
	getValidMenu : function(_menu) {
		return this.getMenuInstance().getValidMenu(_menu);
	},

	/**
	* 현재 보여질 Root Menu를 리턴한다.
	* @return Root Menu Array 객체
	*/
	getRootMenu : function() {
		return this.getMenuInstance().menu;
	},

	/**
	* 해당 메뉴의 URL을 옵션사항에 맞게 변경하여 리턴한다.
	* @param _menu 메뉴객체
	* @param _option 옵션
	* @return Menu 해당URL
	*/
	getMenuUrl : function(_menu, _option) {
		return this.getMenuInstance().getMenuUrl(_menu, _option);
	},

	/**
	* 현재 보여질 1 Depth Menu를 리턴한다.
	* @param _index 메뉴 인덱스
	* @return Section Menu Array 객체
	*/
	getSectionMenu : function(_index) {
		return this.getMenuInstance().menu[_index];
	},

	/**
	* 현재 보여질 1 Depth Menu를 리턴한다.
	* @param _index 메뉴 인덱스
	* @return Section Menu Array 객체
	*/
	getValidCurrentSectionIndex : function() {
		return (this.currentSectionIndex<this.section.length)?this.currentSectionIndex:-1;
	},

	/**
	* 다음 실행할 작업이 있으면 실행한다.
	* @return Void
	*/
	doNext : function() {
		if (this.func.length>0) {
			try {
				this.func[0]();
			} catch(e) {}
			this.func[0] = null;
			this.func = this.func.compact();
		}
	},

	/**
	* 다음 실행할 작업을 등록한다.
	* @param _func 다음 실행할 Function
	* @return Void
	*/
	addNext : function(_func) {
		this.func.push(_func);
	},

	/**
	* 다음 실행할 작업을 초기화 한다.
	* @param _func 다음 실행할 Function
	* @return Void
	*/
	resetNext : function(_func) {
		for (var i=0; i<this.func.length; i++) {
			this.func[i] = null;
		}
		this.func = [];
		this.func.push(_func);
	},

	/**
	* 상단메뉴의 1뎁스 HTML을 생성한다.
	* @return Void
	*/
	createSectionHtml : function() {
		for (var i=0; i<this.section.length; i++) {
			var sectionTitle = this.getSectionMenu(i).title.escapeXml();
			var sectionMenuCode = this.getSectionMenu(i).menuCode.escapeXml();
			var url = (!$js.browser.isMobile) ? "#"+sectionMenuCode+"/" : "#";
			$(this.ids.gnbSectionBg).append('<div><img src="'+this.section[i].bgSrc+'" width="155" height="75" border="0"></div>');
			$(this.ids.gnbSectionMenu).append('<a sectionIndex="'+i+'" id="'+sectionMenuCode+'" href="'+url+'" class="off" style="color:'+this.section[i].color1+';">'+sectionTitle+'</a>');
			
		}
		$(this.ids.gnbSectionFocus).append('<div class="bg-off" style="height:'+((this.section.length-1)*this.config.gnbSectionHeight)+'px;"></div>');
		$(this.ids.gnbSectionFocus).append('<div class="bg-on"></div>');
		$(this.ids.gnbSectionFocus).append('<div class="bg-off" style="height:'+((this.section.length-1)*this.config.gnbSectionHeight)+'px;"></div>');
	},

	/**
	* 하단 히스토리 설정
	* @return void
	*/
	resetFooterHistory : function() {
		var menuCodes = this.currentMenu.parentMenuCodes.concat();
		menuCodes.push(this.currentMenu.menuCode);
		var html = '';
		if (this.getMenuFromMenuCode(menuCodes[0])) {
			for (var i=0; i<menuCodes.length; i++) {
				var menu = this.getMenuFromMenuCode(menuCodes[i]);
				html += '<li><a menuCode="'+menu.menuCode.escapeXml()+'" href="/">'+menu.title.escapeXml()+'</a></li>';
				menu = null;
			}
		}
		$(this.ids.footerHistoryMenu).html(html);
		$.each($(this.ids.footerHistoryMenu+" > li > a"), function(i, each) {
			var menuCode = $(each).attr("menuCode");
			$(each).attr("href", "#"+menuCode+"/").click(function(e) {
				e.preventDefault();
				openMenu(menuCode);
			});
		});
		menuCodes = null;
	},

	/**
	* 상단 타이틀 설정
	* TO-DO : 현재 메뉴 정보 가져와서 자동으로 반영하도록 수정
	* @return void
	*/
	resetHeaderTitle : function(_index, _titleArray) {
		if (_index==undefined&&_titleArray==undefined) {
			_titleArray = [];
			if (this.currentMenu&&this.currentMenu.parentMenuCodes) {
				for (var i=0; i<this.currentMenu.parentMenuCodes.length; i++) {
					_titleArray.push(this.getMenuFromMenuCode(this.currentMenu.parentMenuCodes[i]).title);
				}
				_titleArray.push(this.currentMenu.title);
				_index = this.currentMenu.sectionIndex;
			} else {
				_index = -1;
			}
		}
		var titles = [];
		var index = (_index<this.section.length) ? _index : -1;
		var height = this.config.gnbSectionHeight;
		var styleColor = (index>-1) ? " style='color:"+this.section[index].color2+";' " : "";
		for (var i=0; i<4; i++) {
			titles.push((_titleArray[i]!=undefined)?(""+_titleArray[i]).escapeXml():"");
		}
		if (titles[0]!=""&&titles[1]=="") {
			if (this.section[index]&&this.section[index].slogan!="") {
				titles[1] = this.section[index].slogan;
			}
		}
		if (titles[0]==""&&titles[1]=="") {
			titles[1] = "CJ For Better Life";
		}
		if (this.status.isHeaderClosed) {
			$(this.ids.gnbSectionBg).animate({top: height*(-1)*(index+1)});
		}
		
		var sectionTitleId = this.ids.gnbCurrentSectionTitle;
		var menuTitleId = this.ids.gnbCurrentMenuTitle;
		var ui = this.instanceName;
		(function() {
			var _titles = titles;
			$(sectionTitleId).animate({top: height}, "fast", function() {
				$(this).html(_titles[0]).css("top",(-1)*height).animate({top: 0});
			});
			$(menuTitleId).animate({bottom: (-1)*height}, "fast", function() {
				var titleHtml = "";
				if (_titles[1]!="") {
					titleHtml = (_titles[2]!="")
								? '<span class="menu-title-super" '+styleColor+'>'+_titles[1]+'</span><span class="menu-title">'+_titles[2]
								: '<span class="menu-title only">'+_titles[1];
					if (_titles[3]!="") {
						titleHtml += '<span class="menu-title-detail">'+_titles[3]+'</span>';
					}
					titleHtml += '</span>';
				}
				$(this).html(titleHtml).css("bottom",height).animate({bottom: 0},function() {
					window[ui].doNext();
				});
			});
		})();
		
		_titleArray = titles = null;
	},

	/**
	* 사용자 로그인 정보에 맞춰 관련 Element를 변경한다.
	* @param _isLogin (Boolean) 로그인여부
	* @return void
	*/
	updateUserSession : function(_isLogin) {
		this.userSession.isLogin = _isLogin;
		if (this.userSession.isLogin) {
			$(this.ids.userSessionBefore).hide();
			$(this.ids.userSessionAfter).show();
		} else {
			$(this.ids.userSessionBefore).show();
			$(this.ids.userSessionAfter).hide();
		}
	},

	/**
	* 상단메뉴의 2뎁스 이하 HTML을 생성한다.
	* @return Void
	*/
	loadSubMenuHtml : function() {
		$.ajax({
			context: this,
			type: "get",
			url: this.path.subMenuData,
			data: "_temp="+(new Date()).getTime(),
			dataType: "text",
			success: function(_s){
				var html = _s.split("<!--{GNB_SUBMENU_END}-->")[0]
							.split("<!--{SUBMENU}-->").slice([1]);
				$(this.ids.gnbCurrentMenuTitle).html("");
				for (var i=0; i<this.section.length; i++) {
					$(this.ids.gnbSubMenu).append('<div>' + html[i].trim() + '</div>');
				}
				$.each($(this.ids.gnbSubMenu+" a"), function(i, each) {
					var menuCode = $(each).attr("id");
					if (menuCode.indexOf("M")==0) {
						$(each).attr("href", "#"+menuCode+"/");
						$(each).click(function(e) {
							e.preventDefault();
							openMenu(menuCode);
							return false;
						});
					} else if ($(each).hasClass("empty")) {
						$(each).click(function(e) {
							e.preventDefault();
							return false;
						});
					}
				});
				
				$(this.ids.gnbSub).show();
				var minHeight = this.config.gnbSectionHeight * this.section.length;
				$.each($(this.ids.gnbSubMenu+" > div"), function(i, each) {
					$(each).css("height", Math.max($(each).outerHeight(),minHeight));											   
				});
				$(this.ids.gnbSub).hide();
				this.activeHeader();
			},
			error: function(event, request, settings) {
				this.resetHeaderTitle(10, ["", "Menu data Error. "+event.status, "다시 시도중입니다.", "메뉴정보 가져오기 실패."]);
			},
			complete: function() {
			}
		});
	},

	/**
	* 하단의 각 섹션별 사이트맵 HTML을 생성한다.
	* @return Void
	*/
	loadSitemapHtml : function() {
		$.ajax({
			context: this,
			type: "get",
			url: this.path.sitemapData,
			data: "_temp="+(new Date()).getTime(),
			dataType: "text",
			success: function(_s){
				var html = _s.split("<!--{GNB_SUBMENU_END}-->")[0]
							.split("<!--{SUBMENU}-->").slice([1]);
				for (var i=0; i<this.section.length; i++) {
					$(this.ids.sitemap).append('<div class="'+this.ids.sitemapSectionContents.substring(1)+'">' + html[i].trim() + '</div>');
				}
				this.resetSitemap();
			},
			error: function(event, request, settings) {
			},
			complete: function() {
			}
		});
	},
	
	/**
	* 현재 보고있는 섹션에 맞는 하단 사이트맵을 보여준다.
	* @return Void
	*/
	resetSitemap : function() {
		var focusIndex = this.currentSectionIndex;
		if (this.currentMenu.depth==1) {
			focusIndex = -1;
		}
		if (this.vars.sitemapIndex!=focusIndex) {
			$.each($(this.ids.sitemapSectionContents), function(i, each) {
				$(each).css("display", (focusIndex==i)?"block":"none");
			});
			this.vars.sitemapIndex = focusIndex;
		}
	},

	/**
	* 하단 사이트맵을 노출한다.
	* @return Void
	*/
	showSitemap : function() {
		$(this.ids.sitemap).css("display", "block");
		$(this.ids.footerCopyright).css("display", "block");
	},

	/**
	* 하단 사이트맵을 숨긴다.
	* @return Void
	*/
	hideSitemap : function() {
		$(this.ids.sitemap).css("display", "none");
		$(this.ids.footerCopyright).css("display", "none");
	},

	/**
	* 지정한 컨텐츠를 불러온다.
	* @return Void
	*/
	loadContents : function(_url) {
		$(window).unbind(".eachContents");
		var url = (_url==undefined||_url=="") ? this.currentMenu.url : _url;
		url = url.appendParameter("menuCode="+this.currentMenu.menuCode);
		var cmdParam = (this.currentMenu) ? "menuCode="+this.currentMenu.menuCode : "";
		this.event.onEvent(this, "loadContents", cmdParam, url);
		var frameName = "F"+(new Date()).getTime();
		var html = '';
		html += '<div style="width:100%;height:auto;padding:0;"><iframe';
		html += ' style="position:relative;left:0;top:0;background-color:#fff;"';
		html += ' name="'+frameName+'"';
		html += ' id="'+frameName+'"';
		html += ' src="about:blank"';
		html += ' width="100%"';
		html += ' height="'+this.config.contentsHeight+'"';
		html += ' marginwidth="0"';
		html += ' marginheight="0"';
		html += ' hspace="0"';
		html += ' vspace="0"';
		html += ' scrolling="no"';
		html += ' frameborder="0"';
		html += '></iframe></div>';
		if ($(this.ids.contents).children().length>1) {
			for (var i=1; i<$(this.ids.contents).children().length; i++) {
				$(this.ids.contents).children().eq(i).remove();
			}
		}
		$(this.ids.contents).append(html);
		try {
			window.frames[frameName].location.replace(url);
		} catch(e) {
			open(url, frameName, "");
		}
		
		var tempHeight = $(this.ids.contents).children().eq(0).outerHeight();
		$(this.ids.contents).children().eq(0).css({
			position : "absolute"
			, zIndex : 2
			, height : tempHeight
			, overflow : "hidden"
			, paddingRight : "4px"
			, backgroundColor : "#ffffff"
			, background : "url(/img/richscript/ui/template/contents.shadow.bg.png) repeat-y"
			, backgroundPosition : "right top"
		});
		$(this.ids.contents).css({height:tempHeight});
	},
	
	displayNewContents : function() {
		if (this.vars.loadingTimer) {
			clearTimeout(this.vars.loadingTimer);
		}
		if ($(this.ids.contents).children().length>1) {
			var ui = this.instanceName;
			var tarX = (-1)*$(this.ids.contents).children().eq(0).outerWidth();
			$(this.ids.contents).children().eq(0).stop().animate({left:tarX}, 900, "easeInExpo", function() {
				/*
				var frameName = $(this).children().eq(0).attr("name");
				if (frameName!=undefined&&frameName!="") {
					try {
						window.frames[frameName].location.replace("about:blank");
					} catch(e) {
					}
				}
				*/
				$(window[ui].ids.contents).css({height:"auto"});
				$(this).remove();
				window[ui].hideMainCover();
				window[ui].resetSitemap();
				window[ui].doNext();
			});
		} else {
			this.doNext();
		}
	},

	/**
	* 상단 영역의 메뉴 전체보기 모드를 닫는다.
	* @return Void
	*/
	closeHeader : function(_isTitleChanged) {
		clearTimeout(this.vars.gnbCloseTimer);
		var ui = this.instanceName;
		this.vars.gnbCloseTimer = setTimeout(function() {
			window[ui]._closeHeader(_isTitleChanged);
		},400);
	},
	_closeHeader : function(_isTitleChanged) {
		clearTimeout(this.vars.gnbCloseTimer);
		if (this.status.isHeaderClosed==false) {
			var ui = this.instanceName;
			var minHeight = this.config.gnbSectionHeight;
			var prevOverSectionIndex = this.vars.prevOverSectionIndex;
			$(this.ids.headerCloseButton).hide();
			$(this.ids.gnbSectionFocus).stop().hide();
			$(this.ids.gnbSectionMenu).hide();
			$(this.ids.gnbSectionBg).stop();
			/*
			$.each($(this.ids.gnbSectionMenu+" > a"), function(i, each) {
				$(each).stop().removeClass("on").removeClass("over").addClass("off")
				.css("color", window[ui].section[i].color1);
			});
			*/
			this.status.isHeaderClosed = true;
			$(this.ids.headerBody).stop().animate({height:minHeight}, function() {
				var index = window[ui].getValidCurrentSectionIndex();
				$(window[ui].ids.gnbSub).hide();
				$(window[ui].ids.gnbUtil).hide();
				$(window[ui].ids.gnbSectionBg).stop().animate({top: minHeight*(-1)*(index+1)});
				/* 상단 타이틀이 변경되었을 경우 */
				if (_isTitleChanged==true) {
					$(window[ui].ids.gnbCurrent).css("top",0);
					window[ui].resetHeaderTitle();
				} else {
					$(window[ui].ids.gnbCurrent).stop().animate({top:0});
				}
			});
		}
	},

	/**
	* 상단메뉴 활성화
	* @return void
	*/
	activeHeader : function() {
		var ui = this.instanceName;
		var sectionHeight = this.config.gnbSectionHeight;
		var sectionLength = this.section.length;
		var maxHeaderBodyHeight = sectionHeight * sectionLength;
		
		var openHeaderFunc = function(e) {
			e.preventDefault();
			window[ui].status.isHeaderClosed = false;
			clearTimeout(window[ui].vars.gnbCloseTimer);
			var currentSectionIndex = window[ui].getValidCurrentSectionIndex();
			if (currentSectionIndex<0) currentSectionIndex = 0;
			$(window[ui].ids.gnbSectionBg).stop().animate({top: sectionHeight*(-1)}, "fast", function() {
				$(window[ui].ids.gnbUtil).show();
				$(window[ui].ids.headerCloseButton).show().animate({backgroundColor: window[ui].section[currentSectionIndex].buttonColor});
				$(window[ui].ids.gnbSectionMenu).show();
				$(window[ui].ids.gnbSectionFocus).stop().css("top",(-1)*sectionHeight*(sectionLength-currentSectionIndex-1)).fadeTo("fast",1.0);
				$(window[ui].ids.gnbSub).show();
				$(window[ui].ids.gnbSubMenu).stop().css({top: $(window[ui].ids.gnbSubMenu+" > div").eq(currentSectionIndex).position().top*(-1)});
				var tarH = Math.max($(window[ui].ids.gnbSubMenu+" > div").eq(currentSectionIndex).outerHeight(),maxHeaderBodyHeight);
				if ($(window[ui].ids.headerBody).height()!=tarH&&!window[ui].status.isHeaderClosed) {
					$(window[ui].ids.headerBody).stop().animate({height:tarH}, "fast");
				}
				$.each($(window[ui].ids.gnbSectionMenu+" > a"), function(i, each) {
					if (i!=currentSectionIndex) {
						$(each).stop().removeClass("on").removeClass("over").addClass("off").css("color", window[ui].section[i].color1);
					} else {
						$(each).stop().removeClass("off").removeClass("over").addClass("on").css("color","#ffffff");
					}
				});
				window[ui].vars.prevOverSectionIndex = currentSectionIndex;
			});
			$(window[ui].ids.gnbCurrent).stop().animate({top: sectionHeight*(-1)}, "fast");
			$(window[ui].ids.headerBody).stop().animate({height: maxHeaderBodyHeight}, "fast");
		};
		
		/* 상단 메뉴 열기 버튼 Event 적용 */
		$(this.ids.headerOpenButton).bind("click mouseenter",openHeaderFunc);
		$(this.ids.gnbCurrentMenu).bind("click mouseenter",openHeaderFunc);
		
		
		/* 상단 메뉴 1Depth Event 적용 */
		var focusSection = function(e) {
			if (window[ui].vars.gnbInitTimer!=null) {
				clearTimeout(window[ui].vars.gnbInitTimer);
				window[ui].vars.gnbInitTimer = null;
			}
			if ($js.browser.isMobile) {
				e.preventDefault();
				if (window[ui].vars.prevOverSectionIndex==parseInt($(this).attr("sectionIndex"),10)) {
					openMenu($(this).attr("id"));
					return false;
				}
			}
			var _each = this;
			if ($(window[ui].ids.gnbSectionFocus).css("opacity")==1) {
				clearTimeout(window[ui].vars.gnbTimer);
				var prevSectionIndex = window[ui].vars.prevOverSectionIndex;
				(function() {
					var each = _each;
					window[ui].vars.gnbTimer = setTimeout(function() {
						var sectionIndex = parseInt($(each).attr("sectionIndex"),10);
						if (prevSectionIndex!=sectionIndex) {
							$(window[ui].ids.gnbSectionMenu+" > a").eq(prevSectionIndex).stop().removeClass("on").removeClass("over").addClass("off").animate({
								color : window[ui].section[prevSectionIndex].color1
							});
							window[ui].vars.prevOverSectionIndex = sectionIndex;
							var tarY = $(each).position().top - (maxHeaderBodyHeight-sectionHeight);
							$(window[ui].ids.gnbSectionFocus).stop();
							$(each).removeClass("off").addClass("over");
							$(window[ui].ids.gnbSectionFocus).animate({top: tarY}, function() {
								$(each).removeClass("over").addClass("on");
							});
							$(each).stop().animate({color:"#FFFFFF"});
							$(window[ui].ids.headerCloseButton).stop().animate({backgroundColor: window[ui].section[sectionIndex].buttonColor});
							$(window[ui].ids.gnbSubMenu).stop().animate({top:$(window[ui].ids.gnbSubMenu+" > div").eq(sectionIndex).position().top*(-1)}, function() {
								var tarH = Math.max($(window[ui].ids.gnbSubMenu+" > div").eq(sectionIndex).outerHeight(),maxHeaderBodyHeight);
								if ($(window[ui].ids.headerBody).height()!=tarH&&!window[ui].status.isHeaderClosed) {
									$(window[ui].ids.headerBody).stop().animate({height:tarH}, "fast");
								}
							});
						}
					}, 50);
				})();
			} else {
				(function() {
					var each = _each;
					var evt = e;
					window[ui].vars.gnbInitTimer = setTimeout(function(){
						$(each).trigger("mouseenter", evt);
					}, 10);
				})();
			}
			_each = e = null;
		};
		if (!$js.browser.isMobile) {
			$(this.ids.gnbSectionMenu+" > a").mouseenter(focusSection);
			$(this.ids.gnbSectionMenu+" > a").click(function(e) {
				e.preventDefault();
				openMenu($(this).attr("id"));
			});
		} else {
			$(this.ids.gnbSectionMenu+" > a").click(focusSection);
		}
		
		
		/* 상단 메뉴 닫기 버튼 Event 적용 */
		$(this.ids.headerCloseButton).click(function(e) {
			e.preventDefault();
			window[ui]._closeHeader();
		}).css("visibility","visible").hide();
		
		$(this.ids.header).bind("mouseleave",function() {
			window[ui].closeHeader();
		});
		$(this.ids.header).bind("mouseenter",function() {
			clearTimeout(window[ui].vars.gnbCloseTimer);
		});
		
		
		/* <a/> 클릭 후 테두리 제거 */
		$("a").click(function(e) {
			$(this).blur();
		});
		
		/* 상단 타이틀 초기화 */
		this.resetHeaderTitle();
		this.focusSubMenu();
	},
	
	focusSubMenu : function(_menu) {
		var menu = (_menu==undefined) ? this.currentMenu : _menu;
		var prevMenuCodes, menuCodes;
		if (menu) {
			if (this.currentMenu.menuCode!=menu.menuCode) {
				var prevMenuCodes = this.currentMenu.parentMenuCodes.concat();
				prevMenuCodes.push(this.currentMenu.menuCode);
				for (var i=0; i<prevMenuCodes.length; i++) {
					$("#"+prevMenuCodes[i]).removeClass("on");
				}
			}
			var menuCodes = menu.parentMenuCodes.concat();
			menuCodes.push(menu.menuCode);
			for (var i=0; i<menuCodes.length; i++) {
				$("#"+menuCodes[i]).addClass("on");
			}
		}
		menu = _menu = menuCodes = prevMenuCodes = null;
	},
	
	resizeMainCover : function() {
		$(this.ids.mainCover).css({width : $js.browser.maxW(), height : $js.browser.maxH()});
		$(this.ids.mainCoverLoading).css({width : $(this.ids.contents).outerWidth(), height : Math.min($(this.ids.contents).outerHeight()+this.config.gnbSectionHeight,$js.browser.screenH())});
	},
	
	showMainCover : function() {
		this.resizeMainCover();
		$(this.ids.mainCover).show();
		$(this.ids.mainCoverLoading).show();
		var ui = this.instanceName;
		/*
		$(window).bind("resize.mainCover", function() {
			window[ui].resizeMainCover();
		});
		*/
		this.vars.loadingTimer = setTimeout(function() {
			window[ui].displayNewContents();
		}, this.config.maxStandByTime);
	},
	
	hideMainCover : function() {
		$(this.ids.mainCover).hide();
		$(this.ids.mainCoverLoading).hide();
		this.status.isLoading = false;
		this.doNextReset();
		/*
		$(window).unbind("resize.mainCover");
		*/
	},
	
	setFullScreenMode : function(_minWidth, _minHeight) {
		CjSideboard.inActive();
		this.hideSitemap();
		var minWidth = (_minWidth==undefined) ? 880 : Math.max(Math.toInt(_minWidth),880);
		var minHeight = (_minHeight==undefined) ? 600 : Math.max(Math.toInt(_minHeight),600);
		var ui = this.instanceName;
		var resizeFrame = function() {
			var width = minWidth;
			var height = minHeight;
			clearTimeout(window[ui].vars.resizeTimer);
			window[ui].vars.resizeTimer = setTimeout(function() {
				var tarW = Math.max($(window).width(), width);
				var tarH = Math.max($js.browser.screenH()-window[ui].config.gnbSectionHeight-$(window[ui].ids.footer).outerHeight(), height);
				$("#main").stop().animate({width:tarW}, function() {
					//$(this).css("width", "100%");
				});
				$("#contents iframe").stop().animate({height:tarH});
			}, 100);
		};
		resizeFrame();
		$(window).bind("resize.fullscreen", resizeFrame);
		$("#go-top").hide();
		this.getMenuInstance().event.on("openMenu.fullScreen", function(_menu, _option) {
			window[ui].setNormalScreenMode();
		});
	},
	
	setNormalScreenMode : function() {
		this.showSitemap();
		clearTimeout(this.vars.resizeTimer);
		$(window).unbind("resize.fullscreen");
		this.getMenuInstance().event.off("openMenu.fullScreen");
		$("#contents iframe").css({width:"100%"});
		if (!$js.browser.isMobile) {
			$("#contents iframe").stop().animate({height:600});
			$("#main").stop().animate({width:880}, function() {
				$("#main").css("overflow", "visible");
				CjSideboard.active();
				$("#go-top").show();
			});
		} else {
			$("#main").css({width:880});
			$("#main").css("overflow", "visible");
			CjSideboard.active();
			$("#go-top").show();
		}
	},
	
	reset : function(_menu, _option) {
		if (!this.status.isLoading) {
			this.status.isLoading = true;
			window.scroll(0,0);
			this.focusSubMenu(_menu);
			this.currentMenu = _menu;
			this.currentSectionCode = _menu.sectionCode;
			this.currentSectionIndex = _menu.sectionIndex;
			this.showMainCover();
			if (!this.status.isHeaderClosed) {
				this._closeHeader(true);
			} else {
				this.resetHeaderTitle();
			}
			this.resetFooterHistory();
			
			/* URL 적용 */
			var ui = this.instanceName;
			var url = this.getMenuUrl(_menu, _option);
			(function() {
				var _ui = ui;
				var _url = url;
				window[_ui].addNext(function() {
					window[_ui].loadContents(_url);
				});
			})();
		} else {
			this.setNextReset(_menu, _option);
		}
	},
	
	setNextReset : function(_menu, _option) {
		this.nextResetParam.menu = _menu;
		this.nextResetParam.option = _option;
	},
	
	doNextReset : function() {
		if (this.nextResetParam.menu!=null) {
			this.reset(this.nextResetParam.menu, this.nextResetParam.option);
			this.nextResetParam.menu = null;
			this.nextResetParam.option = null;
		}
	},

	/**
	* 초기화
	* @return void
	*/
	initialize : function() {
		var ui = this.instanceName;
		
		
		/* GNB에 노출할 Section별 색상 */
		this.section.push({
			  slogan: "글로벌 생활문화기업 CJ제일제당"
			, color1: "#1e66b0", color2: "#0998ff", buttonColor: "#1e66b0"
			, bgSrc: "/img/richscript/ui/template/header/gnb.section.bg.00.gif"
		});
		this.section.push({
			  slogan: "건강과 행복을 드리는 CJ제일제당 브랜드"
			, color1: "#f18513", color2: "#f79a3f", buttonColor: "#f57200"
			, bgSrc: "/img/richscript/ui/template/header/gnb.section.bg.01.gif"
		});
		this.section.push({
			  slogan: ""
			, color1: "#f1190e", color2: "#f24843", buttonColor: "#f40f16"
			, bgSrc: "/img/richscript/ui/template/header/gnb.section.bg.02.gif"
		});
		this.section.push({
			  slogan: "CJ제일제당의 소중한 친구 유-모니투어"
			, color1: "#ba347d", color2: "#c95c9e", buttonColor: "#ba347d"
			, bgSrc: "/img/richscript/ui/template/header/gnb.section.bg.03.gif"
		});
		
		this.createSectionHtml();
		this.loadSubMenuHtml();
		this.loadSitemapHtml();
		
		
		/* 메뉴 객체에서 사용자 로그인 정보가 변경되면 UI도 자동으로 변경되도록 이벤트 적용 */
		this.getMenuInstance().event.on("updateUserSession", function(_isLogin) {
			window[ui].updateUserSession(_isLogin);
		});
		this.updateUserSession(this.getMenuInstance().userSession.isLogin);
		
		/* 메뉴 바로가기 URL로 접근 시 해당 메뉴를 로딩함. 존재하지 않는 메뉴이면 Home을 로딩 */
		var hash = (""+location.hash).trim().substring(1);
		var menuCode = hash.split("/")[0];
		var menu = this.getValidMenu(this.getMenuFromMenuCode(menuCode));
		if (menu==null) {
			menu = this.getMenuInstance().getHomeMenu();
		}
		var param = hash.replace(menu.menuCode+"/","").substring(1);
		var url = menu.url.appendParameter(param);
		if (param.indexOf("/")==0) {
			url = param;
		}
		this.currentMenu = menu;
		this.currentSectionCode = menu.sectionCode;
		this.currentSectionIndex = menu.sectionIndex;
		this.loadContents(url);
		this.resetHeaderTitle();
		this.resetFooterHistory();
		
		/* 히스토리 등록 */
		CjCommand.set(this.menuInstanceName, "openMenu", menu, param);
		
		menu = null;
		
		
		/* 메뉴에 맞춰 UI 및 컨텐츠 로딩하는 이벤트 적용 */
		this.getMenuInstance().event.on("openMenu", function(_menu, _option) {
			if (CjSideboard&&(!CjSideboard.status.isClosed||CjSideboard.status.isMovingForClosed)) {
				CjSideboard.close(function() {
					var menu = _menu;
					var option = _option;
					window[ui].reset(menu, option);
				});
			} else {
				window[ui].reset(_menu, _option);
			}
		});
	}
};


/* 모든 DOM(Document Object Model) 의 해석을 완료하면.. onLoad 와는 다름. */
$(function() {
	
	/* Template UI 초기화 */
	CjMenuUI.initialize();
	
	
	/* 상단 언어 선택 레이어에 Event 적용 */
	var hideUtilLocalLayer = function() {
		$("#gnb-top-util-local").slideUp("fast");
		$(document).unbind("click", hideUtilLocalLayer);
		$("#header-open-button, #gnb-current-menu").unbind("mouseenter", hideUtilLocalLayer);
	};
	$(".top-util-local").click(function(e) {
		e.preventDefault();
		var x = $("#gnb-top-util-menu .top-util-local").position().left;
		$("#gnb-top-util-local").css({left:x-35}).slideDown("fast", function() {
			$(document).bind("click", hideUtilLocalLayer);
			$("#header-open-button, #gnb-current-menu").bind("mouseenter", hideUtilLocalLayer);
		});
	});
	
	/* Family Site 버튼에 Event 적용 */
	$("#familysite-btn").click(function(e) {
		e.preventDefault();
		return false;
	});
	$("#familysite-btn").toggle(function() {
		$("#familysite").slideDown("fast", function() {
			var tarH = $(document).height()-$(window).height();
			$("html,body").animate({scrollTop:tarH}, "fast");
			$("#familysite-btn").addClass("on");
		});
	}, function() {
		$("#familysite").slideUp("fast", function() {
			$("#familysite-btn").removeClass("on");
		});
	});
	
	/* 상단 로고에 링크 걸기 */
	$("#header-logo").click(function(e) {
		e.preventDefault();
		openHome();
		return false;
	});
	
	/* 히스토리 홈에 링크 걸기 */
	$(".history-home").click(function(e) {
		e.preventDefault();
		openHome();
		return false;
	});
	
	/* Top 버튼에 Event 적용 */
	$("#go-top").attr("href","javascript:;").click(function(e) {
		e.preventDefault();
		window.scroll(0,0);
		return false;
	});
	
	/* Top 버튼 노출 */
	$("#go-top").css({display:"block",top:$js.browser.screenH()-130}).show();
	$(window).bind("scroll resize", function() {
		$("#go-top").stop().animate({top:$js.browser.scrollY()+$js.browser.screenH()-130}, 500);
	});
});


