/**
 * common js
 *
 * @author artherot, sunny
 * @version 1.0
 * @since 1.0
 * @copyright Copyright (c), Godosoft
 */

$(document).ready(function(){
	/**
	 * 움직이는 스크롤배너
	 * @author sunny
	 */
	$(window).load(function () {
		if (self.name != 'easy') {
			if ($('.layout_leftscroll').length == 1 || $('.layout_rightscroll').length == 1) {
				var saLeftTop = saRightTop = 0;
				if ($('.layout_leftscroll').css('top') != null && $('.layout_leftscroll').css('top') != 'auto') {
					saLeftTop = eval($('.layout_leftscroll').css('top').replace(/px/,''));
				}
				if ($('.layout_rightscroll').css('top') != null && $('.layout_rightscroll').css('top') != 'auto') {
					saRightTop = eval($('.layout_rightscroll').css('top').replace(/px/,''));
				}
				$(window).scroll(function(){
					// 좌측스크롤
					var scrolledLeftTop = ( Math.max(document.documentElement.scrollTop, document.body.scrollTop) );
					scrolledLeftTop += (scrolledLeftTop < 10 ? saLeftTop : 10);
					$('.layout_leftscroll').animate({'top':scrolledLeftTop}, {duration:'slow', easing:'swing', queue:false});
					// 우측스크롤
					var scrolledRightTop = ( Math.max(document.documentElement.scrollTop, document.body.scrollTop) );
					scrolledRightTop += (scrolledRightTop < 10 ? saRightTop : 10);
					$('.layout_rightscroll').animate({'top':scrolledRightTop}, {duration:'slow', easing:'swing', queue:false});
				});
			}
		}
	});

	/**
	 * Global ajaxError
	 * @author sunny
	 */
	$(document).ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError) {
		if (XMLHttpRequest.status == '404' && XMLHttpRequest.statusText == 'Not Found') {
			alert('[Not Found]\nThe requested URL was not found.');
		} else if (XMLHttpRequest.status == '500' && XMLHttpRequest.statusText == 'Internal Server Error' && XMLHttpRequest.responseText !='') {
			alert(XMLHttpRequest.responseText);
		}
	});
});

/**
 * 자바스크립트 Trim함수
 * @return string 좌우 공백 제거한 문자열
 */
String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/, '');
};

/**
 * 자바스크립트 number_format 함수
 * @return string 문자열을 세자리 단위로 쉼표 찍기
 */
String.prototype.number_format = function()
{
	return this.replace(/(\d)(?=(?:\d{3})+(?!\d))/g,'$1,');
};

/**
 * 값이 배열 안에 존재하는지 확인
 * PHP의 in_array()와 동일한 기능
 * @author sunny
 * @param string needle 찾을 값
 * @return bool 배열에서 찾으면 TRUE를, 아니면 FALSE를 반환
 */
Array.prototype.in_array = function(needle)
{
	for (i = 0; i < this.length; i++) {
		if (this[i] == needle) return true;
	}
	return false;
};

/**
 * 값이 배열 안에 존재하는지 확인하여 키를 리턴
 * PHP의 array_search()와 동일한 기능
 * @author sunny
 * @param string needle 찾을 값
 * @return mixed 배열에서 찾으면 키를, 아니면 FALSE를 반환
 */
Array.prototype.array_search = function(needle)
{
	for (i = 0; i < this.length; i++) {
		if (this[i] == needle) return i;
	}
	return false;
};

/**
 * 이미지뷰어창 호출
 * image_viewer.htm은 전역에서 사용할 수 있는 이미지뷰어다
 * 이미지뷰어가 하는일은 매우 큰이미지든 작은이미지든 무리없이 볼 수 있게 해주는 화면이다.
 * @author sunny
 * @param string theURL 이미지경로
 * @return object Window 개체
 */
function image_viewer(theURL)
{
	var path = get_script_dirpath('_template/script/common.js');
	if (path == '') {
		var path = get_script_dirpath('module/script/common.js');
	}
	win = popup({
		url: path+'share/image_viewer.php?'+theURL
		, target: 'imageViewer'
		, width: 800
		, height: 600
		, resizable: 'yes'
	});
	win.focus();
	return win;
};

