/*** prototype ***/

String.prototype.trim = function() { 
	return this.replace(/(^\s*)|(\s*$)/g, ""); 
}

String.prototype.str_replace = function(str1,str2) {
	return this.split(str1).join(str2);
}

String.prototype.josa = function(nm) {
	var nm1 = nm.trim().substring(0, nm.trim().indexOf("/"));
	var nm2 = nm.trim().substring(nm.trim().indexOf("/") + 1, nm.trim().length);
	var a = this.substring(this.length - 1, this.length).charCodeAt();
	a = a - 44032;
	var jongsung = a % 28;
	return (jongsung) ? nm1 : nm2;
}


/*** essential func. ***/

function _ID(id) {
	return document.getElementById(id);
}

function array_search(needle,haystack){
	for(var i in haystack){
		if(haystack[i]==needle){return i;}    
	}
	return false;
}

function addOnloadEvent(fnc) {
	if (typeof window.addEventListener!="undefined") window.addEventListener( "load", fnc, false );
	else if (typeof window.attachEvent!="undefined") window.attachEvent( "onload", fnc );
	else {
		if (window.onload!=null){
			var oldOnload = window.onload;
			window.onload = function ( e ) {
				oldOnload( e );
				window[fnc]();
			};
		} else window.onload = fnc;
	}
}

function get_objectTop(obj) {
	if (obj.offsetParent==document.body || obj==document.body) return obj.offsetTop;
	else return obj.offsetTop + get_objectTop(obj.offsetParent);
}

function get_objectLeft(obj) {
	if (obj.offsetParent==document.body) return obj.offsetLeft;
	else return obj.offsetLeft + get_objectLeft(obj.offsetParent);
}

function embed(src,width,height,vars)
{
	document.write('\
	<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="'+width+'" HEIGHT="'+height+'">\
	<PARAM NAME=movie VALUE="'+src+'">\
	<PARAM NAME=quality VALUE=high>\
	<PARAM NAME=wmode VALUE=transparent>\
	<PARAM NAME=bgcolor VALUE=#FFFFFF>\
	<param name=flashvars value="' + vars + '">\
	<EMBED src="'+src+'" quality=high bgcolor=#FFFFFF WIDTH="'+width+'" HEIGHT="'+height+'" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer" flashvars="' + vars + '"></EMBED>\
	</OBJECT>\
	');
}

function getCookieVal (offset) { 
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
 } 
 
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 "";
}

function setCookie (name, value) { 
	var argv = setCookie.arguments;
	var argc = setCookie.arguments.length;
	var expires = (2 < argc) ? argv[2] : null;
	var path = (3 < argc) ? argv[3] : null;
	var domain = (4 < argc) ? argv[4] : null;
	var secure = (5 < argc) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");
}

/*** user func. ***/

function comma(x) {
	var temp = "";
	var x = String(uncomma(x));
	num_len = x.length;
	co = 3;
	while (num_len>0){
		num_len = num_len - co;
		if (num_len<0){
			co = num_len + co;
			num_len = 0;
		}
		temp = ","+x.substr(num_len,co)+temp;
	}
	return temp.substr(1);
}

function uncomma(x) {
	var reg = /(,)*/g;
	x = parseInt(String(x).replace(reg,""),10);
	return (isNaN(x)) ? 0 : x;
}

function autoComma(obj){
	if (event.keyCode!=9) obj.value=comma(obj.value);
}

function onlynumber(fld) {
	return;
	var e = event.keyCode;
	document.status = e;
	if (e>=48 && e<=57) return;
	if (e>=96 && e<=105) return;
	if (e==8 || e==9 || e==13 || e==45 || e==46) return;
	event.returnValue = false;
	alert('¼ýÀÚ¸¸ ÀÔ·Â°¡´ÉÇÕ´Ï´Ù');
	fld.value = "";
}

function onlynumber_price(fld) {
	return;
	var e = event.keyCode;
	document.status = e;
	if (e>=48 && e<=57) return;
	if (e>=96 && e<=105) return;
	if (e==8 || e==9 || e==13 || e==45 || e==46) return;
	event.returnValue = false;
	alert('°´½Ç¿ä±ÝÀº ¼ýÀÚ¸¸ ÀÔ·ÂÇÏ¼Å¾ß ÇÕ´Ï´Ù.');
	fld.value = "";
}

function chkBox(El,mode) {
	if (!El) return;
	if (typeof(El)!="object") El = document.getElementsByName(El);
	for (i=0;i<El.length;i++){
		El[i].checked = (mode=='rev') ? !El[i].checked : mode;
		if (El[i].disabled) El[i].checked = false;
	}
}

