﻿/********************************************************************************************************
	[개발 추가영역 - 균]
		- /common/js/richScript.js, /common/js/richScript.XmlData.js 임포트
		- [선언] loadSiteMenuDataXml - 메뉴 XML을 로딩하여 자바스크립트 객체로 변환하여 SITE_MENU에 셋팅함.
		- [선언] getMenu - DIR Array로 해당메뉴 데이터를 가져옴
		- [선언] setCurrentDir - 현재 URL 정보를 Array로 변환하여 CURRENT_DIR에 셋팅함.
	
	함수 순서
	[선언] addEvent - 이벤트 추가 함수
	[실행] addEvent - 추가되는 이벤트 목록
	[선언] findRollOvers - 페이지내 롤오버 이미지 찾기
	[선언] viewPopup - 레이어 팝업 오픈(단순한 display:block)
	[선언] resizeIframe - 같은 도메인의 iframe 리사이즈
	[선언] txtFocus, bgFocus - input, textarea 포커스시 텍스트 삭제.
	[선언] initConditionToggle - 브랜드 색인 - 조건별 검색 - Toggle
	[선언] initFAQToggle - 고객센터 FAQ, 상품평 DL - Toggle
	[선언] initBrandToggle - 브랜드 검색결과 - Toggle
	[선언] setRoundBox - 가변 박스 설정
	[선언] setPositionBtns - 이전 페이지, 맨위로 버튼 설정
	[선언] setSectionArea - 섹션별 타이틀 설정
	[선언] setSiteLocation - 사이트 현재위치(히스토리) 설정
	[선언] getSiteInfo - 롯데면세점 사이트 정보영역 내용 설정
	[선언] setPositionSiteInfo - 롯데면세점 사이트 정보영역 위치 설정
	
	[플래시 링크함수 영역]

	[개발 추가영역 -욱]
		- string
		- validate


********************************************************************************************************/

var SITE_MENU = null;	// 메뉴 XML을 자바스크립트 OBJECT로 변환한 객체
var CURRENT_DIR = null;	// 현재 URL의 디렉토리 정보 Array
document.title = "名牌化妆品随心购买, 更多优惠尽在乐天市内免税店!";

/***********************************************
 * 메뉴 XML을 로딩하여 자바스크립트 객체로
 * 변환하여 SITE_MENU에 셋팅함.
 @ return : void
***********************************************/
function loadSiteMenuDataXml() {
	var xData = new XmlData();
	xData.load("/common/xml/cldfmenu.xml");
	SITE_MENU = xData.toObject();
	xData = null;
}
loadSiteMenuDataXml();		// Load Menu Data XML


/***********************************************
 * DIR Array로 해당메뉴 데이터를 가져옴
 @ param : _dirArray (Array)
 @ return : Object
***********************************************/
function getMenu(_dirArray) {
	var menu = {id : "", title : "", url : ""};
	var _tempMenu = getMenuData(_dirArray);
	if (_tempMenu!=undefined) {
		try { menu.id = _tempMenu.ID.value; } catch(e) { }
		try { menu.title = _tempMenu.TITLE.value; } catch(e) { }
		try { menu.url = _tempMenu.URL.value; } catch(e) { }
	}
	_tempMenu = null;
	return menu;
}


/***********************************************
 * DIR Array로 해당메뉴 원본 Object를 반환
 @ param : _dirArray (Array)
 @ return : Object
***********************************************/
function getMenuData(_dirArray) {
	var menu = SITE_MENU;
	for (var i=0; i<_dirArray.length; i++) {
		for (var j=0; j<menu.MENU.length; j++) {
			if (menu.MENU[j].ID.value==_dirArray[i]) {
				menu = menu.MENU[j];
				break;
			}
		}
	}
	return menu;
}

/***********************************************
 * 현재 URL 정보를 Array로 변환하여 CURRENT_DIR에 셋팅함.
 @ return : void
***********************************************/
function setCurrentDir() {
	var path = location.pathname;
	while(path.indexOf("//")>-1) {
		path = path.replace("//","/");
	}
	if (path.indexOf("/")==0) {
		path = path.substring(1,path.lastIndexOf("/"));
	}
	CURRENT_DIR = path.split("/", 3);
}

// Set Current Dir Info
setCurrentDir();



/***********************************************
 * _url만 받으면 현재 지점 코드를 유지하고 이동함.
 * _bCode를 받으면 입력한 지점코드를 달로 이동함.
 @ param : _url (String)
 @ param : _bCode (String:지점코드)
 @ return : void
***********************************************/
function openB(_url, _bCode) {
	var url = (_url!=undefined) ? _url : "";
	var bCode = (_bCode!=undefined) ? _bCode : "";
	if (bCode!="") {
		location.href = "#bCode="+BRANCH_CODE;
		url = _url.appendParameter("bCode="+bCode);
	}
	location.href = url;
}

