/*******************************************************************************
 * 인터넷 교보문고 TP 프로젝트
 *
 * Copyright(c) 1997-2009 Kyobo Book Centre
 * All rights reserved.
 ******************************************************************************/

/**
 * 입력 객체가 실제로 페이지상에 존재하는 HTML객체인지를 검사한다.
 * 
 * @param obj
 *            객체
 * @return
 */


function gfOpenOrderSend(){
    window.open("http://www.kyobobook.co.kr/myroom/myroomMain.laf","_blank");
}

function gfGoCSCenter(){
    window.open("http://www.kyobobook.co.kr/cscenter/csCenterMain.laf","_blank");
}
function isObject(obj) {
	if (typeof obj != "object") {
		window.alert("객체가 존재하지 않습니다. 객체의 철자를 확인하세요.");

		return false;
	}

	return true;
}

/**
 * 입력 객체가 Array 형태인지 검사한다.
 * 
 * @param obj
 *            객체
 * @return
 */
function isArray(obj) {
	if ((typeof obj != "object") || (typeof obj[0] != "object")) {
		return false;
	}

	return true;
}

/**
 * 입력 문자열의 앞뒤 공백(white space)을 제거한다.
 * 
 * @param str
 *            문자열
 * @return
 */
function trim(str) {
	var n = str.length;

	var i;

	for (i = 0; i < n; i++) {
		if (str.charAt(i) != " ") {
			break;
		}
	}

	var j;

	for (j = n - 1; j >= 0; j--) {
		if (str.charAt(j) != " ") {
			break;
		}
	}

	if (i > j) {
		return "";
	} else {
		return str.substring(i, j + 1);
	}
}

/**
 * 입력 문자열의 앞에서 공백(white space)을 제거한다.
 * 
 * @param str
 *            문자열
 * @return
 */
function ltrim(str) {
	var n = str.length;

	var i;

	for (i = 0; i < n; i++) {
		if (str.charAt(i) != " ") {
			break;
		}
	}

	return str.substring(i);
}

/**
 * 입력 문자열의 뒤에서 공백(white space)을 제거한다.
 * 
 * @param str
 *            문자열
 * @return
 */
function rtrim(str) {
	var n = str.length;

	var j;

	for (j = n - 1; j >= 0; j--) {
		if (str.charAt(j) != " ") {
			break;
		}
	}

	return str.substring(0, j + 1);
}

/**
 * 입력 객체의 바이트단위의 길이를 구한다.
 * 
 * @param str
 *            문자열
 * @return
 */
function strlen(str) {
	var j = 0;

	for ( var i = 0; i < str.length; i++) {
		if (escape(str.charAt(i)).length == 6) {
			j++;
		}

		j++;
	}

	return j;
}

/**
 * 문자열의 공백(white space)을 제거한다.
 * 
 * @param str
 *            문자열
 * @return
 */
function removeSpace(str) {
	return removeString(" ");
}

/**
 * 문자열을 뒤에서부터 3자리씩 ,(comma)로 끊는다.
 * 
 * @param str
 *            문자열
 * @return
 */
function insertComma(str) {
	str = removeComma(str);

	var strIdx = str.indexOf(".");

	if (strIdx == -1) {
		return insertCharacterByBack(str, ",", 3);
	} else {
		var str1 = str.substring(0, strIdx);
		var str2 = str.substring(strIdx);

		return insertCharacterByBack(str1, ",", 3) + str2;
	}
}

/**
 * ','(Comma)를 삭제한다.
 * 
 * @param str
 *            문자열
 * @return
 */
function removeComma(str) {
	return removeString(str, ",");
}

/**
 * 문자열을 교체한다.
 * 
 * @param str
 *            문자열
 * @param src
 *            찾을 문자열
 * @param tar
 *            바꿀 문자열
 * @return
 */
function replace(str, src, tar) {
	if (str == null) {
		return "";
	}

	if (src == null || src == "") {
		return str;
	}

	var i = 0;
	var j = 0;

	var outVal = "";

	while (j > -1) {
		j = str.indexOf(src, i);

		if (j > -1) {
			outVal += str.substring(i, j);
			outVal += tar;
			i = j + src.length;
		}
	}

	outVal += str.substring(i, str.length);

	return outVal;
}

/**
 * 지정한 자리수의 난수를 발생시킨다.
 * 
 * @param size
 *            난수 크기
 * @return
 */
function getRandom(size) {
	var random;

	while ((random = Math.random() * Math.pow(10, size) - 1) < Math.pow(10,
			size - 1)) {
		;
	}

	return parseInt(random);
}

/**
 * 입력 문자열의 지정문자를 제거한다.
 * 
 * @param str
 *            문자열
 * @return
 */
function removeString(str, src) {
	var outVal = "";

	for ( var i = 0; i < str.length; i++) {
		if (str.charAt(i) == src) {
			continue;
		} else {
			outVal += str.charAt(i);
		}
	}

	return outVal;
}

/**
 * 소수점을 포함한 숫자를 소수점을 제거한 정수로 변환한다.
 * 
 * @param str
 *            문자열
 * @return
 */
function toInteger(str) {
	if (str.indexOf(".") == -1) {
		return str;
	} else {
		return str.substring(0, str.indexOf("."));
	}
}

/**
 * 소수점을 포함하지 않은 숫자를 소수점을 포함한 실수로 변환한다.
 * 
 * @param str
 *            문자열
 * @return
 */