/*** Ã¼Å©¹Ú½º ÀÏ°ý º¯°æ ***/
function chkrev(El,mode) {
	if (!El) return;
	if (typeof(mode)=="undefined") mode = "rev";
	if (typeof(El)!="object") El = document.getElementsByName(El);
	for (i=0;i<El.length;i++){
		El[i].checked = (mode=='rev') ? !El[i].checked : mode;
		if (El[i].disabled) El[i].checked = false;
	}
}

function isChked(El,msg) {
	if (!El) return;
	if (typeof(El)!="object") El = document.getElementsByName(El);
	if (El) for (i=0;i<El.length;i++) if (El[i].checked) var isChked = true;
	if (isChked) return (msg) ? confirm(msg) : true;
	else {
		alert ("¼±ÅÃµÈ »çÇ×ÀÌ ¾ø½À´Ï´Ù");
		return false;
	}
}

function vLayer(obj,mode) {
	if (typeof(obj)!="object") obj = _ID(obj);
	if (typeof(obj)=="undefined" || obj==null) return;
	if (!mode) obj.style.display = (obj.style.display!="block") ? "block" : "none";
	else obj.style.display = mode;
}

function popup(src,width,height) {
	var scrollbars = "1";
	var resizable = "no";
	if (typeof(arguments[3])!="undefined") scrollbars = arguments[3];
	if (arguments[4]) resizable = "yes";
	window.open(src,'','width='+width+',height='+height+',scrollbars='+scrollbars+',toolbar=no,status=no,resizable='+resizable+',menubar=no');
}

function popupZipcode(rfunc)
{
	var dir = "";
	if (arguments[1]) dir = arguments[1];
	window.open(dir+'../module/zipcode.php?rfunc='+rfunc,'','width=400,height=350,scrollbars=0');
}

function getDiscount(price,code) {
	if (!code) return 0;
	if (code.charAt(code.length-1)!="%") return code;
	code = code.substr(0,code.length-1);
	var div = (arguments[2]==null) ? 1 : arguments[2];
	var ret = rounddown(price * code / 100,div);
	return ret;
}

function rounddown(x)
{
	var div = (arguments[1]==null) ? 1 : arguments[1];
	var t = Math.pow(10,div);
	x = Math.floor(x / t) * t;
	return x + 0;
}

function roundup(x){
	var div = (arguments[1]==null) ? 1 : arguments[1];
	var t = Math.pow(10,div);
	x = Math.ceil(x / t) * t;
	return x + 0;
}

function putCell(obj,inner)
{
	var tmp = obj.insertCell();
	tmp.innerHTML = inner;
}

function putInput(fm,name,value)
{
	var obj = document.createElement('input');
	obj.name = name;
	obj.value = value;
	fm.insertBefore(obj);
}

function in_array(val,arr)
{
	for (var i=0;i<arr.length;i++){
		if (arr[i]==val) return true;
	}
	return false;
}

/**
 * selectDisabled(oSelect)
 *
 * ¼¿·ºÆ®¹Ú½º¿¡ disabled ¿É¼ÇÃß°¡
 */
function selectDisabled(oSelect) {
	var isOptionDisabled = oSelect.options[oSelect.selectedIndex].disabled;
    if (isOptionDisabled){
        oSelect.selectedIndex = oSelect.preSelIndex;
        return false;
    } else oSelect.preSelIndex = oSelect.selectedIndex;
    return true;
}

function chkDisabeld(obj)
{
	if (!selectDisabled(obj)) return false;
}

/*** Àå¹Ù±¸´Ï »óÇ° °³¼ö ¼öÁ¤ ***/
function chgCart(obj,idx)
{
	var ret = parseInt(obj.value) + idx;
	if (ret<1) ret = 1;
	if (obj.getAttribute('min') && ret<obj.getAttribute('min')) ret = obj.getAttribute('min');
	if (obj.getAttribute('max') && ret>obj.getAttribute('max')) ret = obj.getAttribute('max');
	obj.value = ret;
}

/*** ³¯Â¥ ÀÚµ¿ »ðÀÔ ***/
function autoDate(obj1,obj2,val1,val2)
{
	if (typeof(obj1)!=Object) obj1 = _ID(obj1);
	if (typeof(obj2)!=Object) obj2 = _ID(obj2);
	obj1.value = val1;
	obj2.value = val2;
}