/**
 * PG 관련 영수증 보기
 * show_receipt.php는 전역에서 사용할 수 있는 PG 관련 영수증 정보 화일입니다.
 *
 * @author artherot
 * @param string modeStr 카드, 현금영수증 종류 (card, cash)
 * @param string orderNo 주문 번호
 */
function pg_receipt_view(modeStr, orderNo)
{
	var path = get_script_dirpath('module/script/common.js');

	// 사이즈를 미리 설정 - 자동으로 창이 커지지 않아 미리 설정함
	var preWidth	= 430;
	var preHeight	= 700;

	// 미리 팝업창을 띄우기
	var prePopupData	= {
		'url'		: 'about:blank',
		'target'	: 'show_receipt',
		'width'		: preWidth,
		'height'	: preHeight
	};
	var show_receipt = popup(prePopupData);

	// 각 PG별 영수증 팝업창
	$.post(path+'share/show_receipt.php',{ mode : modeStr, orderNo : orderNo }, function(data){
		var infoData = data;
		if (typeof infoData['error'] == 'undefined') {
			popup(infoData);
		} else {
			alert(infoData['error']);
			show_receipt.close();
		}
	}, 'json');
}

/**
 * 에스크로 구매확인 - 올더게이트용
 *
 * @author artherot
 */
function pg_escrow_confirm(escrowUrl,orderNo)
{
	// 사이즈를 미리 설정 - 자동으로 창이 커지지 않아 미리 설정함
	var preWidth	= 430;
	var preHeight	= 300;

	// 미리 팝업창을 띄우기
	var popupData	= {
		'url'		: escrowUrl+'?orderNo='+orderNo,
		'target'	: 'escrow_confirm',
		'width'		: preWidth,
		'height'	: preHeight
	};
	var show_confirm = popup(popupData);
}

/**
 * 에스크로 구매안전 서비스 확인창
 *
 * @author artherot
 * @param string widthSize 확인창의 가로 사이즈
 * @param string heightSize 확인창의 세로 사이즈
 */
function egg_check_view(widthSize, heightSize)
{
	var status  = 'width='+widthSize+' height='+heightSize+' menubar=no,scrollbars=no,resizable=no,status=no';
	var obj     = window.open('', 'egg_check_view', status);

	document.egg_check.target	= 'egg_check_view';
	document.egg_check.submit();
}

/**
 * 세금계산서 보기
 *
 * @author artherot
 * @param string orderNo 주문 번호
 * @param string modeStr 공급자 공급받는자 구분
 */
function tax_invoice_view(orderNo, modeStr)
{
	var path = get_script_dirpath('module/script/common.js');

	win = popup({
		url: path+'share/show_tax_invoice.php?orderNo='+orderNo+'&modeStr='+modeStr
		, target: 'tax_invoice'
		, width: 750
		, height: 600
		, resizable: 'yes'
		, scrollbars: 'yes'
	});
	win.focus();
	return win;
};

/**
 * 고도빌(전자 세금계산서) 보기
 *
 * @author artherot
 * @param string orderNo 주문 번호
 * @param string modeStr 공급자 공급받는자 구분
 */
function tax_godobill_view(godobillUrl)
{
	win = popup({
		url: godobillUrl
		, target: 'godobill_view'
		, width: 830
		, height: 450
		, resizable: 'yes'
		, scrollbars: 'yes'
	});
	win.focus();
	return win;
};

/**
 * 우편번호 찾기
 *
 * @author artherot
 * @param string codeID zipcode input ID
 * @param string addrID address input ID
 */
function zipcode_search(codeID, addrID)
{
	var path = get_script_dirpath('module/script/common.js');

	win = popup({
		url: path+'share/zipcode.php?codeID='+codeID+'&addrID='+addrID
		, target: 'zipcode'
		, width: 450
		, height: 460
		, resizable: 'yes'
	});
	win.focus();
	return win;
};

