﻿/**************************************************************************************************
* File Name		: Util.js
* Discription	: 공용 유틸 메소드 파일
* Write	Date	: 2010-01-25
* Writer		: ykums
**************************************************************************************************/


// 클라이언트 객체를 ID로 조회 하여 리턴한다.
function $get(element)
{
	return document.getElementById(element);
}

// 서버 객체를 ID로 조회 하여 리턴한다.
function $sget(element) 
{
	return document.getElementById(__ServerControl[element]);
}

// 클라이언트 객체를 이름으로 조회 하여 리턴한다.
function $nget(element) 
{
	return document.getElementsByName(element);
}

// String 객체에 trim 메소드를 추가 합니다.
String.prototype.trim = function() 
{
    return this.replace(/(^\s*)|(\s*$)|($\s*)/g, "");
}



//*****************************************************
// Util 클래스 저의
//*****************************************************

function Util() { }


// 쿠키값을 리턴합니다.
Util.getCookie = function(sCookieName)
{
	var sName = sCookieName + "=", ichSt, ichEnd;
	var sCookie = document.cookie;

	if (sCookie.length && (-1 != (ichSt = sCookie.indexOf(sName))))
	{
		if (-1 == (ichEnd = sCookie.indexOf(";", ichSt + sName.length)))
			ichEnd = sCookie.length;
		return unescape(sCookie.substring(ichSt + sName.length, ichEnd));
	}

	return "";
}


// 쿠키를 설정 합니다.
// domain, expiredays 파라미터는 옵셔널 파라미터 입니다.
// domain이 null이거나 입력하지 않을시 기본값은 시스템이 사용하는 쿠키 도메인 입니다.
Util.setCookie = function(sName, vValue, domain, expiredays)
{
	if (domain == undefined || domain == null)
		domain = Public.getCookieDomain();

	var sCookie = sName + "=" + escape(vValue, 0);

	if (domain != null && domain != "")
		sCookie += ";domain=" + domain + ";path=/";

	if (expiredays != null && expiredays != undefined) 
	{
		var today = new Date();
		today.setDate(today.getDate() + expiredays);
		sCookie += "; expires=" + today.toGMTString();
	}

	document.cookie = sCookie;
}


// 로컬 호스트 인지를 리턴합니다.
Util.isLocalHost = function()
{
	var url = document.location.href;

	if (url.indexOf("125.131") >= 0)
		return true;
	
	if (url.indexOf("localhost") < 0)
	{
		return false;
	}
	
	return true;
}


// 숫자를 ##,### 형태로 포맷팅 합니다.
Util.getNumberFormat = function(value)
{
	var str = value + "";
	var len = str.length;
	var buf = "";

	for (var i = 0; i < len; i++)
	{
		if (i != 0 && i % 3 == 0)
			buf = "," + buf;
		buf = str.charAt(len - (i + 1)) + buf;
	}

	return buf;
}



// 안전한(null 제외) 스트링 문자를 리턴합니다.
Util.safeString = function(strValue)
{
	return strValue == null ? "" : strValue;
}


// 안전한(null 제외) 숫자를 리턴합니다.
Util.safeInt = function(value, defValue)
{
	if (value == null || value == undefined || value.length == 0)
		return defValue;

	return parseInt(value);
}


// 전화번호를 - 로 파싱 하여 idx번째의 번호를 리턴합니다.
Util.getTelNo = function(telno, idx)
{
	var arrTelNo = telno.split("-");

	if (arrTelNo.length != 3)
	{
		if (idx == 0)
		{
			if (telno.length > 8)
			{
				if (telno.substr(0, 2) == "02")
					return telno.substr(0, 2);
				else
					return telno.substr(0, 3);
			}
		}
		else if (idx == 1)
		{
			if (telno.length > 8)
			{
				if (telno.substr(0, 2) == "02")
					return telno.substr(2, telno.length - (2 + 4));
				else
					return telno.substr(3, telno.length - (3 + 4));
			}
		}
		else
		{
			if (telno.length >= 4)
				return telno.substr(telno.length - 4, 4);
		}

		return "";
	}

	return arrTelNo[idx];
}