/*** ½ºÅ©·Ñ Á¦¾î ***/
function innerScroll(obj)
{
	if (event.wheelDelta >= 120) obj.scrollTop -= 40;
	else if (event.wheelDelta <= -120) obj.scrollTop += 40;
	//obj.scrollBy(0,event.wheelDelta / -3);
	return false;
}

function mTop(fstx,fsty,lstx,lsty) {
	var Timer;
	var winHeight = document.body.scrollTop;
	if(Timer) clearTimeout(Timer);
	
	startx = 0;
	starty = winHeight;
	if(!fstx || fstx < 0) fstx = 0;
	if(!fsty || fsty < 0) fsty = 0;
	
	var speed = 7;
	if(!lstx) lstx = 0 + startx;
	if(!lsty) lsty = 0 + starty;
	lstx += (fstx - startx) / speed;
	if (lstx < 0) lstx = 0;
	lsty += (fsty - starty) / speed;
	if (lsty < 0) lsty = 0;
	var posX = Math.ceil(lstx);
	var posY = Math.ceil(lsty);
	window.scrollTo(posX, posY);
	if((Math.floor(Math.abs(startx - fstx)) < 1) && (Math.floor(Math.abs(starty - fsty)) < 1)){
		clearTimeout(Timer);
		//window.scroll(fstx,fsty);
	}
	else if(posX != fstx || posY != fsty){
		Timer = setTimeout("mTop("+fstx+","+fsty+","+lstx+","+lsty+")",15);
	}
	else{
		clearTimeout(Timer);
	}
}

/*** blink ÅÂ±×È¿°ú ***/
function doBlink() {
    var blink = document.all.tags("BLINK");
    for (var i=0; i < blink.length; i++) {
        blink[i].style.visibility = (blink[i].style.visibility =="visible") ? "hidden":"visible";
    }
}
if (document.all) setInterval("doBlink()",500);

/*** »óÇ° ÆË¾÷À©µµ¿ì¿¡¼­ ±¸¸Å¹öÆ° ÀÌº¥Æ® ***/
function exec_dyn(fm,mode)
{
	if (chkForm(fm)){
		if (mode=="wishlist") fm.action = "../mypage/wishlist.php";
		else fm.action = "../order/cart.php";
		fm.mode.value = mode;
		fm.submit();
	}
}

/*** »óÇ° ½ºÅ©·Ñ ***/
function eScroll(obj)
{
	var inner;
	var _self = this;
	var d = 1;
	var cnt = 0;
	var delay = 100;

	this.per = 0;

	this.init = function(){
		if (typeof(obj)!='Object') obj = $(obj);
		obj.style.overflow = "hidden";
		//obj.innerHTML = "<table cellpadding=0 cellspacing=0><tr><td>" + obj.innerHTML + "</td><td>" + obj.innerHTML + "</td></tr></table>";
		this.act(1);
	}

	this.go = function(idx)
	{
		d = idx;
	}

	this.scroll = function()
	{
		if (this.per && obj.scrollLeft%this.per==0 && cnt<delay){
			cnt++;
			return;
		}
		cnt = 0;

		obj.scrollLeft += d;
		
		if (obj.scrollLeft==0) obj.scrollLeft = obj.scrollWidth - obj.offsetWidth;
		else if (obj.scrollWidth==obj.offsetWidth+obj.scrollLeft){
			obj.scrollLeft = 0;
		}
	}

	this.act = function(idx)
	{
		if (idx) this.tObj = setInterval(function(){_self.scroll()},5);
		else clearTimeout(this.tObj);
	}
	
}

function removeNode(o){ return o.parentNode.removeChild(o); }

function chgCity(category,city){	
	var obj = _ID('rCity');
	obj.options.length = 1;

	if (!category){
		alert('³ª¶ó¸¦ ¼±ÅÃÇØÁÖ¼¼¿ä');
		obj.options.length = 1;
		return;
	}
	
	new Ajax.Request('../main/indb.php',{
		parameters:	'mode=chgCity&category=' + category,
		onComplete: showResponse
	});

	function showResponse(data){
		var ret = data.responseText;
		var div = ret.split(",");
		
		for (var i=0;div.length;i++){
			var txt = div[i].split("=");
			obj.options[i+1] = new Option(txt[1],txt[0]);
			if (city && city == txt[0]) obj.options[i+1].selected = true;
		}
	}
}

function chg_country(category){
	if(category!='') location.replace('list.php?category='+category);
}