/**
 * 배송추적
 *
 * @author artherot
 * @param string deliverySno 택배사 코드
 * @param string invoiceNo 송장번호
 */
function delivery_trace(deliverySno, invoiceNo)
{
	var path = get_script_dirpath('module/script/common.js');

	win = popup({
		url: path+'share/delivery_trace.php?deliverySno='+deliverySno+'&invoiceNo='+invoiceNo
		, target: 'trace'
		, width: 650
		, height: 660
		, resizable: 'yes'
		, scrollbars: 'yes'
	});
	win.focus();
	return win;
};

/**
 * 쿠폰 적용 - 상품 쿠폰
 *
 * @author artherot
 * @param integer goodsNo 상품 번호
 * @param integer cartSno 장바구니 sno
 * @param integer goodsPrice 상품 가격
 * @param integer optionPrice 옵션 가격
 */
function coupon_apply_goods(goodsNo, cartSno, goodsPrice, optionPrice)
{
	var path = get_script_dirpath('module/script/common.js');

	win = popup({
		url: path+'share/coupon_apply_goods.php?goodsNo='+goodsNo+'&cartSno='+cartSno+'&goodsPrice='+goodsPrice+'&optionPrice='+optionPrice
		, target: 'coupon_goods'
		, width: 700
		, height: 400
		, resizable: 'yes'
		, scrollbars: 'yes'
	});
	win.focus();
	return win;
};

/**
 * 쿠폰 적용 - 주문 쿠폰
 *
 * @author artherot
 */
function coupon_apply_order()
{
	var path = get_script_dirpath('module/script/common.js');

	win = popup({
		url: path+'share/coupon_apply_order.php'
		, target: 'coupon_order'
		, width: 700
		, height: 400
		, resizable: 'yes'
		, scrollbars: 'yes'
	});
	win.focus();
	return win;
};

/**
 * 윈도우팝업 호출
 * @author sunny
 * @param array options 창정보
 * @return object Window 개체
 */
function popup(options)
{
	if (!options.width) options.width = 500;
	if (!options.height) options.height = 415;
	var status = new Array();
	$.each(options, function(i, v) {
		if (['url','target'].in_array(i) === false) {
			status.push(i+'='+v);
		}
	});
	var status = status.join(',');
	var win = window.open(options.url, options.target, status);
	return win;
}

/**
 * 해당되는 CheckBox 체크 여부
 * @author artherot
 * @param string chkID 체크 기준 checkbox ID
 * @param string targetName 타겟 checkbox의 공통적인 name 부분
 */
function check_toggle(chkID, targetName)
{
	var checkedStr	= '';
	if ($('input[id=\''+chkID+'\']').attr('checked') == true) {
		checkedStr	= 'checked';
	}
	$('input[name*=\''+targetName+'\']').attr('checked',checkedStr);
}

/**
 * 포커스이동
 * @author sunny
 * @param object self 자신 Element
 * @param object next 이동할 Element
 * @param int maxlen 문자 한계길이
 * @return
 */
function focusNext(self, next, maxlen)
{
	if (typeof(self) != 'object') return;
	if (typeof(next) != 'object') return;
	if (typeof(maxlen) != 'number') return;
	if ($(self).val().length >= maxlen) $(next).focus();
}

/**
 * 스크립트 디렉토리경로 리턴
 * @author sunny
 * @param string fileName 스크립트파일명
 * @return string 디렉토리경로
 */
function get_script_dirpath(fileName)
{
	var e = document.getElementsByTagName('script');
	for (var i = 0; i < e.length; i++) {
		regexp = new RegExp('(^|\/)' + fileName.replace('.','\.') +'([?#].*)?$', 'i');
		if(e[i].src && regexp.test(e[i].src)) {
			return thisScriptDir = e[i].src.replace(fileName, '');
		}
	}
}

/**
 * 플래시 태그
 * @author sunny
 * @param string src 플래시경로
 * @param string query 쿼리
 * @param int width 넓이
 * @param int height 높이
 * @param string vars flashvars
 */