function toReal(str) {
	var strIdx = str.indexOf(".")

	if (strIdx == -1) {
		return str + ".0";
	} else if (strIdx == str.length - 1) {
		return str + "0";
	} else {
		return str;
	}
}

/**
 * 자바스크립트 Date 객체를 Time 문자열로 변환한다.
 * 
 * @param date
 *            Date 객체
 * @return
 */
function toTimeString(date) {
	var year = date.getFullYear();
	var month = date.getMonth() + 1; // 1월=0, 12월=11
	var day = date.getDate();
	var hour = date.getHours();
	var min = date.getMinutes();
	var sec = date.getSeconds();

	if (("" + month).length == 1) {
		month = "0" + month;
	}

	if (("" + day).length == 1) {
		day = "0" + day;
	}

	if (("" + hour).length == 1) {
		hour = "0" + hour;
	}

	if (("" + min).length == 1) {
		min = "0" + min;
	}

	if (("" + sec).length == 1) {
		sec = "0" + sec;
	}

	return "" + year + month + day + hour + min + sec;
}

/**
 * 연월일시분초 문자열을 자바스크립트 Date 객체로 변환한다.
 * 
 * @param time
 *            연월일시분초 문자열
 * @return
 */
function toTimeObject(str) {
	var year = str.substr(0, 4);
	var month = str.substr(4, 2) - 1; // 1월 = 0, ..., 12월 = 11
	var day = str.substr(6, 2);
	var hour = str.substr(8, 2);
	var min = str.substr(10, 2);

	return new Date(year, month, day, hour, min);
}

/**
 * 현재 시각을 Time 형식으로 리턴한다.
 * 
 * @return
 */
function getCurrentTime() {
	return toTimeString(new Date());
}

/**
 * 현재 年을 YYYY형식으로 리턴
 * 
 * @return
 */
function getYear() {
	return getCurrentTime().substr(0, 4);
}

/**
 * 현재 月을 MM형식으로 리턴
 * 
 * @return
 */
function getMonth() {
	return getCurrentTime().substr(4, 2);
}

/**
 * 현재 日을 DD형식으로 리턴
 * 
 * @return
 */
function getDay() {
	return getCurrentTime().substr(6, 2);
}

/**
 * 오늘날짜에 해당하는 요일을 구한다.
 * 
 * @return
 */
function getDayOfWeek() {
	var now = new Date();

	var day = now.getDay();
	var week = new Array("일", "월", "화", "수", "목", "금", "토");

	return week[day];
}

/**
 * 주어진 Time 과 y년 m월 d일 h시 차이나는 Time을 구한다.
 * 
 * @param time
 *            Time 객체
 * @param y
 *            year년 차이
 * @param m
 *            month월 차이
 * @param d
 *            day일 차이
 * @param h
 *            hour시 차이
 * @return
 */
function shiftTime(time, year, month, day, hour) {
	var date = toTimeObject(time);

	date.setFullYear(date.getFullYear() + year);
	date.setMonth(date.getMonth() + month);
	date.setDate(date.getDate() + day);
	date.setHours(date.getHours() + day);

	return toTimeString(date);
}

/**
 * 현재로부터 지정한 만큼의 이전연을 구한다.
 * 
 * @param year
 *            연
 * @return
 */
function getYearBefore(year) {
	return shiftTime(getCurrentTime(), -year, 0, 0, 0);
}

/**
 * 현재로부터 지정한 만큼의 이전월을 구한다.
 * 
 * @param month
 *            월
 * @return
 */
function getMonthBefore(month) {
	return shiftTime(getCurrentTime(), 0, -month, 0, 0);
}

/**
 * 현재로부터 지정한 만큼의 이전일를 구한다.
 * 
 * @param day
 *            일
 * @return
 */
function getDayBefore(day) {
	return shiftTime(getCurrentTime(), 0, 0, -day, 0);
}

/**
 * 현재로부터 지정한 만큼의 이전시를 구한다.
 * 
 * @param hour
 *            시
 * @return
 */
function getHourBefore(hour) {
	return shiftTime(getCurrentTime(), 0, 0, 0, -hour);
}

/**
 * 현재로부터 지정한 만큼의 이후연을 구한다.
 * 
 * @param year
 *            연
 * @return
 */
function getYearAfter(year) {
	return shiftTime(getCurrentTime(), year, 0, 0, 0);
}

/**
 * 현재로부터 지정한 만큼의 이후월을 구한다.
 * 
 * @param month
 *            월
 * @return
 */
function getMonthAfter(month) {
	return shiftTime(getCurrentTime(), 0, month, 0, 0);
}

/**
 * 현재로부터 지정한 만큼의 이후일를 구한다.
 * 
 * @param day
 *            일
 * @return
 */
function getDayAfter(day) {
	return shiftTime(getCurrentTime(), 0, 0, day, 0);
}

/**
 * 현재로부터 지정한 만큼의 이후시를 구한다.
 * 
 * @param hour
 *            시간
 * @return
 */
function getHourAfter(hour) {
	return shiftTime(getCurrentTime(), 0, 0, 0, hour);
}

/**
 * 두 시간이 몇 개월 차이인지 구한다.
 * 
 * @param time1
 *            연월일시분초 문자열
 * @param time2
 *            연월일시분초 문자열
 * @return
 */