// 새로운 지점코드를 쿠키에 저장
if (request.get("bCode")!="") {
	Cookie.set("bCode", request.get("bCode"));
}

// history.go(-1) 했을 경우 이전 지점코드를 쿠키에 저장
var prevBranchCodeParam = location.href.split("#")[1];
var prevBranchCode = "";
if (prevBranchCodeParam!=undefined) {
	prevBranchCode = prevBranchCodeParam.split("=")[1];
}
if (prevBranchCode!=undefined&&prevBranchCode!="") {
	Cookie.set("bCode", prevBranchCode);
}

// 쿠키의 지점코드를 가져온다.
var BRANCH_CODE = Cookie.get("bCode");




/***********************************************
 * 정해진 사이즈보다 크면 이미지 사이즈를 줄여준다.
 @ param : _obj (이미지객체)
 @ return : void
***********************************************/
function resizeContentsToMaxWidth(_obj) {
	var maxWidth = 632;
	if (_obj!=undefined) {
		if (_obj.offsetWidth>maxWidth) {
			_obj.style.width = maxWidth + "px";
		}
	}
}


/***********************************************
 * 레이어 팝업 open.
 @ param : _seviceId (login:로그인, zipcode:우편번호팝업, buyTime:구매가능시간안내)
 @ return : void
***********************************************/
var LAYERPOPUP_ROOT_ELEMENT_ID = "layerPopupRootArea";
function openLayerPopup(_seviceId) {
	var bgTitleImagePath = "/img/common/popup/bgTitle/"+_seviceId+".gif";
	var titleImagePath = "/img/common/popup/title/"+_seviceId+".gif";
	var contentsPath = "/layerPopup/"+_seviceId+"/index.jsp";
	var s = '';
	s += '<div class="popupLayout" style="top: 251px; left: 419px;">\n';
	s += '	<div class="pTitleArea">\n';
	s += '		<div class="btnClose"><img src="/img/common/popup/btnClose01.gif" alt="닫기" onClick="closeLayerPopup();" /></div>\n';
	s += '		<div class="mainTitle"><img src="'+bgTitleImagePath.escapeXml()+'" /></div>\n';
	s += '		<p class="pageTitle"><img src="'+titleImagePath.escapeXml()+'" /></p>\n';
	s += '	</div>\n';
	s += '	<div class="containerPContents">\n';
	s += '		<iframe id="layerPopupContentsFrame" name="layerPopupContentsFrame" src="'+contentsPath.escapeXml()+'" width="424" height="260" frameborder="0" scrolling="no"></iframe>\n';
	s += '		<p class="copyright"><img src="/img/common/popup/copyright.gif" alt="" /></p>\n';
	s += '	</div>\n';
	s += '</div>\n';
	if ($(LAYERPOPUP_ROOT_ELEMENT_ID).isNull) {
		var span = document.createElement("SPAN");
		span.setAttribute("id", LAYERPOPUP_ROOT_ELEMENT_ID);
		document.body.insertBefore(span, document.body.firstChild);
		span = null;
	}
	$(LAYERPOPUP_ROOT_ELEMENT_ID).innerHTML = s;
}

function closeLayerPopup() {
	try {
		document.body.removeChild($(LAYERPOPUP_ROOT_ELEMENT_ID));
	} catch(e) { }
}

function openLayerPopup_buyTime() {
	openLayerPopup("buyTime");
}

/***********************************************
 * 레이어 팝업 Contents Resize.
 @ return : void
***********************************************/
function resizeLayerPopupContents() {
	var windowName = window.name;
	var contentsHeight = document.documentElement.scrollHeight;
	if (contentsHeight<100) contentsHeight = 100;
	try {
		parent.$(windowName).setStyle("height", contentsHeight);
	} catch(e) { }
}





try {
	document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}


/********************************************************************************************************
	이벤트 추가 함수
********************************************************************************************************/
function addEvent(elm, evType, fn, useCapture) {   
    if( elm.addEventListener ) {
        elm.addEventListener(evType, fn, useCapture);   
        return true;   
    } else if ( elm.attachEvent ) {   
        var r = elm.attachEvent('on' + evType, fn);   
        return r;
    } else {
        elm['on' + evType] = fn;
    }
}


/********************************************************************************************************
	추가되는 이벤트 목록
********************************************************************************************************/
addEvent(window, "load", function() {


	// 페이지 공통 영역 설정
	setSectionArea();			// 섹션별 타이틀 설정
	setSiteLocation();			// 사이트 현재위치(히스토리) 설정
	setPositionSiteInfo();		// 사이트 정보영역 위치 설정
	setPositionBtns();			// 이전 페이지, 맨위로 버튼 설정	
});