function get_embed(src,query,width,height,vars)
{
	src += '?' + query;
	var codebase = "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0";
	var pluginspage = "http://www.macromedia.com/go/getflashplayer";

	if (document.location.protocol == "https:") {
		codebase = codebase.replace(/http:/, "https:");
		pluginspage = pluginspage.replace(/http:/, "https:");
	}

	var widthAttr = (width > 0 ? 'width="'+width+'"' : '');
	var heightAttr = (height > 0 ? 'height="'+height+'"' : '');
	var tag = '';
	tag += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+codebase+'" '+widthAttr+' '+heightAttr+'>';
	tag += '<param name="movie" value="'+src+'"/>';
	tag += '<param name="quality" value="high"/>';
	tag += '<param name="wmode" value="transparent"/>';
	tag += '<param name="bgcolor" value="#FFFFFF"/>';
	tag += '<param name="flashvars" value="' + vars + '"/>';
	tag += '<embed src="'+src+'" quality="high" wmode="transparent" bgcolor="#FFFFFF" '+widthAttr+' '+heightAttr+' type="application/x-shockwave-flash" pluginspage="'+pluginspage+'" flashvars="' + vars + '"></embed>';
	tag += '</object>';
	return tag;
}

/**
 * 플래시 출력
 * @author sunny
 * @param string src 플래시경로
 * @param string query 쿼리
 * @param int width 넓이
 * @param int height 높이
 * @param string vars flashvars
 */
function embed(src,query,width,height,vars)
{
	var tag = get_embed(src,query,width,height,vars);
	document.write(tag);
}

/**
 * Image Resize
 * @author sunny
 */
set_image_resize = function(img, reWidth, reHeight)
{
	if (reWidth == null) reWidth = 0;
	if (reHeight == null) reHeight = 0;
	// Original SIze
	viewImageOWidth = img.context.width;
	viewImageOHeight = img.context.height;
	// 비율
	var ratioHeight = reHeight / viewImageOHeight;
	var ratioWidth = reWidth / viewImageOWidth;
	var ratio = (ratioHeight > ratioWidth ? ratioWidth : ratioHeight);
	if (ratio > 1) {
		ratio = 1;
	}

	// 화면에 표시할 이미지사이즈를 구한다.
	var displayImgWidth = Math.round(viewImageOWidth * ratio);
	var displayImgHeight = Math.round(viewImageOHeight * ratio);

	// 이미지사이즈를 설정하고 css를 설정한다
	img.width(displayImgWidth).height(displayImgHeight);
};

/**
 * 이메일 도메인 대입
 *
 * @author artherot, sunny
 * @param string emailID email input ID
 * @param boolean overlap overlap_email
 */
function put_email_domain(emailID,overlap)
{
	if ($('#email_domain').val() != '' && $('#email_domain').val() != 'self') {
		$('#'+emailID).attr('disbled', false);
		$('#'+emailID).css('display', 'none');
		$('#'+emailID).val($('#email_domain').val());
	} else if ($('#email_domain').val() == 'self') {
		//$('#'+emailID).val('');
		$('#'+emailID).css('display', 'inline');
	}

	if (overlap == 'y') {
		eval(emailID).prepare();
	}
}

/**
 * 주문취소 사유
 *
 * @author artherot
 * @param string selectID reason select ID
 * @param string inputNm reason input Name
 */
function put_cancel_reason(selectID, inputNm)
{
	if ($('#'+selectID).val() != '' && $('#'+selectID).val() != 'self') {
		$('input[name=\''+inputNm+'\']').attr('disbled', false);
		$('input[name=\''+inputNm+'\']').css('display', 'none');
		$('input[name=\''+inputNm+'\']').val($('#'+selectID).val());
	} else if ($('#'+selectID).val() == 'self') {
		//$('input[name=\''+inputNm+'\']').val('');
		$('input[name=\''+inputNm+'\']').css('display', 'inline');
	}
}