function getMonthInterval(time1, time2) {
	var date1 = toTimeObject(time1);
	var date2 = toTimeObject(time2);

	var year = date2.getFullYear() - date1.getFullYear();
	var month = date2.getMonth() - date1.getMonth();
	var day = date2.getDate() - date1.getDate();

	return year * 12 + month + ((day >= 0) ? 0 : -1);
}

/**
 * 두 시간이 몇일 차이인지 구한다.
 * 
 * @param time1
 *            연월일시분초 문자열
 * @param time2
 *            연월일시분초 문자열
 * @return
 */
function getDayInterval(time1, time2) {
	var date1 = toTimeObject(time1);
	var date2 = toTimeObject(time2);
	var day = 1000 * 3600 * 24;

	return parseInt((date2 - date1) / day, 10);
}

/**
 * 두 시간이 몇시간 차이인지 구한다.
 * 
 * @param time1
 *            연월일시분초 문자열
 * @param time2
 *            연월일시분초 문자열
 * @return
 */
function getHourInterval(time1, time2) {
	var date1 = toTimeObject(time1);
	var date2 = toTimeObject(time2);
	var hour = 1000 * 3600;

	return parseInt((date2 - date1) / hour, 10);
}

/**
 * YYYY-MM-DD 형식이 맞는지 검사한다.
 * 
 * @param str
 *            문자열
 * @return
 */
function isValidDate(str) {
	if (str.length != 10) {
		return false;
	}

	var src = replace(str, '-', '');
	var year = src.substring(0, 4);
	var month = src.substring(4, 6);
	var day = src.substring(6, 8);

	if (!ValidDate(year, month, day)) {
		return false;
	}

	return true;
}

/**
 * 윤년여부를 나타낸다.
 */
function isLeapYear(year) {
	if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {
		return true;
	} else {
		return false;
	}
}

/**
 * 쿠키값을 지정한다.
 * 
 * @param name
 *            쿠키명
 * @param value
 *            쿠키값
 * @param expireday
 *            만료일
 * @return
 */
function setCookie(name, value, expireday) {
	var today = new Date();
	var nextDate = today.getDate() + (expireday - 1)
	today.setDate(nextDate);
	var newDate = new Date(today.getYear(), today.getMonth(), today.getDate(),
			23, 59, 59);
	document.cookie = name + "=" + escape(value) + "; path=/; expires="
			+ newDate.toGMTString() + ";";
}

/**
 * 쿠키값을 가져온다.
 * 
 * @param name
 *            쿠키명
 * @return
 */
function getCookie(name) {
	var nameOfCookie = name + "=";
	var x = 0;

	while (x <= document.cookie.length) {
		var y = (x + nameOfCookie.length);

		if (document.cookie.substring(x, y) == nameOfCookie) {
			if ((endOfCookie = document.cookie.indexOf(";", y)) == -1) {
				endOfCookie = document.cookie.length;
			}

			return unescape(document.cookie.substring(y, endOfCookie));
		}

		x = document.cookie.indexOf(" ", x) + 1;

		if (x == 0) {
			break;
		}
	}

	return "";
}

/**
 * 지정한 쿠키이름의 쿠키를 삭제한다.
 * 
 * @param name
 *            쿠키 이름
 * @return
 */
function removeCookie(name) {
	var expireDay = new Date();
	expireDay.setTime(expireDay.getTime() - 1);
	var value = getCookie(name);

	document.cookie = name + "=" + value + "; expires="
			+ expireDay.toGMTString();
}

/**
 * 새창을 지정한 옵션으로 띄운다.
 * 
 * @param url
 *            창의 URL
 * @param name
 *            창의 이름
 * @param width
 *            창의 넓이
 * @param height
 *            창의 높이
 * @param num
 *            창의 번호(0 ~ 창의갯수 - 1)
 * @return 창의 객체
 */
function openWindow(url, name, width, height, num) {
	var X = 0;
	var Y = 0;

	if (typeof num == "undefined") {
		X = (window.screen.width - width) / 2;
		Y = (window.screen.height - height) / 2;
	} else {
		X = num * 10;
		Y = 20 + num * 10;
	}

	var win = window.open(url, name, "height=" + height + ",width=" + width
			+ ", left=" + X + ", top=" + Y + ", screenX=" + X + ", screenY="
			+ Y + ", resizable=yes, scrollbars=no, status=no");
	win.focus();

	return win;
}

/**
 * 새창을 지정한 옵션으로 띄운다.
 * 
 * @param url
 *            창의 URL
 * @param width
 *            창의 넓이
 * @param height
 *            창의 높이
 * @param feature
 *            창의 옵션
 * @param target
 *            창의 이름
 * @return
 *            창의 객체
 */
function window_open(url, width, height, feature, target) {
    var top = (screen.availHeight - height) / 2;
    var left = (screen.availWidth - width) / 2;

    feature = arguments[3] ? arguments[3] : "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no";
    target = arguments[4] ? arguments[4] : url.substring(((url.lastIndexOf("/") != -1) ? (url.lastIndexOf("/") + 1) : 0), url.lastIndexOf("."));

    var win = window.open(url, target, 'top=' + top + ',left=' + left + ',width=' + width + ',height=' + height + ',' + feature);
    
    if (win == null || win == "undefined") {
        window.alert("차단된 팝업창을 허용해 주십시오.");
    }

    return;
}