/********************************************************************************************************
	페이지내 롤오버 이미지 찾기
********************************************************************************************************/
function findRollOvers() {
	var imgs = document.getElementsByTagName("img");

	for( var i=0; i<imgs.length; i++ ) {
		if( imgs[i].getAttribute("rel") == null ) continue;
		
		if( imgs[i].getAttribute("rel").indexOf("rollover") != -1 ) {
			imgs[i].onmouseover = function() {
				this.src = this.src.replace(".gif", "On.gif");
			}
			imgs[i].onmouseout = function() {
				this.src = this.src.replace("On.gif", ".gif");
			}
		}
	}
}



/********************************************************************************************************
	레이어 팝업 오픈(단순한 display:block)
********************************************************************************************************/
function viewPopup(_id) {
	if( !document.getElementById(_id) ) return false;
	var popupNote = document.getElementById(_id);
	popupNote.style.display = "block";
	popupNote.focus();
}



/********************************************************************************************************
	같은 도메인의 iframe 리사이즈
********************************************************************************************************/
function resizeIframe(targetId, _height) {
	if( !parent.document.getElementById(targetId) ) return false;
	
	var targetIframe = parent.document.getElementById(targetId);
	targetIframe.style.height = _height + "px";
}




/********************************************************************************************************
	이미지 탭 - TAB
********************************************************************************************************/
function initTabMenu(tabContainerID) {
	var tabContainer = document.getElementById(tabContainerID);
	var tabAnchor = tabContainer.getElementsByTagName("a");
	var i = 0;

	for(i=0; i<tabAnchor.length; i++) {
		if (tabAnchor.item(i).className == "tab")
			thismenu = tabAnchor.item(i);
		else
			continue;

		thismenu.container = tabContainer;
		thismenu.targetEl = document.getElementById(tabAnchor.item(i).href.split("#")[1]);
		thismenu.targetEl.style.display = "none";
		thismenu.imgEl = thismenu.getElementsByTagName("img").item(0);

		thismenu.onclick = function tabMenuClick() {
			currentmenu = this.container.current;
			if (currentmenu == this)
				return false;

			if (currentmenu) {
				currentmenu.targetEl.style.display = "none";
				if (currentmenu.imgEl) {
					currentmenu.imgEl.src = currentmenu.imgEl.src.replace("On.gif", ".gif");
					currentmenu.className = currentmenu.className.replace(" here", "");
				} else { }
			}
			
			this.targetEl.style.display = "";
			if (this.imgEl) {
				this.imgEl.src = this.imgEl.src.replace(".gif", "On.gif");
				this.className += " here";
			} else { }
			this.container.current = this;

			return false;
		};

		if (!thismenu.container.first)
			thismenu.container.first = thismenu;
	}
	if (tabContainer.first)
		tabContainer.first.onclick();
}



/********************************************************************************************************
	고객센터 FAQ, 상품평 DL - Toggle
********************************************************************************************************/
function initFAQToggle(tabContainer, _initialTarget) {
	
	triggers = tabContainer.getElementsByTagName("a");

	for(i = 0; i < triggers.length; i++) {
		if (triggers.item(i).href.split("#")[1])
			triggers.item(i).targetEl = document.getElementById(triggers.item(i).href.split("#")[1]);

		if (!triggers.item(i).targetEl)
			continue;
		
		triggers.item(i).targetEl.style.display = "none";
		triggers.item(i).onclick = function () {
			if (tabContainer.current == this) {
				this.targetEl.style.display = "none";
				tabContainer.current.parentNode.className = "";
				tabContainer.current = null;
			} else {
				if (tabContainer.current) {
					tabContainer.current.targetEl.style.display = "none";
					tabContainer.current.parentNode.className = "";
				}
				this.targetEl.style.display = "block";
				tabContainer.current = this;
				tabContainer.current.parentNode.className = "active";
			}
			
			return false;
		}

		if( !document.getElementById(_initialTarget) ) { continue; }
		var initialTarget = document.getElementById(_initialTarget);
		if( triggers.item(i).targetEl == initialTarget ) {
			triggers.item(i).onclick();
		}
	}
}