// 표준에러에 대한 에러 스트링을 리턴합니다.
Util.getStdErrMsg = function(strTitle, objResult)
{
	return strTitle + "\n" + "[" + objResult.ERR_NO + "]" + objResult.ERR_MSG;
}



// 화이트 스페이스여부를 리턴합니다.
Util.isWhiteSpace = function(inChar)
{
	return (inChar == ' ' || inChar == '\t' || inChar == '\n');
}

// 스트링의 문자열을 치환 합니다.
Util.replace = function(source, str1, str2) 
{
    var idx = source.indexOf(str1);

    if (idx >= 0) {
        var ret = "";

        if (idx > 0) {
            ret = source.substring(0, idx);
        }

        ret += str2;

        if (idx + str1.length < source.length) {
            ret += source.substring(idx + str1.length);
        }

        return Util.replace(ret, str1, str2);
    }

    return source;
}


Util.isNumber = function(str)
{
	if(str.length == 0)
	return false;

	for(var i=0; i < str.length; i++) {
		if(!('0' <= str.charAt(i) && str.charAt(i) <= '9'))
		return false;
	}
	return true;
}


Util.isPhoneNumber = function(str) {
	if (str.length == 0)
		return false;

	for (var i = 0; i < str.length; i++) {
		if (!(('0' <= str.charAt(i) && str.charAt(i) <= '9') || str.charAt(i) == "-"))
			return false;
	}
	return true;
}



Util.isHangul = function(str)
{
	var regexp = /[ㄱ-ㅎ|ㅏ-ㅣ|가-힝]/;

	if(regexp.test(str))
		return true;
	
	return false;
}



// 이벤트 핸들러를 등록 합니다.
// objid는 id거나 오브젝트 일수 있습니다.
Util.addEventHandler = function(objid, event, evnetfunc) 
{
	ControlUtil.addEventHandler(objid, event, evnetfunc);
}

// 서버객체의 이벤트 핸들러를 등록 합니다.
Util.addSEventHandler = function(objid, event, evnetfunc) 
{
	ControlUtil.addSEventHandler(objid, event, evnetfunc);
}


// 팝업을 오픈 합니다.
Util.openPopup = function(url, width, heigth, name) 
{
	var objPop = window.open(url, name, 'width=' + width + ', height=' + heigth + ', top=' + (screen.height - heigth) / 3 + ',left=' + (screen.width - width) / 2 + ', resize=no, scrollbars=no');
	objPop.focus();

	return objPop;
}

// 팝업을 오픈 합니다.
Util.openPopupScroll = function(url, width, heigth, name) {
	var objPop = window.open(url, name, 'width=' + width + ', height=' + heigth + ', top=' + (screen.height - heigth) / 3 + ',left=' + (screen.width - width) / 2 + ', resize=no, scrollbars=yes');
	objPop.focus();

	return objPop;
}

//페이지 리로드
Util.reloadPage = function()
{
	window.location.reload();
}


//페이지 GO
Util.goPage = function(url)
{
	window.location.href = url;
}



// aspx의 서버폼을 리턴합니다.
Util.getServerForm = function() 
{
	return ControlUtil.getServerForm();
}


// aspx의 서버폼을 서브밋 합니다.
// action은 옵셔널 파라미터 입니다.(없을경우 현재 페이지로 서브밋 됩니다.)
Util.submitServerForm = function(action) 
{
	ControlUtil.submitServerForm(action);
}

//이벤트 응모
Util.EventApply = function(eid) {
	Util.openPopup(Public.getWWWServerUrl("/Event/EventApply.aspx" + "?eid=" + eid), 416, 316, "EventApply");
}


Util.forwardOpener = function(url)
{
	try
	{
		if (url.substr(0, 7) == "http://" || url.substr(0, 8) == "https://")
		{
			var idx = url.indexOf("/", 9);

			if (idx >= 0)
			{
				if (url.substr(0, idx) != window.location.href.substr(0, idx))
				{
					var idx2 = url.indexOf("/", idx + 1);
					
					if (idx2 >= 0)
					{
						url = url.substr(0, idx2) + "/Common/SafeFowardOpener.aspx?fowardurl=" + escape(url);
						window.location.href = url;
						
						return false;
					}
				}
			}
		}

		window.opener.location.href = url;
	}
	catch(ex)
	{
		return false;
	}
	
	window.close();
}