/**
 * 모달창을 지정한 옵션으로 띄운다.
 * 
 * @param url
 *            창의 URL
 * @param url
 *            창의 이름
 * @param width
 *            창의 넓이
 * @param height
 *            창의 높이
 * @param scroll
 *            스크롤 여부(yes/no)
 * @param resize
 *            크기조절 여부(yes/no)
 * @return 창의 객체
 */
function openModalWindow(url, arguments, width, height) {
	var X = 0;
	var Y = 0;

	X = (window.screen.width - parseInt(width, 10) + 6) / 2;
	Y = (window.screen.height - parseInt(height, 10)) / 2;

	return window.showModalDialog(url, arguments, "dialogWidth:"
			+ (parseInt(width, 10) + 6) + "px; dialogHeight:" + height
			+ "px; dialogLeft:" + X + "px; dialogTop:" + Y
			+ "px; center:yes; help:no; resizable:yes; scroll:no; status:no");
}

/**
 * 이벤트를 초기화 한다.
 */
function enableEnterKey() {
	function onkeypress(e) {
		if (window.event.srcElement.type != "textarea"
				&& window.event.srcElement.type != "button") { // 텍스트 입력박스 이외의
			// 입력에 대하여
			if (window.event.keyCode == 13) { // 13 : Enter
				if (typeof __submit == "function") {
					__submit();
				}
			}

		}
	}

	document.onkeypress = onkeypress;
}

/**
 * 오른쪽 버튼 사용하지 못하도록 한다.
 */
function disableRightButton() {
	if (window.Event) {
		document.captureEvents(Event.MOUSEUP);
	}

	function noContextMenu() {
		event.cancelBubble = true;
		event.returnValue = false;

		return false;
	}

	function noRightButton(e) {
		if (window.Event) {
			if (e.which == 2 || e.which == 3) {
				return false;
			}
		} else {
			if (event.button == 2 || event.button == 3) {
				event.cancelBubble = true
				event.returnValue = false;

				return false;
			}
		}
	}

	document.oncontextmenu = noContextMenu;
	document.onmousedown = noRightButton;
}

/**
 * 이벤트를 초기화 한다.
 */
function disableBackSpace() {
	function onKeyDown(e) {
		if (window.event.srcElement.readOnly
				|| (window.event.srcElement.type != "password"
						&& window.event.srcElement.type != "text" && window.event.srcElement.type != "textarea")) { // 텍스트
			// 입력박스
			// 이외의
			// 입력에
			// 대하여
			if (window.event.keyCode == 8) { // 8 : BackSpace
				event.returnValue = false;
			}
		}
	}

	document.onkeydown = onKeyDown;
}

function gfLoginPage(refererURL) {
    location.href="/comm/login.do?refererUrl="+escape(refererURL);
}
/**
 * 인터넷 교보문고 로그인 팝업을 오픈한다.
 */
function gfLogin(refererURL,serverURL) {
	var isOpen = null;
	if (typeof (serverURL) == "undefined") {
	    serverURL = "http://www.kyobobook.co.kr";
	}
	
	if (typeof (refererURL) == "undefined") {
		isOpen = openWindow(serverURL+"/login/login.laf",
				"LoginPop", 420, 283);

		if (isOpen == null) {
			window.alert("차단된 팝업창을 허용해 주십시오.");
		}
	} else {
		isOpen = openWindow(serverURL+"/login/login.laf?retURL="
						+ escape(refererURL), "LoginPop", 420, 283);

		if (isOpen == null) {
			window.alert("차단된 팝업창을 허용해 주십시오.");
		}
	}
}

function gfLoginPopup(serverURL) {
    var refererURL = location.href;
    if (typeof (serverURL) == "undefined") {
        var serverURL = "http://www.kyobobook.co.kr";
    }
    document.body.style.overflow = "hidden";
    location.href = serverURL + "/login/login.laf";
}

/**
 * 인터넷 교보문고 아이디 검색 팝업을 오픈한다.
 */
function gfSearchId(serverURL) {
	var isOpen = null;
	
	if (typeof (serverURL) == "undefined") {
        serverURL = "http://www.kyobobook.co.kr";
    }
	
	isOpen = openWindow(serverURL+"/login/memberIDSearchForm.laf",
			"SearchId", 420, 283);

	if (isOpen == null) {
		window.alert("차단된 팝업창을 허용해 주십시오.");
	}
}

/**
 * 인터넷 교보문고 비밀번호 검색 팝업을 오픈한다.
 */
function gfSearchPw(serverURL) {
	var isOpen = null;
    if (typeof (serverURL) == "undefined") {
        serverURL = "http://www.kyobobook.co.kr";
    }	
	isOpen = openWindow(serverURL+"/login/memberPWSearchForm.laf",
			"SearchPw", 420, 283);

	if (isOpen == null) {
		window.alert("차단된 팝업창을 허용해 주십시오.");
	}
}

/**
 * 인터넷 교보문고 회원 가입으로 이동한다.
 */
function gfJoinMember(serverURL) {
    if (typeof (serverURL) == "undefined") {
        serverURL = "http://www.kyobobook.co.kr";
    }
    window.open(serverURL+"/member/joinIntro.laf");
}
/**
 * 로그아웃을 처리한다.
 */