/********************************************************************************************************
	가변 박스 설정
********************************************************************************************************/
function setRoundBox(_roundContents, _roundStyle, _classParam) {
	var roundContents = _roundContents;
	var roundStyle = _roundStyle;
	var classParam = _classParam;

	var tbRoundBox = document.createElement("table");
		if( !classParam ) {
			tbRoundBox.className = roundStyle;
		} else {
			tbRoundBox.className = roundStyle + " " + classParam;
		}
		
		var trTop = tbRoundBox.insertRow(0);
			var tdTopLeft = trTop.insertCell(0);
				tdTopLeft.className = "rtTL";
			var tdTop = trTop.insertCell(1);
				tdTop.className = "rtT";
			var tdTopRight = trTop.insertCell(2);
				tdTopRight.className = "rtTR";
		
		var trMiddle = tbRoundBox.insertRow(1);
			var tdLeft = trMiddle.insertCell(0);
				tdLeft.className = "rtL";
			var tdCenter = trMiddle.insertCell(1);
				tdCenter.className = "rtC";
			var tdRight = trMiddle.insertCell(2);
				tdRight.className = "rtR";
		
		var trBottom = tbRoundBox.insertRow(2);
			var tdBottomLeft = trBottom.insertCell(0);
				tdBottomLeft.className = "rtBL";
			var tdBottom = trBottom.insertCell(1);
				tdBottom.className = "rtB";
			var tdBottomRight = trBottom.insertCell(2);
				tdBottomRight.className = "rtBR";
	
	var parentRoundContents = roundContents.parentNode;
	parentRoundContents.insertBefore(tbRoundBox, roundContents);
	tdCenter.appendChild(roundContents);
	
}

/********************************************************************************************************
	이전 페이지, 맨위로 버튼 설정
********************************************************************************************************/
function setPositionBtns() {
	if( !document.getElementById("btnPrev") || !document.getElementById("scTop") ) return false;

	var btnPrev = document.getElementById("btnPrev");
	var scTop = document.getElementById("scTop");
	btnPrev.innerHTML = '<a href="#" onclick="history.back(-1); return false;">이전 페이지로</a>';
	scTop.innerHTML = '<a href="#menuLottedfs">맨위로</a>';
}



/********************************************************************************************************
	섹션별 타이틀 설정
********************************************************************************************************/
function getDepth01() {
	var crntURI = location.href;
	var domain = "http://" + document.domain + "/";
	crntURI = crntURI.replace(domain, '');
	var directories = crntURI.split("/");

	for( var i=0; i<directories.length; i++ ) {
		if( directories[i].indexOf(".") != -1 ) directories[i]=null;
	}
	return directories[0];
}

function setSectionArea() {
	if( !document.getElementById("titleSection") || !document.getElementById("imgSection") ) return false;
	
	var titleSection = document.getElementById("titleSection");
	var imgSection = document.getElementById("imgSection");
	var directories;
	var h2Tag = document.createElement("h2");
	
	directories = CURRENT_DIR[0];
	
	switch(directories) {
		case 'company' : 
			var txt = document.createTextNode("Our Company");
			h2Tag.appendChild(txt);
			break;

		case 'stores' : 
			var txt = document.createTextNode("Our Stores");
			h2Tag.appendChild(txt);
			break;

		case 'guide' : 
			var txt = document.createTextNode("Shopping Guide");
			h2Tag.appendChild(txt);
			break;

		case 'membership' : 
			var txt = document.createTextNode("Membership");
			h2Tag.appendChild(txt);
			break;
		
		case 'event' : 
			var txt = document.createTextNode("Event");
			h2Tag.appendChild(txt);
			break;

		default :
		
	}
	
	titleSection.appendChild(h2Tag);
	titleSection.className = "h2" + directories;
	
	imgSection.className = directories + "Exp";
}



/********************************************************************************************************
	사이트 현재위치(히스토리) 설정
********************************************************************************************************/
function setSiteLocation() {
	if( !document.getElementById("siteLocation") ) return false;
	var siteLocation = document.getElementById("siteLocation");
	var _tempDir = [];
	var s = "";
	s += '<h3>사이트 현재 위치</h3>\n';
	s += '<ul>\n';
	s += '<li class="home"><a href="javascript:openB(\'/index.jsp\', 1);">HOME</a></li>\n';
	if (CURRENT_DIR!=null&&SITE_MENU!=null) {
		for (var i=0; i<CURRENT_DIR.length; i++) {
			_tempDir.push(CURRENT_DIR[i]);
			var menu = getMenu(_tempDir);
			if (i<CURRENT_DIR.length-1) {
				s += '<li><a href="'+menu.url+'">'+menu.title+'</a></li>\n';
			} else {
				s += '<li class="here">'+menu.title+'</li>\n';
			}
		}
	}
	s += '</ul>\n';
	siteLocation.innerHTML = s;
	_tempDir = null;
}