//*****************************************************
// 컨트롤 유틸 클래스 정의
//*****************************************************

var ControlUtil = function() { }


// Util.getObjectToIEClientCoords 메소드에서 리턴하는 클래스 타입
ControlUtil.Position = function(x, y)
{
	this.X = x;
	this.Y = y;
}


// 클라이언트 객체의 포지션을 리턴 합니다.
ControlUtil.getObjectToIEClientCoords = function(strObjName)
{
	var x, y, elem1;

	elem1 = document.getElementById(strObjName);

	x = elem1.offsetLeft;
	y = elem1.offsetTop + elem1.offsetHeight;
	x = x - elem1.scrollLeft;
	y = y - elem1.scrollTop;

	elem1 = elem1.offsetParent;

	while (elem1 != null)
	{
		x = x + elem1.offsetLeft + elem1.clientLeft;
		y = y + elem1.offsetTop + elem1.clientTop;
		x = x - elem1.scrollLeft;
		y = y - elem1.scrollTop;

		elem1 = elem1.offsetParent;
	}

	return new ControlUtil.Position(x, y);
}


// 오브젝트를 디스플레이 하거나 감춘다.
ControlUtil.displayObject = function(objid, displayFlag) 
{
	if (objid == null)
		return;

	var obj = null;

	if (typeof (objid) == "string")
		obj = $get(objid);
	else
		obj = objid;

	if (obj == null)
		return;

	obj.style.display = displayFlag ? "" : "none";
}



ControlUtil.visibleObject = function(objid, visibleFlag) 
{
	if (objid == null)
		return;

	var obj = null;

	if (typeof (objid) == "string")
		obj = $get(objid);
	else
		obj = objid;

	if (obj == null)
		return;

	obj.style.visibility = visibleFlag ? "visible" : "hidden";
}


// 오브젝트의 디스플레이 속성을 토글 한다.
ControlUtil.toggleDisplayObject = function(objid) 
{
	if (objid == null)
		return;

	var obj = null;

	if (typeof (objid) == "string")
		obj = $get(objid);
	else
		obj = objid;

	if (obj == null)
		return;

	if (obj.style.display == "none")
		obj.style.display = displayFlag = "";
	else
		obj.style.display = displayFlag = "none";
}


ControlUtil.disableObject = function(objid, flag) 
{
	if (objid == null)
		return;

	var obj = null;

	if (typeof (objid) == "string")
		obj = $get(objid);
	else
		obj = objid;

	if (obj == null)
		return;

	obj.disabled = flag;
	obj.style.background = flag ? "#d3d3d3" : "#ffffff";
}


ControlUtil.focusObject = function(objid) 
{
	if (objid == null)
		return;

	var obj = null;

	if (typeof (objid) == "string")
		obj = $get(objid);
	else
		obj = objid;

	if (obj == null)
		return;

	obj.focus();
}


// 이벤트 핸들러를 등록 합니다.
// objid는 id거나 오브젝트 일수 있습니다.
ControlUtil.addEventHandler = function(objid, event, evnetfunc) 
{
	if (objid == null)
		return;

	var obj = null;

	if (typeof (objid) == "string")
		obj = $get(objid);
	else
		obj = objid;

	if (obj == null)
		return;

	Handler.add(obj, event, evnetfunc);
}


// 서버객체의 이벤트 핸들러를 등록 합니다.
ControlUtil.addSEventHandler = function(objid, event, evnetfunc) 
{
	var obj = $sget(objid);
	if (obj == null)
		return;

	Handler.add(obj, event, evnetfunc);
}


// aspx의 서버폼을 리턴합니다.
ControlUtil.getServerForm = function() 
{
	return document.forms["aspnetForm"];
}


// aspx의 서버폼을 서브밋 합니다.
// action은 옵셔널 파라미터 입니다.(없을경우 현재 페이지로 서브밋 됩니다.)
ControlUtil.submitServerForm = function(action) 
{
	var form = ControlUtil.getServerForm();

	if (action != undefined && action != null) 
	{
		form.action = action;
		$get("__VIEWSTATE").value = "";
	}
	
	form.submit();
}