function gfLogout(refererURL, serverURL) {
    if (typeof (serverURL) == "undefined") {
        serverURL = "http://www.kyobobook.co.kr";
    }
    location.href = serverURL+"/login/logout.laf?retURL="
			+ escape(refererURL);
}


function getFiles(editor) {
	  var files = editor.getFiles();

  	if (files == null) {
		    window.alert("업로드한 파일이 없습니다.");

        return;
	  }

	  for (var i = 0; i < files.length; i++) {
		    var str = "";

        str += "URL       : " + files[i].fileUrl + "\n";
        str += "저장 경로 : " + files[i].filePath + "\n";
        str += "원본 이름 : " + files[i].origName + "\n";
        str += "저장 이름 : " + files[i].fileName + "\n";
        str += "크     기 : " + files[i].fileSize;

		    window.alert(str);
	  }
}

function getImages(obj) {
    var images = obj.getImages();

    if (images == null) {
      window.alert("업로드한 이미지가 없습니다.");

      return;
    }

	  for (var i = 0; i < images.length; i++) {
		    var str = "";

        str += "URL       : " + images[i].fileUrl + "\n";
        str += "저장 경로 : " + images[i].filePath + "\n";
        str += "원본 이름 : " + images[i].origName + "\n";
        str += "저장 이름 : " + images[i].fileName + "\n";
        str += "크     기 : " + images[i].fileSize;

		    window.alert(str);
	  }
}

function itemInfo() {
    var items = obj.getItems();

    if (items == null) {
        window.alert("선택한 상품이 없습니다.");

        return;
    }

    for (var i=0; i<items.length; i++) {
        var str = "";
        
        str += "ejkGb   : " + items[i].ejkGb + "\n";
        str += "barcode : " + items[i].barcode;

        window.alert(str);
    }
}

// select값 가져옴
function getSelectValue(form_name, elm) {
	var obj = eval("document." + form_name + "." + elm);
	if (obj) {
		if (obj.length) {
			var inputStr = obj.options[obj.selectedIndex].value;
			return inputStr;
		} else {
			return obj.value;
		}
	} else {
		return '';
	}
}

// Radio 체크값 가져옴, 2004/11/01
// selectRadioValue("PageForm","ssn")
function getRadioValue(form_name, elm) {
	var obj = eval("document." + form_name + "." + elm);
	if (obj) {
		for (i = 0; i < obj.length; i++) {
			if (obj[i].checked == true) {
				return obj[i].value;
				break;
			}
		}
	}
	return '';
}


/*
체크되어있는 값을 한줄로 갖고 온다 -  "1,2,3,5" 이런식으로 document.all.객제명
*/
function GetValForCheckbox(ElementName, getEl){

    if (ElementName==undefined){
         return "" ;//object 찾지 못하면

    }else if(!(ElementName.length)){  //단독일때 즉, 배열이 아닐때

        if(ElementName.checked){

            var rtn_val='';//리턴 문자  
            rtn_val = getEl.value;
            return rtn_val;

        }else{

            return "";

        }
    }else{
    
        var rtn_val='';//리턴 문자
        var split_str=',';//구분 문자
        var EleSize=ElementName.length;
        var i=0;
        var i_sun=0;

        if(EleSize){ 

            for(i;EleSize>i;++i){

                if (ElementName[i].checked==true){//해당항목이 선택이면

                    if (i_sun > 0) rtn_val=rtn_val+split_str;//구분문자를 처음이 아니면 더해준다.

                        rtn_val=rtn_val+getEl[i].value;
                        i_sun++;// 체크하는 순번

                }//해당항목이 선택이면

            }
        }
        return rtn_val;
    }
}

/* 
다중 라디오(체크박스) 체크 value 리턴
*/
function radioValue(obj){
    var returnVal = "";
    
    if(obj==undefined){ //오브젝트를 찾지 못했다면
        returnVal = ""; 
    }else{
        if(obj.length == undefined){  //배열이 아니면(개체수가 한개이면)
            if(obj.checked) returnVal = obj.value;
        }else{
            for(i=0;i<obj.length;i++){
                if(obj[i].checked) returnVal = obj[i].value;
                if(returnVal!="") break;
            }
        }
    }
    return returnVal;
}
function positionSetup_view(obj){
    //alert(document.body.scrollHeight ); 
     var posTemp = document.documentElement.scrollTop+350;
     var objTemp="#"+obj;

     $(objTemp).css({
        //'top':posTemp+'px',
        'top':'50%',
        'left':'50%',
        'z-index':'500',        
        "margin-left":-($(objTemp).width()/2),
        "margin-top":-($(objTemp).height()/2) 
    });     
}

function openPopup_view(obj){
    positionSetup_view(obj)  //위치값 설정
    $("#"+obj).show();
}

function openId(obj){
    $(obj).parent().css('z-index','500');
    $(obj).parent().children(".one_popup").css('z-index','501');
    $(obj).parent().children(".one_popup").show();
    
}
function closeId(obj){
    $(obj).parent().children(".one_popup").hide();
    $(obj).parent().css('z-index','0');
} 
function subopenId(obj){ 
    $(obj).children(".two_popup").css('z-index','501'); 
    $(obj).children(".two_popup").show();
    $(obj).css('background-color','#efefef');
}
function subcloseId(obj){
    $(obj).children(".two_popup").hide();
    $(obj).css('z-index','0');
    $(obj).css('background-color','#fff');
}
function inEffect(obj){  
    $(obj).css('background-color','#efefef');
}
function outEffect(obj){
    $(obj).css('background-color','#fff');
}
function linkMove(obj){
    window.open(obj);
}