/********************************************************************************************************
	롯데면세점 사이트 정보영역 내용 설정
********************************************************************************************************/
function getSiteInfo() {
	var sInfo = "";
	sInfo += '		<h3>롯데면세점 사이트 정보</h3>\n';
	sInfo += '		<ul>\n';
	sInfo += '			<li class="info01"><a href="/stores/storeinfo.jsp">OUR STORES</a></li>\n';
	sInfo += '			<li class="info02"><a href="/guide/submain.jsp">SHOPPING GUIDE</a></li>\n';
	sInfo += '			<li class="info03"><a href="/membership/introduction/introduction.jsp">MEMBERSHIP</a></li>\n';
	sInfo += '			<li class="info04">CALL US 82-1688-3000</li>\n';
	sInfo += '		</ul>\n';
	sInfo += '		<p class="copyright">copyright(C)2008 lotte hotel all rights reserved</p>\n';
	sInfo += '		<div class="cBoth"></div>\n';
	return sInfo;
}



/********************************************************************************************************
	롯데면세점 사이트 정보영역 위치 설정
********************************************************************************************************/
function setPositionSiteInfo() {
	if( !document.getElementById("lottedfsInfo") || !document.getElementById("frameContents") ) return false;
	
	var lottedfsInfo = document.getElementById("lottedfsInfo");
	var frameContents = document.getElementById("frameContents");
	
	if( frameContents.className.indexOf("frameBrancMainContents") == 0 ) {
		var headerHight = 15;
	} else if( frameContents.className == "frameMainContents" ) {
		var headerHight = 175;
	} else {
		var headerHight = 105;
	}

	var infoMargin = 20;
	var frameContentsHeightHeight = frameContents.offsetHeight;
	var currentHeight = 0;
	
	currentHeight = frameContentsHeightHeight + headerHight + infoMargin;
	
	lottedfsInfo.style.top = currentHeight + "px";
//	lottedfsInfo.style.left = 41 + "px";

	lottedfsInfo.innerHTML = getSiteInfo();
	
	frameContents.onresize = function() {
		setPositionSiteInfo();
	}
}



/********************************************************************************************************
	플래시 링크함수 영역
********************************************************************************************************/
function scHome() { location.href="/"; }
function scKor() { open("http://kr.lottedfs.com/", "_blank", ""); }
function scEng() { open("http://en.lottedfs.com/", "_blank", ""); }
function scJp() { open("http://jp.lottedfs.com/", "_blank", ""); }
function scCn() { open("http://cn.lottedfs.com/", "_blank", ""); }
function scCustomer() { location.href="/guide/service/faq/faq.jsp"; }
function scVip() { location.href="/membership/introduction/introduction.jsp" }
function scLotteDFS() { window.open("http://www.lottedfs.com/", "_blank", ""); }
function bsLotteDFS() { window.open("http://www.busanlottedfs.com/", "_blank", ""); }



/***** 가이드 지점안내 - 매장정보 지도 확대보기 *****/
function magnificationMap(_nFloor) {
	if( !document.getElementById("popupMap") ) return false;
	
	var popupMap = document.getElementById("popupMap");
	popupMap.style.display = "block";

	if( document.getElementById("floor0"+parseInt(_nFloor)) ) {
		var pFloor = document.getElementById("floor0"+parseInt(_nFloor));
		pFloor.style.display = "block";

		scrollbarWidth = (pFloor.clientWidth/(pFloor.scrollWidth/pFloor.clientWidth));
		scrollbarHeight = (pFloor.clientHeight/(pFloor.scrollHeight/pFloor.clientHeight));

		pFloor.scrollLeft = pFloor.clientWidth - scrollbarWidth;
		pFloor.scrollTop = pFloor.clientHeight - scrollbarHeight;
	}

}

function closeStoreMap() {
	if( !document.getElementById("popupMap") ) return false;

	if( document.getElementById("floor01") ) {
		document.getElementById("floor01").style.display = "none";
	}
	if( document.getElementById("floor02") ) {
		document.getElementById("floor02").style.display = "none";
	}
	
	document.getElementById("popupMap").style.display = "none";
}


/***** 가이드 - 지점안내 *****/
function scStoreInfo(_bCode) {
//	alert("지점코드 : " + _bCode);
	switch(parseInt(_bCode)) {
		case 2 :	// 본점
			location.href = "/stores/main/introduction/intro.jsp";
			break;

		case 3 :	// 로비점
			location.href = "/stores/lobby/introduction/intro.jsp";
			break;

		case 4 :	// 월드점
			location.href = "/stores/world/introduction/intro.jsp";
			break;

		case 5 :	// 인천공항점
			location.href = "/stores/incheon/introduction/intro.jsp";
			break;

		case 6 :	// 김해공항점
			location.href = "/stores/gimhae/introduction/intro.jsp";
			break;

		case 7 :	// 부산점
			location.href = "/stores/busan/introduction/intro.jsp";
			break;

		case 8 :	// 제주점
			location.href = "/stores/jeju/introduction/intro.jsp";
			break;

		case 9 :	// 제주공항점
			location.href = "/stores/jejua/introduction/intro.jsp";
			break;

		case 10 :
			scLotteDFS();			
			break;

		case 11 :
			bsLotteDFS();			
			break;

		case 12 :
			location.href = "/stores/gimpoa/introduction/intro.jsp";			
			break;

		case 13 :
			location.href = "/stores/coex/introduction/intro.jsp";			
			break;
	}
}