ControlUtil.setEnterKeyEvent = function(id, func)
{
	ControlUtil.addEventHandler(id, "onkeypress", 
		function(e)
		{
			var ev = e;
			
			if (window.event) 
			{
				ev = window.event;
			}

			if (ev.keyCode == 13)
			{
				func();
			}
		}
	);
}




/* DateUtil 시작*/
var DateUtil = function() { };

/**
* 현재의 날짜를 숫자 8짜리 포맷으로 반환 (예 : 20070515)
* @return String 오늘 날짜
*/
DateUtil.GetCurrentDate = function() {
	var cur_date = GMKT.ServiceInfo.ServerTime;
	return DateUtil.FormatDate(cur_date);
};

/**
* 지정날짜에 추가일을 더한 포맷 날짜 문자열을 얻는다
* 
* @param {int} addValue 추가할 날짜 수
* @param {String} addType "yy", "mm", "dd" 중 한가지를 지정하며, 각 지정에 따라 연, 월, 일을 증가시킨다
* @param {String} nDate 기준 날짜, 지정되지 않을 경우 현재 날짜를 기준으로 한다
* @return String
*/
DateUtil.DateAdd = function(addValue, addType, nDate) {
	var dt = DateUtil.ReturnDateTypeValue(nDate);

	switch (addType.toLowerCase()) {
		case "yy":
			{// year
				dt.setFullYear(dt.getFullYear() + parseInt(addValue));
				break;
			}

		case "mm":
			{// month
				dt.setMonth(dt.getMonth() + parseInt(addValue));
				break;
			}
		case "dd":
			{// day
				dt.setDate(dt.getDate() + parseInt(addValue));
				break;
			}
	}

	return DateUtil.FormatDate(dt);
};