function validate(){
	var userNm = document.pageForm.name;
	var userNo1 = document.pageForm['resno[]'][0];
	var userNo2 = document.pageForm['resno[]'][1];
	var foreigner = document.pageForm.foreigner;
	var userNo = userNo1.value + userNo2.value;
	if ( userNm.value == "" ){
		//alert( getCheckMessage( "S23" ) );
		userNm.focus();
		return false;
	}
	if ( userNo1.value == "" ){
		if ( foreigner.value == "2" ) alert( getCheckMessage( "S27" ) );
		else alert( getCheckMessage( "S21" ) );
		userNo1.value = "";
		userNo1.focus();
		return false;
	}
	if ( userNo2.value == "" ){
		if ( foreigner.value == "2" ) alert( getCheckMessage( "S27" ) );
		else alert( getCheckMessage( "S21" ) );
		userNo2.value = "";
		userNo2.focus();
		return false;
	}
	if ( foreigner.value == "2" ){
		if ( checkForeignNm( userNm.value ) == false ){ 
			alert( getCheckMessage( "S28" ) );
			document.all.userNm.focus();
			return false;
		}
		if ( checkForeignNo( userNo ) == false ){
			alert( getCheckMessage( "S26" ) );
			document.all.userNo2.focus();
			return false;
		}
	} else {
		if ( checkString( userNm.value ) == false ){
			alert( getCheckMessage( "S24" ) );
			userNm.focus();
			return false;
		}
		if ( checkNumeric( userNo ) == false ){
			alert( getCheckMessage( "S25" ) );
			userNo1.focus();
			return false;
		}
	}
	return true;
}

function goIDCheck(){
	if ( validate() == true ){
		var strNm = document.pageForm.name.value;
		var strNo = document.pageForm['resno[]'][0].value + document.pageForm['resno[]'][1].value;
		var strRsn = document.pageForm.inqRsn.value;
		var strForeigner = document.pageForm.foreigner.value;
		document.inputForm.SendInfo.value = makeSendInfo( strNm, strNo, strRsn, strForeigner );
		var form = document.inputForm;
		form.submit();
	}
	return;
}


function mergeRow(tb,cell_index){
	for (var x=0;x<cell_index.length;x++){
		var idx = cell_index[x];
		var tmp = "";
		var pidx = 0;
		for (var i=0;i<tb.rows.length;i++){
			if (tmp==tb.rows[i].cells[idx].innerHTML){
				tb.rows[pidx].cells[idx].rowSpan++;
				tb.rows[i].deleteCell(idx); 
			} else {
				pidx = i;
				tmp = tb.rows[i].cells[idx].innerHTML;
			}
		}
	}
}