/********************************************************************************************************
	개발쪽 추가 javascript 영역
********************************************************************************************************/
/***** String *****/
String.prototype.trim = function () {
	var s = (this!=null) ? this : "";
	s = s.replace(/^\s+/g,"");
	s = s.replace(/\s+$/g,"");
	return s;
};

String.prototype.getBytes = function() {
	var s = (this!=null) ? this : "";
	var bytes = 0;
	var c = "";
	var u = "";
	for (var i=0; i<s.length; i++) {
		c = s.charAt(i);
		u = escape(c);
		if (u.length < 4) { // 반각문자 : 기본적인 영문, 숫자, 특수기호
			bytes++; // + 1byte
		} else {
			var b = parseInt(c.charCodeAt(0));
			if (((b >= 65377)&&(b <= 65500))||((b >= 65512)&&(b <= 65518))) // 반각문자 유니코드 10진수 범위 : 한국어, 일본어, 특수문자
				bytes++; // + 1byte
			else // 전각문자 : 위 조건을 제외한 모든 문자
				bytes += 2; // + 2byte
		}
	}
	return bytes;
};


/***** validate *****/
var funcs = {};
funcs['nospace'] = isNoSpace;				// 공백없이
funcs['email'] = isValidEmail;				// 이메일검사
funcs['emailfirst'] = isValidEmailFirst;	// 이메일 앞자리
funcs['phone'] = isValidPhone;				// 전화번호
funcs['userid'] = isValidUserid;			// 아이디
funcs['hangul'] = hasHangul;				// 한글
funcs['number'] = isNumeric;				// 숫자
funcs['number2'] = isNumeric2;				// 숫자2
funcs['engonly'] = alphaOnly;				// 영문
funcs['hangulonly'] = hangulOnly;			// 한글
funcs['jumin'] = isValidJumin;				// 주민번호
funcs['bizno'] = isValidBizNo;				// 사업자번호
funcs['pw'] = isValidPassword;				// 비밀번호


var NO_BLANK = "{name+을를} 입력하여 주십시오";
var NO_SELECT = "{name+을를} 선택하여주십시오";
var NOT_VALID = "{name+이가} 올바르지 않습니다";
var TOO_LONG = "{name}의 길이가 초과되었습니다 (최대 {maxbyte}바이트)";
var TOO_SHORT = "{name}의 길이가 부족합니다 (최소 {minbyte}바이트)";

String.prototype.hasFinalConsonant = function(str) {
	str = this != window ? this : str; 
	var strTemp = str.substr(str.length-1);
	return ((strTemp.charCodeAt(0)-16)%28!=0);
}

function josa(str,tail) {
	return (str.hasFinalConsonant()) ? tail.substring(0,1) : tail.substring(1,2);
}

function validate(form) {
	var i=0;

	for (i = 0; i < form.elements.length; i++ ) {
		var el = form.elements[i];
		if(el.tagName.toUpperCase() != "OBJECT") {
			try
			{
			el.value = el.value.trim();
			}
			catch (e)
			{
			}
	
			if (el.getAttribute("REQUIRED") != null) {
				//select 구문 처리
				if(el.type.indexOf("select")>-1){
					//|| el.option[el.selectedIndex].value == ""
					if (el.selectedIndex==0 ) {
						return doError(el,NO_SELECT);
					}
				}else{
					if (el.value == null || el.value == "") {
						return doError(el,NO_BLANK);
					}
				}
			}
	
			if (el.getAttribute("MAXBYTE") != null && el.value != "") {
				var len = el.value.getBytes();
				if (len > parseInt(el.getAttribute("MAXBYTE"))) {
					maxbyte = el.getAttribute("MAXBYTE");
					return doError(el,TOO_LONG,"",maxbyte);
				}
			}
			if (el.getAttribute("MINBYTE") != null && el.value != "") {
				var len = el.value.getBytes();
				if (len < parseInt(el.getAttribute("MINBYTE"))) {
					minbyte = el.getAttribute("MINBYTE");
					return doError(el,TOO_SHORT,"",minbyte);
				}
			}
	
			if (el.getAttribute("OPTION") != null && el.value != "") {
				if (!funcs[el.getAttribute("OPTION").toLowerCase()](el)) return false;
			}
	
			if (el.getAttribute("FILETYPE") != null && el.value != "") {
				var validFileType = el.getAttribute("FILETYPE").split(",");
				var nFileType = el.value.substring(el.value.lastIndexOf(".")+1,el.length);
				var isValidFileType = false;
				for (j=0; j<validFileType.length ; j++) {
					if (nFileType.toUpperCase()==validFileType[j].toUpperCase().replace(/\s/g,"")) {
						isValidFileType = true;
					}
				}
				if (!isValidFileType) {
					var nameString = "";
					if (el.getAttribute("$name") != null && el.getAttribute("$name") != "") {
						nameString = "{name+이가} ";
					}
					return doError(el,nameString+"적절한 파일 포맷이 아닙니다.");
				}
			}
		}
	}
	return true;
}