/* 날짜 --> Date형으로 return */
DateUtil.ReturnDateTypeValue = function(strDate) {
	var mmm = { "JAN": "01", "FEB": "02", "MAR": "03", "APR": "04", "MAY": "05", "JUN": "06", "JUL": "07", "AUG": "08", "SEP": "09", "OCT": "10", "NOV": "11", "DEC": "12" };
	var tmpDateString;

	if (strDate == null) {
		strDate = DateUtil.GetCurrentDate();
	}

	if (typeof (strDate) == "object") // DateTime 형식이라면
	{
		dt = strDate;
	}
	else {
		strDate = strDate.replace(/-/g, '').replace(/\//g, '').replace(/:/g, '').replace(/ /g, '').replace(/,/g, '');

		if (strDate.length == 8 || strDate.length == 14) // "yyyymmdd" or "yyyymmddhhmmss"
		{
			tmpDateString = strDate.substring(0, 4) + "/" + strDate.substring(4, 6) + "/" + strDate.substring(6, 8);
			dt = new Date(tmpDateString);
		}
		else if (strDate.length == 9 || strDate.length == 15) // "MMMddyyyy" or"MMMddyyyyhhmmss"
		{
			tmpDateString = strDate.substring(5, 9) + "/" + mmm[strDate.substring(0, 3).toUpperCase()] + "/" + strDate.substring(3, 5);
			dt = new Date(tmpDateString);
		}
	}
	return dt;
};

//*****************************************************************************************
// [선택] 지정날짜(Datetime)을 해당 포맷으로 전환한다.
// 인자
// nDate : 날짜, null일경우 오늘 날짜를 서버에서 가져온다
// nformat : 날짜포맷 예) yyyy년 MM월 dd일
// DateFormat은 config에 지정한 내용으로 고정
//*****************************************************************************************
DateUtil.FormatDate = function(nDate) {
	var dt = DateUtil.ReturnDateTypeValue(nDate);
	var MMM = { "01": "Jan", "02": "Feb", "03": "Mar", "04": "Apr", "05": "May", "06": "Jun", "07": "Jul", "08": "Aug", "09": "Sep", "10": "Oct", "11": "Nov", "12": "Dec" };
	var format = GMKT.ServiceInfo.DateFormat.replace(" HH:mm:ss", "");

	var y, m, d;
	y = dt.getFullYear();
	m = dt.getMonth() + 1;
	d = dt.getDate();

	m = m < 10 ? "0" + m : m;
	d = d < 10 ? "0" + d : d;

	format = format.replace("yyyy", y);
	format = format.replace("MMM", MMM[m]);
	format = format.replace("MM", m);
	format = format.replace("dd", d);

	return format;
};

/**
* 날짜의 차이를 계산하여 두 날짜 사이의 간격(단위:day)을 숫자로 반환
* 
* @param {String} date1 yyyymmdd or mmm dd,yyyy 무방함
* @param {String} date2 yyyymmdd or mmm dd,yyyy 무방함
* @return String
*/
DateUtil.DateDiff = function(date1, date2) {
	var sDate = DateUtil.ReturnDateTypeValue(date1);
	var eDate = DateUtil.ReturnDateTypeValue(date2);

	var timeSpan = (eDate - sDate) / 86400000;
	var daysApart = Math.abs(Math.round(timeSpan));

	return daysApart;
};
/* DateUtil 종료 */


/* PriceUtil 시작*/
var PriceUtil = function() { };

/* 국가별 Currency Formatting */
PriceUtil.FormatCurrency = function(money) {
	var sign, cents;

	money = money.toString().replace(/\$|\,/g, '');

	if (isNaN(money))
		money = "0";

	sign = (money == (money = Math.abs(money)));
	money = Math.floor(money * 100 + 0.50000000001);

	cents = money % 100;
	money = Math.floor(money / 100).toString();


	if (cents < 10) cents = "0" + cents;

	for (var i = 0; i < Math.floor((money.length - (1 + i)) / 3); i++)
		money = money.substring(0, money.length - (4 * i + 3)) + ',' + money.substring(money.length - (4 * i + 3));

	if (GMKT.ServiceInfo.nation == "SG") return (((sign) ? '' : '-') + money + "." + cents);
	else return (((sign) ? '' : '-') + money);
};

PriceUtil.FormatCurrencySymbol = function(money) {
	var newmoney = PriceUtil.FormatCurrency(money);
	
	if (GMKT.ServiceInfo.nation == "SG")
		return GMKT.ServiceInfo.currency + newmoney;
	else
		return newmoney + GMKT.ServiceInfo.currency;
};

/* 일반 숫자값 Formatting */
PriceUtil.FormatNumber = function(value) {
	value = value.toString().replace(/\$|\,/g, '');
	for (var i = 0; i < Math.floor((value.length - (1 + i)) / 3); i++)
		value = value.substring(0, value.length - (4 * i + 3)) + ',' + value.substring(value.length - (4 * i + 3));

	return value;
}

/* Config에 정의된 money_format에 맞춰서 관련된 반올림 정리 : 통화 관련된건 이걸 사용한다. */
PriceUtil.PriceCutting = function(value) {
	var format = GMKT.ServiceInfo.money_format;
	var digits;

	if (format.indexOf(".") == -1) {
		digits = 0;
	}
	else {
		digits = format.substr(format.indexOf(".") + 1, format.length).length;
	}

	return value;
	//return Utils.Round(value, digits);
}

PriceUtil.GetMoney = function(money) {
	money = money.toString().replace(/\S\$|\,/g, '');
	return parseFloat(money);
}

PriceUtil.ChangeFormatToNum = function(sValue){
	return sValue.toString().replace(/\$|\,/g,'');
}

/* PriceUtil 종료*/


String.format = function(text) {

	//check if there are two arguments in the arguments list
	if (arguments.length <= 1) {
		//if there are not 2 or more arguments there's nothing to replace
		//just return the original text
		return text;
	}

	//decrement to move to the second argument in the array
	var tokenCount = arguments.length - 2;
	for (var token = 0; token <= tokenCount; token++) {
		//iterate through the tokens and replace their placeholders from the original text in order
		text = text.replace(new RegExp("\\{" + token + "\\}", "gi"),
                                                arguments[token + 1]);
	}
	return text;
};

/* dreamweaver용 swap 스크립트 상세에 하도 사용을 해대서 util에 등록함. */
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
/* swap 스크립트 end*/