/**
*	상단 검색 ink 통합검색영역
*	2009-10-30,hoon
*/
function searchInk(form){
    if((form.vPstrKeyWord.value=='통합검색')||(form.vPstrKeyWord.value=='')){
        alert("검색어를 입력해주십시오");
        form.vPstrKeyWord.value='';
        form.vPstrKeyWord.focus();
        return false;
    }else{
        form.action = "/jsp/comm/charsetConv.jsp";
        return true;
    }
}

//초기화
var IdMenu = function() {
this.isMenuOver = false;
this.menuOverColor = "#e4ff75";
this.menuOutColor = "#ffffff";
}

//메뉴, 이벤트 핸들러 설정
IdMenu.prototype.init = function(menuId, onMouseDown) {
    this.menuId = menuId;
    document.onclick = onMouseDown;
}

//메뉴 숨김
IdMenu.prototype.hideAllMenu = function() {
    
    try{
        document.getElementById(this.menuId).style.display = 'none';
        overHide();
    }catch(e){}
}

//메뉴 노출
IdMenu.prototype.viewMenu = function(e, menuId) {
    if (menuId == "none") return;
    var menuLocBod = document.documentElement;
    var event = e || window.event;
    var xPos = event.pageX || event.clientX+menuLocBod.scrollLeft;
    var yPos = event.pageY || event.clientY+menuLocBod.scrollTop;

    with(document.getElementById(menuId).style) {
        top = (yPos+5)+'px';
        //left = xPos+'px';
        display = '';
    }
}

//메뉴에 마우스 올렸을때 이벤트 핸들러
IdMenu.prototype.menuOver = function(e, targetObj, targetId) {
    var event = e || window.event;
    this.isMenuOver = true;
    this.changeColor(targetObj);
}

//메뉴에 마우스 빠졌을때 이벤트 핸들러
IdMenu.prototype.menuOut = function(targetObj) {
    this.isMenuOver = false;
    this.changeColor(targetObj);
}

//메뉴색 변경
IdMenu.prototype.changeColor = function(targetObj) {
    if (typeof targetObj.isPainted == 'undefined') {
        targetObj.isPainted = false;
    }
    targetObj.style.backgroundColor = targetObj.isPainted? this.menuOutColor : this.menuOverColor;
    targetObj.isPainted = !targetObj.isPainted;
}

var idMenu = new IdMenu();

var NameView = function() {
    this.menuId;
    this.userId;
    this.targetId;
    this.openType;
    this.blogsrnb;
    this.targetsrnb;
    this.syscode;
    this.targetNick;
}


//메뉴 DIV 설정

var layerView = ''
  layerView +='<div id="idMenuDiv" style="position:absolute;display:none;top:0; margin-left:10px; z-index:600;">'
  layerView +='     <div class="id_box" >'
  layerView +='         <ul class="one_popup"> '
  layerView +='             <li onmouseover="inEffect(this);" onmouseout="outEffect(this);" onclick="nameView.validate(\'EVENT1\');" id="kids" style="display:none"><span>쪽지보내기</span></li>'
  layerView +='             <li onmouseover="inEffect(this);" onmouseout="outEffect(this);" onclick="nameView.validate(\'EVENT12\');" id="teen" style="display:none"><span>쪽지보내기</span></li>'
  layerView +='             <li onmouseover="inEffect(this);" onmouseout="outEffect(this);" onclick="nameView.validate(\'EVENT2\');"><span>북로그가기</span></li>'

  layerView +='             <li onmouseover="inEffect(this);" onmouseout="outEffect(this);" onclick="nameView.validate(\'EVENT3\');" id="kids1" style="display:none"><span>마이지식가기</span></li>'
  layerView +='             <li onmouseover="inEffect(this);" onmouseout="outEffect(this);" onclick="nameView.validate(\'EVENT4\');" id="kids2" style="display:none"><span>키위마법사</span></li>'

  layerView +='             <li onmouseover="inEffect(this);" onmouseout="outEffect(this);" onclick="nameView.validate(\'EVENT5\');" id="teen1" style="display:none"><span>마이지식Q가기</span></li>'
  layerView +='             <li onmouseover="subopenId(this);" onmouseout="subcloseId(this);" id="teen2" style="display:none"><span>마이멘토Q</span>'
  layerView +='                  <ul class="two_popup">'
  layerView +='                      <li onmouseover="inEffect(this);" onmouseout="outEffect(this);" onclick="nameView.validate(\'EVENT6\');"><span>마이멘토Q보기</span></li>'
  layerView +='                      <li onmouseover="inEffect(this);" onmouseout="outEffect(this);" onclick="nameView.validate(\'EVENT7\');"><span>멘토맺기</span></li>'
  layerView +='                      <li onmouseover="inEffect(this);" onmouseout="outEffect(this);" onclick="nameView.validate(\'EVENT8\');"><span>질문하기</span></li>'
  layerView +='                  </ul>'
  layerView +='             </li>'
  
  layerView +='             <li onmouseover="inEffect(this);" onmouseout="outEffect(this);" onclick="nameView.validate(\'EVENT9\');" id="blog1" style="display:none"><span>이웃 신청</span></li>'
  layerView +='             <li onmouseover="inEffect(this);" onmouseout="outEffect(this);" onclick="nameView.validate(\'EVENT10\');" id="blog2" style="display:none"><span>프로필보기</span></li>'
  layerView +='             <li onmouseover="inEffect(this);" onmouseout="outEffect(this);" onclick="nameView.validate(\'EVENT11\');" id="cafe1" style="display:none"><span>프로필보기</span></li>'
  
  layerView +='         </ul>'
  layerView +='     </div>'
  layerView +='</div>';