function doError(el,type,action,byte) {
	var pattern = /{([a-zA-Z0-9_]+)\+?([가-힝]{2})?}/;
	var name = ($name = el.getAttribute("$NAME")) ? $name : el.getAttribute("NAME");
	pattern.exec(type);
	var tail = (RegExp.$2) ? josa(eval(RegExp.$1),RegExp.$2) : "";
	alert(type.replace(pattern,eval(RegExp.$1) + tail).replace(pattern,byte));
	if (action == "sel") {
		el.select();
	} else if (action == "del")	{
		el.value = "";
	}
	if (el.getAttribute("UNFOCUSED") == null) {
		if(el.type!="hidden"&&el.style.display.toUpperCase()!="NONE"){		
			el.focus();
		}
	}	
	return false;
}	


/// 패턴 검사 함수들 ///
function isNoSpace(el) {
	var pattern = /[\s]/;
	return (!pattern.test(el.value)) ? true : doError(el,"{name+은는} 띄어쓰기 없이 입력해주시기 바랍니다");
}

function isValidEmail(el) {
	var pattern = /^[_a-zA-Z0-9-\.]+@[\.a-zA-Z0-9-]+\.[a-zA-Z]+$/;
	return (pattern.test(el.value)) ? true : doError(el,NOT_VALID);
}

function isValidEmailFirst(el) {
	var pattern = /^[_a-zA-Z0-9-\.]+$/;
	return (pattern.test(el.value)) ? true : doError(el,NOT_VALID);
}



//수정 필요
function isValidUserid(el) {
	var pattern = /^[a-zA-Z]{1}[a-zA-Z0-9_]{3,11}$/;
	return (pattern.test(el.value)) ? true : doError(el,"{name+은는} 4자이상 12자 미만이어야 하고,\n 영문,숫자, _ 문자만 사용할 수 있습니다");
}

function hasHangul(el) {
	var pattern = /[가-힝]/;
	return (pattern.test(el.value)) ? true : doError(el,"{name+은는} 반드시 한글을 포함해야 합니다");
}
function hangulOnly(el) {
	var pattern = /^[가-힝]+$/;
	return (pattern.test(el.value)) ? true : doError(el,"{name+은는} 한글만 입력가능 합니다");
}

function alphaOnly(el) {
	var pattern = /^[a-zA-Z]+$/;
	return (pattern.test(el.value)) ? true : doError(el,NOT_VALID);
}

function isNumeric(el) {
	var pattern = /^[0-9]+$/;
	return (pattern.test(el.value)) ? true : doError(el,"{name+은는} 반드시 숫자로만 입력해야 합니다");
}

function isNumeric2(el) {
	var pattern = /^[0-9,.]+$/;
	return (pattern.test(el.value)) ? true : doError(el,"{name+은는} 반드시 숫자로만 입력해야 합니다");
}


function isValidJumin(el) {
    var pattern = /^([0-9]{6})-?([0-9]{7})$/; 
	var num = el.value;
    if (!pattern.test(num)) return doError(el,NOT_VALID); 
    num = RegExp.$1 + RegExp.$2;

	var sum = 0;
	var last = num.charCodeAt(12) - 0x30;
	var bases = "234567892345";
	for (var i=0; i<12; i++) {
		if (isNaN(num.substring(i,i+1))) return doError(el,NOT_VALID);
		sum += (num.charCodeAt(i) - 0x30) * (bases.charCodeAt(i) - 0x30);
	}
	var mod = sum % 11;
	return ((11 - mod) % 10 == last) ? true : doError(el,NOT_VALID);
}