$.warnUI = function(title, message, timeout, onClose) {
	var $m = $('<div class="warnUI"></div>');

	var $ml = $('<div class="warnUI_Left"></div>');
	var $mr = $('<div class="warnUI_Right"></div>');
	var $mc = $('<div class="warnUI_Center"></div>');

	var $mc_td = $('<td></td>');
	var $mc_tr = $('<tr></tr>');
	var $mc_table = $('<table width="100%" height="100%"></table>');

	if (title) $mc_td.append('<h1>'+title+'</h1>');
	if (message) $mc_td.append('<h2>'+message+'</h2>');

	$mc_tr.append($mc_td);
	$mc_table.append($mc_tr);
	$mc.append($mc_table);
	$mr.append($mc);
	$ml.append($mr);
	$m.append($ml);

	if (timeout == undefined) timeout = 2000;
	$.blockUI({
		message		: $m, fadeIn: 700, fadeOut: 1000, centerY: false,
		timeout		: timeout, showOverlay: false,
		onUnblock	: onClose,
		css			: {
			width :    '30%',
			border:   'none',
/*		    padding:  '3px',*/
		    opacity:   1,
			cursor:    null,
		    backgroundColor: "transparent",
/*			borderStyle: "solid",
			borderColor: "blue",*/
		    '-webkit-border-radius': '10px',
		    '-moz-border-radius':    '10px'
		}
	});
};

/**
 * 개체에 맞춰 이미지 크기 변환
 * @param contents 개체
 * @param objimg 이미지
 */
function miniSelfResize(contents,objimg)
{
	var objCon = document.getElementById(contents);
	objCon.style.display = 'block';
	objimg.style.display = 'none';
	fix_w = objCon.clientWidth;
	objimg.style.display = 'block';
	if (objimg.width > fix_w){
		objimg.width = fix_w;
		objimg.title = "popup original size Image";
	} else objimg.title = "popup original Image";
	objimg.style.cursor = "pointer";
	objimg.onclick = popupImg;
}

/**
 * 이미지 팝업 (삭제예정!!)
 * @param src 이미지 url
 * @param base path
 */
function popupImg(src,base)
{
	if (!src) src = this.src;
	if (!src) return;
	if (!base) base = "";
	window.open(base+'../board/viewImg.php?src='+escape(src),'','width=1,height=1');
}

/**
 * 수량 변경하기
 *
 * @param string inputName input box name
 * @param string modeStr up or dn
 * @param integer minCnt 최소수량
 * @param integer maxCnt 최대수량
 */
function count_change(inputName, modeStr, minCnt, maxCnt)
{
	var nowCnt	= parseInt($('input[name=\''+inputName+'\']').val());

	// 최소 수량 체크
	if (minCnt == 0 || minCnt == '' || typeof minCnt == 'undefined') {
		minCnt	= 1;
	}
	if (nowCnt < minCnt) {
		nowCnt	= parseInt(minCnt);
	}

	// 최대 수량 체크
	if (maxCnt == 0 || maxCnt == '' || typeof maxCnt == 'undefined') {
		var maxCntChk	= false;
	} else {
		var maxCntChk	= true;
		maxCnt	= parseInt(maxCnt);
	}

	if (isNaN(nowCnt) === true) {
		var thisCnt	= minCnt;
	} else {
		if (modeStr == 'up') {
			if (maxCntChk === true && nowCnt == maxCnt) {
				var thisCnt	= nowCnt;
			} else {
				var thisCnt	= nowCnt + 1;
			}
		} else if (modeStr == 'dn') {
			if (nowCnt > minCnt) {
				var thisCnt	= nowCnt - 1;
			}
		}
	}
	$('input[name=\''+inputName+'\']').val(thisCnt);
	$('input[name=\''+inputName+'\']').focus();
}

/**
 * show(block)
 * @author sunny
 */
$.fn.showup = function () {
	var docSize = parseInt($(document).width());
	if ($(this).css('position') == 'absolute') {
		$(this).css({'left':'10px','right':'auto'});
	}
	$(this).show();
	if ($(this).css('position') == 'absolute') {
		var offset = $(this).offset();
		var boxSize = parseInt(offset.left) + parseInt($(this).width());
		if (docSize <= boxSize) {
			$(this).css({'left':'auto','right':'10px'});
		}
	}
};