//초기화
NameView.prototype.init = function(openType) {
    
}

//쪽지보내기
NameView.prototype.sendno1 = function() {
  window.open("/mypage/mykids.do?leftCgtrIndex=12&memid="+this.targetId , "note_pop");
}

//블로그가기
NameView.prototype.sendno2 = function() {
  window.open("http://booklog.kyobobook.co.kr/"+this.targetId+"/" , "blog_pop");
}

//마이지식 가기
NameView.prototype.sendno3 = function(key) {
  if(key=='Y'){
      window.open("/mypage/mykids.do" , "my_pop");
  }else{
      window.open("/mypage/mykids.do?memid="+this.targetId+"&isMainYsNo=N" , "my_pop");
  }
}

//키위 마법사
NameView.prototype.sendno4 = function() {
  ufPopupMiniHome(this.targetId);
}

//프로필 가기
NameView.prototype.sendno8 = function() {
  window.open("/cafe/manage/popup/cafeMemberProfile.do?cafeSrnb="+this.blogsrnb+"&cafeMmbrSrnb="+this.targetsrnb, "", "width=400, height=400");
}

//틴큐 쪽지보내기
NameView.prototype.sendno10 = function() {
window.open("/mypage/myteen.do?isMainYsNo=N&myPageLeftIndex=31&memid="+this.targetId , "note_pop");
}

//틴큐 마이 지식큐(방문자)
NameView.prototype.sendno11 = function() {
window.open("/mypage/myteen.do?isMainYsNo=N&myPageLeftIndex=0&memid="+this.targetId , "note_pop");
}

//틴큐 마이 지식큐(자신)
NameView.prototype.sendno12 = function() {
window.open("/mypage/myteen.do?myPageLeftIndex=1&isMainYsNo=N", "note_pop");
}

//틴큐 멘토큐(방문자)
NameView.prototype.sendno13 = function() {
window.open("/mypage/myteen.do?myPageLeftIndex=4&isMainYsNo=N&memid="+this.targetId, "note_pop");
}

//틴큐 멘토큐(자신)
NameView.prototype.sendno14 = function() {
window.open("/mypage/myteen.do?myPageLeftIndex=6&isMainYsNo=N", "note_pop");
}

//질문하기
NameView.prototype.sendno14 = function() {
location.href = "/teen/mnto/formTeenMnto.do?myMntolist="+this.targetId;
}



//틴큐 멘토큐(방문자)
NameView.prototype.sendno21 = function() {
    $.post('/comm/mmbrFlag.do?memid='+this.targetId,'',function(data){
        nameView.question(data);
    });
}

NameView.prototype.question = function(checking) {
    if(checking =='1'){
        alert(this.targetNick+'님은 멘티상태로 질문을 하실 수 없습니다.');
    }else{
        location.href = "/teen/mnto/formTeenMnto.do?myMntolist="+this.targetId;
    }
}

//멘토맺기(2009-11-17 박동수)
NameView.prototype.sendno20 = function(){
    $.post('/comm/mmbrFlag.do?memid='+this.targetId,'',function(data){
        nameView.mntoaln(data);
    });
}
NameView.prototype.mntoaln = function(checking) {
    if(checking =='1'){
        alert(this.targetNick+'님은 멘티상태로 멘토 맺기를 하실 수 없습니다.');
    }else{
        window.open('/teen/comm/formMntoApln.do?mntoId='+this.targetId, 'commMntoAplnPopup', 'width=430, height=350, toolbar=no, location=no, status=no, menubar=no, scrollbar=yes, resizable=no');
    }
}

//메뉴 팝업, 클릭시 설정 초기화
NameView.prototype.layer = function(userId, targetId, blogsrnb, targetsrnb, syscode, targetNick) {
    
    switch (syscode) {
        case 'KIDS':
                document.getElementById("kids").style.display="";
                document.getElementById("kids1").style.display="";
                document.getElementById("kids2").style.display="";
                document.getElementById("teen").style.display="none";
                document.getElementById("teen1").style.display="none";
                document.getElementById("teen2").style.display="none";
                document.getElementById("blog1").style.display="none";
                document.getElementById("blog2").style.display="none";
                document.getElementById("cafe1").style.display="none";
            break;
        case 'TEEN':
                document.getElementById("kids").style.display="none";
                document.getElementById("kids1").style.display="none";
                document.getElementById("kids2").style.display="none";
                document.getElementById("teen").style.display="";
                document.getElementById("teen1").style.display="";
                document.getElementById("teen2").style.display="";
                document.getElementById("blog1").style.display="none";
                document.getElementById("blog2").style.display="none";
                document.getElementById("cafe1").style.display="none";
            break;
        case 'BLOG':
                try{
                document.getElementById("teen").style.display="";
                document.getElementById("blog1").style.display="";
                document.getElementById("blog2").style.display="";
                }catch(e){}
            break;
        case 'BLOGADMIN':
                try{
                document.getElementById("teen").style.display="";
                document.getElementById("blog2").style.display="";
                }catch(e){}
            break;
        case 'CAFE':
                document.getElementById("kids").style.display="none";
                document.getElementById("kids1").style.display="none";
                document.getElementById("kids2").style.display="none";
                document.getElementById("teen1").style.display="none";
                document.getElementById("teen").style.display="";
                document.getElementById("teen2").style.display="none";
                document.getElementById("blog1").style.display="none";
                document.getElementById("blog2").style.display="none";
                document.getElementById("cafe1").style.display="";
            break;
        }

    $.post('/comm/nickName.do','',function(data){
        nameView.id(data);
    });
  
    this.userId = userId;
    this.targetId = targetId;
    this.blogsrnb = blogsrnb;
    this.targetsrnb = targetsrnb;
    this.targetNick = targetNick;
}