function isValidBizNo(el) { 
	var pattern = /([0-9]{3})-?([0-9]{2})-?([0-9]{5})/; 
	var num = el.value;
    if (!pattern.test(num)) return doError(el,NOT_VALID); 
    num = RegExp.$1 + RegExp.$2 + RegExp.$3;
    var cVal = 0; 
    for (var i=0; i<8; i++) { 
        var cKeyNum = parseInt(((_tmp = i % 3) == 0) ? 1 : ( _tmp  == 1 ) ? 3 : 7); 
        cVal += (parseFloat(num.substring(i,i+1)) * cKeyNum) % 10; 
    } 
    var li_temp = parseFloat(num.substring(i,i+1)) * 5 + '0'; 
    cVal += parseFloat(li_temp.substring(0,1)) + parseFloat(li_temp.substring(1,2)); 
    return (parseInt(num.substring(9,10)) == 10-(cVal % 10)%10) ? true : doError(el,NOT_VALID); 
}

function isValidPhone(el) {
	var pattern = /^[0-9-]+$/;
	return (pattern.test(el.value)) ? true : doError(el,"{name+은는} 반드시 숫자로만 입력해야 합니다");
}

function isValidDate(el) {
	var oDateStr = el.value;

	var oDate = new Date(oDateStr.substr(0,4),oDateStr.substr(4,2)-1,oDateStr.substr(6,2));

	var oYearStr=oDate.getFullYear();

	var oMonthStr=(oDate.getMonth()+1).toString();
		
	oMonthStr = (oMonthStr.length ==1) ? "0"+ oMonthStr: oMonthStr; 
	var oDayStr=oDate.getDate().toString();
	oDayStr = (oDayStr.length ==1) ? "0"+ oDayStr: oDayStr; 

	return  (oDateStr == oYearStr+oMonthStr+oDayStr) ? true : doError(el,NOT_VALID); 
}

function isValidPassword(el) {
	var pattern = /^[A-Za-z0-9_\-\!@#]{4,12}$/;
	return (pattern.test(el.value)) ? true : doError(el,"비밀번호가 올바르지 않습니다.\n비밀번호는 4자이상 12자 이하의 영문, 숫자, 특수문자만 사용할 수 있습니다");
}


function scBranch(n) {
	if (n == 2)
	{
		document.location.href = "http://cn.lottedfs.com/stores/main/introduction/intro.jsp";
	}
	else if (n == 1)
	{
		document.location.href = "http://cn.lottedfs.com/membership/introduction/introduction.jsp";
	}
}


/********************************************************************************************************
	메인페이지 Notice 영역 스크롤
********************************************************************************************************/
ScrollText = function(option) {
	this._options = {
		containerId : "",
		intervalSpeed : 2000,
		moveSpeed : 10
	}
	this.option(option);

	var move;
	var container = document.getElementById(this._options['containerId']);
	var box = container.getElementsByTagName('UL')[0];
	var currentNo = 0;
	var totalNo = box.getElementsByTagName('LI').length;
	var movePixel = 20;
	var mTop = 0;
	var moveSpeed = this._options['moveSpeed'];
	var stop = false;
	var moving = false;
	
	if (totalNo <= 1) {
		this.setStop = function() {};
		this.moveUp = function() {};
		this.moveDown = function() {};
		return;
	}

	box.innerHTML += box.innerHTML;

	interval = setInterval(function () {
		if (!stop) {
			if (currentNo == totalNo) {
				currentNo = 0;
				mTop = 0;
				box.style.marginTop = mTop + "px";
			}
			move = setInterval(function () {
				moving = true;
				mTop--;
				box.style.marginTop = mTop;
				if (mTop == 0 - (currentNo * movePixel)) {
					clearInterval(move);
					moving = false;
				}
			}, moveSpeed);
			currentNo++;
		}
	}, this._options['intervalSpeed']);

	container.onmouseover = function() { stop = true; }
	container.onmouseout = function() { stop = false; }
	this.setStop = function(b) { stop = b; }

	this.moveUp = function() {
		if (moving) return;
		if (currentNo == totalNo) {
			currentNo = 0;
			mTop = 0;
			box.style.marginTop = mTop + "px";
		}
		move = setInterval(function () {
			mTop--;
			box.style.marginTop = mTop;
			if (mTop == 0 - (currentNo * movePixel)) {
				clearInterval(move);
			}
		}, moveSpeed);
		currentNo++;
	}

	this.moveDown = function() {
		if (moving) return;
		if (currentNo == 0) {
			currentNo = totalNo;
			mTop = 0 - (totalNo * movePixel);
			box.style.marginTop = mTop + "px";
		}
		move = setInterval(function () {
			mTop++;
			box.style.marginTop = mTop;
			if (mTop == 0 - (currentNo * movePixel)) {
				clearInterval(move);
			}
		}, moveSpeed);
		currentNo--;
	}
}

ScrollText.prototype.option = function(name, value) {
	if (typeof name == "undefined") return "";
	if (typeof name == "string") {
		if (typeof value == "undefined") return this._options[name];
		this._options[name] = value;
		return this;
	}

	try { for (var x in name) this._options[x] = name[x] } catch (e) {};

	return this;
}