function strtotime (str, now) {
    // http://kevin.vanzonneveld.net
    // +   original by: Caio Ariede (http://caioariede.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: David
    // +   improved by: Caio Ariede (http://caioariede.com)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Wagner B. Soares
    // +   bugfixed by: Artur Tchernychev
    // %        note 1: Examples all have a fixed timestamp to prevent tests to fail because of variable time(zones)
    // *     example 1: strtotime('+1 day', 1129633200);
    // *     returns 1: 1129719600
    // *     example 2: strtotime('+1 week 2 days 4 hours 2 seconds', 1129633200);
    // *     returns 2: 1130425202
    // *     example 3: strtotime('last month', 1129633200);
    // *     returns 3: 1127041200
    // *     example 4: strtotime('2009-05-04 08:30:00');
    // *     returns 4: 1241418600
 
    var i, match, s, strTmp = '', parse = '';

    strTmp = str;
    strTmp = strTmp.replace(/\s{2,}|^\s|\s$/g, ' '); // unecessary spaces
    strTmp = strTmp.replace(/[\t\r\n]/g, ''); // unecessary chars

    if (strTmp == 'now') {
        return (new Date()).getTime()/1000; // Return seconds, not milli-seconds
    } else if (!isNaN(parse = Date.parse(strTmp))) {
        return (parse/1000);
    } else if (now) {
        now = new Date(now*1000); // Accept PHP-style seconds
    } else {
        now = new Date();
    }

    strTmp = strTmp.toLowerCase();

    var __is =
    {
        day:
        {
            'sun': 0,
            'mon': 1,
            'tue': 2,
            'wed': 3,
            'thu': 4,
            'fri': 5,
            'sat': 6
        },
        mon:
        {
            'jan': 0,
            'feb': 1,
            'mar': 2,
            'apr': 3,
            'may': 4,
            'jun': 5,
            'jul': 6,
            'aug': 7,
            'sep': 8,
            'oct': 9,
            'nov': 10,
            'dec': 11
        }
    };

    var process = function (m) {
        var ago = (m[2] && m[2] == 'ago');
        var num = (num = m[0] == 'last' ? -1 : 1) * (ago ? -1 : 1);

        switch (m[0]) {
            case 'last':
            case 'next':
                switch (m[1].substring(0, 3)) {
                    case 'yea':
                        now.setFullYear(now.getFullYear() + num);
                        break;
                    case 'mon':
                        now.setMonth(now.getMonth() + num);
                        break;
                    case 'wee':
                        now.setDate(now.getDate() + (num * 7));
                        break;
                    case 'day':
                        now.setDate(now.getDate() + num);
                        break;
                    case 'hou':
                        now.setHours(now.getHours() + num);
                        break;
                    case 'min':
                        now.setMinutes(now.getMinutes() + num);
                        break;
                    case 'sec':
                        now.setSeconds(now.getSeconds() + num);
                        break;
                    default:
                        var day;
                        if (typeof (day = __is.day[m[1].substring(0, 3)]) != 'undefined') {
                            var diff = day - now.getDay();
                            if (diff == 0) {
                                diff = 7 * num;
                            } else if (diff > 0) {
                                if (m[0] == 'last') {diff -= 7;}
                            } else {
                                if (m[0] == 'next') {diff += 7;}
                            }
                            now.setDate(now.getDate() + diff);
                        }
                }
                break;

            default:
                if (/\d+/.test(m[0])) {
                    num *= parseInt(m[0], 10);

                    switch (m[1].substring(0, 3)) {
                        case 'yea':
                            now.setFullYear(now.getFullYear() + num);
                            break;
                        case 'mon':
                            now.setMonth(now.getMonth() + num);
                            break;
                        case 'wee':
                            now.setDate(now.getDate() + (num * 7));
                            break;
                        case 'day':
                            now.setDate(now.getDate() + num);
                            break;
                        case 'hou':
                            now.setHours(now.getHours() + num);
                            break;
                        case 'min':
                            now.setMinutes(now.getMinutes() + num);
                            break;
                        case 'sec':
                            now.setSeconds(now.getSeconds() + num);
                            break;
                    }
                } else {
                    return false;
                }
                break;
        }
        return true;
    };

    match = strTmp.match(/^(\d{2,4}-\d{2}-\d{2})(?:\s(\d{1,2}:\d{2}(:\d{2})?)?(?:\.(\d+))?)?$/);
    if (match != null) {
        if (!match[2]) {
            match[2] = '00:00:00';
        } else if (!match[3]) {
            match[2] += ':00';
        }

        s = match[1].split(/-/g);

        for (i in __is.mon) {
            if (__is.mon[i] == s[1] - 1) {
                s[1] = i;
            }
        }
        s[0] = parseInt(s[0], 10);

        s[0] = (s[0] >= 0 && s[0] <= 69) ? '20'+(s[0] < 10 ? '0'+s[0] : s[0]+'') : (s[0] >= 70 && s[0] <= 99) ? '19'+s[0] : s[0]+'';
        return parseInt(this.strtotime(s[2] + ' ' + s[1] + ' ' + s[0] + ' ' + match[2])+(match[4] ? match[4]/1000 : ''), 10);
    }

    var regex = '([+-]?\\d+\\s'+
        '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'+
        '|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday'+
        '|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday)'+
        '|(last|next)\\s'+
        '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'+
        '|sun\\.?|sunday|mon\\.?|monday|tue\\.?|tuesday|wed\\.?|wednesday'+
        '|thu\\.?|thursday|fri\\.?|friday|sat\\.?|saturday))'+
        '(\\sago)?';

    match = strTmp.match(new RegExp(regex, 'gi')); // Brett: seems should be case insensitive per docs, so added 'i'
    if (match == null) {
        return false;
    }

    for (i = 0; i < match.length; i++) {
        if (!process(match[i].split(' '))) {
            return false;
        }
    }

    return (now.getTime()/1000);
}

function bannerstats(bannerno,category){

	new Ajax.Request('../ajax.php',{
		parameters:	'mode=bannerStats&bannerno=' + bannerno + '&category=' + category,
		onComplete: showResponse
	});

	function showResponse(data){
		var ret = data.responseText;
	}
	
}

function evalJSON(str){ return eval('(' + str + ')'); }

/*** iframe ³ôÀÌÁ¶Àý ***/
function resizeHeight(obj) {
	var frbody = obj.contentWindow.document.body;
	var height = frbody.scrollHeight + ( frbody.offsetHeight - frbody.clientHeight + 30);
	//$j(obj).css("height",height);
	$j(obj).height(height);
}