NameView.prototype.id = function(userId) {
    this.userId = userId
}
//메뉴 클릭시 이벤트 핸들러
NameView.prototype.onMouseDown = function(e) {

  var event = e || window.event;
  var eventTarget = event.target || event.srcElement;

  var event_check = false;
  var event_check_etc = false;
      try {
          if(eventTarget.className.indexOf("nickname") > -1){
              event_check = true;
          }
      } catch(e) { }

      if (!this.isMenuOver) {
          idMenu.hideAllMenu();
      }
      try {
          if (event_check) {
              nameView.viewMenuLayer(event, idMenu.menuId);
              
          }
      } catch(e) { }
}

NameView.prototype.viewMenuLayer = function(e, menuId) {
if (menuId == "none") return;
var menuLocBod = document.documentElement;
var event = e || window.event;
var xPos = event.pageX || event.clientX+menuLocBod.scrollLeft;
var yPos = event.pageY || event.clientY+menuLocBod.scrollTop;

with(document.getElementById(menuId).style) {
  top = (yPos+5)+'px';
  left = xPos+'px';
  display = '';
}
}

//메뉴 유효성 판단
NameView.prototype.validate = function(key) {
var isAdmin = (this.userId == this.targetId) ? true : false;
var isLogin = (this.userId == null || this.userId == '' || this.userId == 'undefined') ? true : false;
switch(key) {
  case "EVENT1" :
      if (isAdmin) {
          alert("자신에게 쪽지를 보낼수 없습니다!");
      } else if(isLogin) {
          alert("로그인을 해주세요!");
      } else {
          this.sendno1();
      } break;
  case "EVENT2" :
          this.sendno2();
       break;
  case "EVENT3" :
      if (isAdmin) {
          this.sendno3('Y');
      } else {
          this.sendno3('N');
      } break;
  case "EVENT4" :
          this.sendno4();
       break;
  case "EVENT5" :
      if (isAdmin) {
          this.sendno12();
      } else if(isLogin) {
          alert("로그인을 해주세요!");
      } else {
          this.sendno11();
      } break;
  case "EVENT6" :
      if (isAdmin) {
          this.sendno14();
      } else if(isLogin) {
          alert("로그인을 해주세요!");
      } else {
          this.sendno13();
      } break;
  case "EVENT7" :
      if (isAdmin) {
          alert("자신과 맨토를 맺을 수 없습니다.");
      } else if(isLogin) {
          alert("로그인을 해주세요!");
      } else {
          //ufOpenCommMntoAplnPopup(this.targetId);
          this.sendno20();
      } break;
  case "EVENT8" :
      if (isAdmin) {
          alert("자신에게 질문을 할 수 없습니다.");
      } else if(isLogin) {
          alert("로그인을 해주세요!");
      } else {
          this.sendno21();
      } break;
  case "EVENT9" :
      if (isAdmin) {
          alert("자신에게 이웃을 신청할수 없습니다");
      } else if(isLogin) {
          alert("로그인을 해주세요!");
      } else {
          openNeigPopupForId(this.targetId); //this.sendno7();
      } break;
  case "EVENT10" :
      gotoProfile(this.targetId); //this.sendno7();
      break;
  case "EVENT11" :
      if (isAdmin) {
          //alert("클릭한 아이디랑 로그인한 아이디랑 같을때 행동");
          //this.sendno8();
          alert("준비중입니다.");
      } else if(isLogin) {
          alert("로그인을 해주세요!");
      } else {
          this.sendno8();
      } break;
  case "EVENT12" :
      if (isAdmin) {
          alert("자신에게 쪽지를 보낼수 없습니다!");
      } else if(isLogin) {
          alert("로그인을 해주세요!");
      } else {
          this.sendno10();
      } break;
  }
}

var nameView = new NameView();

idMenu.init('idMenuDiv', nameView.onMouseDown)

function boxViewReady(view){
appname = navigator.appName;
useragent = navigator.userAgent;

nameView.init(view);
if(appname == 'Microsoft Internet Explorer'){
    if(!document.getElementById("idMenuDiv")){
        document.write(layerView);         
    }      
}else{
    if(!document.getElementById("idMenuDiv")){
        
        if(document.getElementById("wrap")){
            document.getElementById("wrap").innerHTML = layerView;
        }
    }     
}
}
boxViewReady('idbox');