/**
 * 이벤트 무료화
 * @author sunny
 */
function event_hold(e){
	if (window.netscape) {
		e.preventDefault();
	} else {
		event.returnValue = false;
	}
}

/**
 * 기간차
 * @author sunny
 * @param string $sdate Start date
 * @param string $edate End date
 * @return int
 */
function between_date(sdate,edate)
{
	// 시작일
	sdate = sdate.replace(/-/g,'');
	var year = sdate.substr(0,4);
	var month = sdate.substr(4,2) - 1;
	var day = sdate.substr(6,2);
	var sDay = new Date(year,month,day);
	// 종료일
	edate = edate.replace(/-/g,'');
	var year = edate.substr(0,4);
	var month = edate.substr(4,2) - 1;
	var day = edate.substr(6,2);
	var eDay = new Date(year,month,day);
	// 차이
	var gap = sDay.getTime() - eDay.getTime();
	gap = Math.floor(gap / (1000 * 60 * 60 * 24));
	return Math.abs(gap);
}

/**
 * 문자열 Parse
 * @author sunny
 */
String.prototype.parse_str = function()
{
	var arr = {};
	var tmp = this.split('&');
	$.each(tmp, function() {
		var tmp2=this.split('=');
		arr[tmp2[0]] = tmp2[1];
	});
	return arr;
};

/**
 * 숫자의 올림 반올림 내림 처리
 *
 * @author artherot
 * @param integer numberInt 계산할 숫자
 * @param integer unit 자리수
 * @param string methodStr 올림 반올림 내림 방법 (up, half, down)
 * @return integer 계산된 숫자
 */
function get_number_figure(numberInt, unit, methodStr)
{
	if (unit == '' || unit == 0) {
		return numberInt;
	}

	// 올림
	if (methodStr == 'up') {
		return Math.ceil( numberInt / (unit * 10)) * (unit * 10);

	// 반올림
	} else if (methodStr == 'half') {
		return Math.round( numberInt / (unit * 10)) * (unit * 10);

	// 내림
	} else if (methodStr == 'down') {
		return Math.floor( numberInt / (unit * 10)) * (unit * 10);

	// 설정이 없는 경우
	} else {
		return numberInt;
	}
}

/*
 * 페이지별 스타일 적용.
 *
 * 스타일을 적용할 페이지를 pageinfo 에 추가.
 *
 *  ex)
 *	var pageinfo = {
 *		'/board/faq.php': [ // 페이지명
 *			{
 *				loc : 'table.list .contents p', // 적용할 스타일의 위치 selector
 *				style : { // 적용할 스타일.
 *					'margin' : '16px 0px 16px 0px',
 *					'padding' : '0px'
 *				}
 *			},
 *			{
 *				loc : 'table.list .contents img', // 적용할 스타일의 위치 selector
 *				style : { // 적용할 스타일.
 *					'border' : '0px',
 *					'padding' : '0px'
 *				}
 *			}
 *		],
 *		'/event/event.php': [
 *			{
 *				loc : 'div p',
 *				style : {
 *					'margin' : '16px 0px 16px 0px'
 *				}
 *			}
 *		],
 *	};
 *
 */
function setPageStyle() {
	var pageinfo = {
		'/board/faq.php': [
			{
				loc : 'table.list .contents p',
				style : {
					'margin' : '16px 0px 16px 0px'
				}
			}
		],
		'/event/event.php': [
			{
				loc : 'div p',
				style : {
					'margin' : '16px 0px 16px 0px'
				}
			}
		]
	};

	var curpage = document.location.pathname;
	if (!pageinfo[curpage]) return;

	try {
		for (var i = 0; i < pageinfo[curpage].length; i++) {
			var obj = $(pageinfo[curpage][i]['loc']);
			for(var style in pageinfo[curpage][i]['style']) {
				obj.css(style, pageinfo[curpage][i]['style'][style]);
			}
		}
	}
	catch(e) {}
}
$(document).ready(function() {
	setPageStyle();
});
