var gvDefaultButtonOverColor = "#000000";
var gvDefaultButtonColor = "#FFFFFF";

//로딩중을 위한 아이프레임 및 div 선언
//document.write("<IFRAME style='DISPLAY: none; width:150px ; height:50px ; LEFT: 0px; POSITION: absolute; TOP: 0px' src=\"javascript:'';\" frameBorder='0' id=gvLoadingIFrame scrolling='no'></IFRAME>");
//document.write("<DIV style='padding-top:7px ;  text-align:center ; DISPLAY: none; LEFT: 0px; width:150px ; height:50px ; border:solid 2px #92BFD4 ; POSITION: absolute; TOP: 0px' id=gvLoadingDiv></DIV>");

String.prototype.trim=function() {
	var str=this.replace(/(\s+$)/g,"");
	return str.replace(/(^\s*)/g,"");
}

//태그만 제거  
String.prototype.stripTags = function() {  
	var str = this;  
	var pos1 = str.indexOf('<');  
	if (pos1 == -1) return str;  
	else {  
		var pos2 = str.indexOf('>', pos1);  
		if (pos2 == -1) return str;  
		return (str.substr(0, pos1) + str.substr(pos2+1)).stripTags();  
	}  
}  

function gfPopup(url, name, width, height, option) {
	if(width == null) width = 500;
	var screenWidth = 0;
	var screenHeight = 0;

	if(screen) {
		screenWidth = screen.width;
		screenHeight = screen.height;
		
	} else if (navigator.appName.substring(0,9) != "Microsoft" && navigator.javaEnabled())  {
		var toolkit = java.awt.Toolkit.getDefaultToolkit();
		var screen_size = toolkit.getScreenSize();
		screenWidth = screen_size.width;
		screenHeight = screen_size.height;
	}

	var left = screenWidth / 2 - width / 2;
	var top = screenHeight / 2 - height / 2;

	window.open(url, name, "height=" + height + ", width=" + width + ", top=" + top + ", left=" + left + ", " + option);
}

// 패스워드 조회
function gfSearchPW() {
	gfSetLink("/member/member.find.pwd.step1.php");
}

// 최근 1개월간 일별 가격
function gfMonthlyPrice(item) {
	gfPopup("/market/market.monthly.php?productkey=" + item + "&dataurl=" + encodeURIComponent("/market/market.ajax.monthly.php?productkey=" + item), "MONTHLY", 800, 450, 'scrollbars=yes');
}

// 제품별 갤러리
function gfGalleryByProduct(product) {
	gfPopup("/product/product.gallery.php?productkey=" + product, "P_GALLERY", 800, 700);
}

// 제품정보 보기 팝업
function gfProductInfo(item) {
	gfPopup("/product/product.view.php?productkey=" + item, "PRODUCT_INFO", 840, 600, 'scrollbars=yes');
}

// 쪽지보내기
function gfSendLetter(to) {
	gfPopup("/member/member.send.letter.php?receiver=" + to, 'SEND_LETTER', 590, 600, 'scrollbars=yes');	
}

// 회원정보 보기
function gfViewUser(id) {
	gfPopup("/member/member.info.php?userid=" + id, 'VIEW_INFO', 540, 500, 'scrollbars=yes');	
}

// 페이지 이동
var gvNowMoving = false;
function gfSetLink(url) {
	if(gvNowMoving) return;
	gvNowMoving = true;
	document.location.href = url;
}

function gfCheckStrLength(maxlen, val, maxbl) {  
    var ls_str = val;  
    var li_str_len = ls_str.length;  
    
    var li_max = maxlen;   
    var i = 0;   
    var li_byte = 0;   
    var li_len = 0;   
    var ls_one_char = "";  
    var ls_str2 = "";  
    
    for(i=0; i<li_str_len; i++) {  
        ls_one_char = ls_str.charAt(i);  
        
        if (escape(ls_one_char).length > 4)  
            li_byte += 2;  
        else  
            li_byte++;  
         
        if(li_byte <= li_max)  
            li_len = i + 1;  
    }  
    
    if(maxbl) {
	    if(li_byte > li_max) {  
	        return false;
	    }
    } else {
	    if(li_byte < li_max) {  
	        return false;
	    }
    }
    return true;
} 

// 값 체크
function gfValidate(arg) {
	
	for(var i = 0; i < arg.elements.length; i++ ) {
		var obj = arg.elements[i];
		if(obj == null) continue;
		var type = obj.getAttribute("type");
		var value = obj.value;
		var maxLength = obj.getAttribute("maxlength");
		var minLength = obj.getAttribute("minlength");
		var hname = obj.getAttribute("hname")==null?obj.getAttribute("name"):obj.getAttribute("hname");
		var limit = obj.getAttribute("limit");
		var required = obj.getAttribute("required");
		var nofocus = obj.getAttribute("nofocus");

		
		// 필수입력
		if(required != null && value.trim() == "") {
			alert(hname + " 항목은 필수입니다.");
			if(nofocus == null) obj.focus();
			return false;
		}
		
		// 최대 길이 
		if(maxLength != null && !gfCheckStrLength(maxLength, value, true)) {
			alert(hname + " 항목은 최대 " + maxLength + " byte 까지만 입력이 가능합니다.");
			if(nofocus == null) obj.focus();
			return false;
		}
		
		// 최소 길이 
		if(minLength != null && !gfCheckStrLength(minLength, value, false)) {
			alert(hname + " 항목은 최소 " + minLength + " byte 이상이어야만 합니다.");
			if(nofocus == null) obj.focus();
			return false;
		}		
		
		// 제한
		var pattern = "";
		var result = "";
		if(limit != null) {
		
			if(limit.toUpperCase() == "DATE") {
				if(!gfIsValidDate(value)) {
					alert(hname + " 항목의 날짜 입력이 이상합니다.");
					if(nofocus == null) obj.focus();
					return false;
				}
			
			} else {
					
				if(limit.toUpperCase() == "NUM") {
					pattern = /^[0-9-]+$/;
					msg = hname + " 항목은 숫자만 입력가능합니다.";
				} else if(limit.toUpperCase() == "ENG+NUM") {
					pattern = /^[a-zA-Z0-9-]+$/;
					msg = hname + " 항목은 숫자와 영문만 입력가능합니다.";
				
				} else if(limit.toUpperCase() == "ENG") {
					pattern = /^[a-zA-Z]+$/;
					msg = hname + " 항목은 영문만 입력가능합니다.";				
				} 
				
				if(!pattern.test(value)) {
					alert(msg);
					if(nofocus == null) obj.focus();
					return false;
				}
			}		
		}
	}
	
	return true;
}


//버튼
function gfMakeButton(id, name, func, color) {
	document.write(gfGetButtonTag(id, name, func, color));
}

// 버튼태그 생성
function gfGetButtonTag(id, name, func, color) {
	if(color == null) color = "orange";
	var bgImg = "btn." + color + ".bg.gif";
	var str = "<table type=button id='" + id + "' style='cursor:pointer' onclick=\"" + func + "\" cellspacing=0 cellpadding=0 border=0>";
	str += "<tr><td style=\"width:6px ; height:18px ; background-image:url('/common/images/" + bgImg + "')\"></td>";
	str += "<td style=\"height:18px ; padding-top:0px ; padding-left:5px ; padding-right:5px ; text-align:center ; background-image:url('/common/images/" + bgImg + "') ; color:" + gvDefaultButtonColor + "\" onmouseover='gfButtonMouseOver(this)' onmouseout='gfButtonMouseOut(this)'><b>" + name + "</b></td>";
	str += "<td style=\"width:6px ; height:18px ; background-image:url('/common/images/" + bgImg + "')\"></td>";
	str += "</tr></table>";
	return str;
}


//버튼을 위한 함수
function gfButtonMouseOver(obj) {
	obj.style.color = gvDefaultButtonOverColor;
}

function gfButtonMouseOut(obj) {
	obj.style.color = gvDefaultButtonColor;
}

//모든 버튼을 비활성화 한다
var gvIsAttachedEvent = new Array()
function gfDisableButton(isLoading, option) {
	if(isLoading == null) isLoading = false;

	// 프로그레스바
	if(isLoading) {
		gfShowLoadingBar(option);
	}

	var btn = document.getElementsByTagName("TABLE");
	for(var i=0 ; i<btn.length ; i++) {
		var t = btn[i].getAttribute("type");
		if(t != null && t == "button") {
			btn[i].disabled = true;
		}
	}
}

//모든 버튼을 활성화 한다
function gfEnableButton(isLoading) {
	if(isLoading == null) isLoading = false;
	if(isLoading) {
		gfHiddenLoadingBar();
	}
	var btn = document.getElementsByTagName("TABLE");
	for(var i=0 ; i<btn.length ; i++) {
		var t = btn[i].getAttribute("type");
		if(t != null && t == "button") {
			btn[i].disabled = false;
		}
	}
}

/************************************
 * 화면에 프로그레스바 보임/숨김
*************************************/
function gfShowLoadingBar(option) {
	var msg = "In Progress!";
	var width = null;
	var height = null;

	if(option != null) {
		option = option.toLowerCase();
		var arr1 = option.split(",");
		for(var i=0 ; i<arr1.length ; i++) {
			var arr2 = arr1[i].split("=");
			if(arr2.length != 2) continue;
			if(arr2[0] == "message") msg = arr2[1];
			else if(arr2[0] == "width") width = arr2[1];
			else if(arr2[0] == "height") height = arr2[1];
		}
	}

	//var ifr = $(gvLoadingIFrame);
	//var div = $(gvLoadingDiv);
	var ifr = document.getElementById("gvLoadingIFrame");
	var div = document.getElementById("gvLoadingDiv");	
	
	// 길이
	if(width != null) {
		ifr.style.width = width + "px";
		div.style.width = width + "px";
	}
	
	// 높이
	if(height != null) {
		ifr.style.height = height + "px";
		div.style.height = height + "px";
	}	
	
	var w = parseInt(div.style.width, 10);
	var h = parseInt(div.style.height, 10);
	
	// var dim = document.viewport.getDimensions();  <------- 왜 안먹을까나...
    var left = document.body.scrollWidth;
    var top = document.body.scrollHeight;
    var stop = document.body.scrollTop;
    var sleft = document.body.scrollLeft;
    var l = left / 2 - w / 2;
    var t = top / 2 - h / 2;

    ifr.style.left = l;
    ifr.style.top = t;	    
    div.style.left = l;
    div.style.top = t;	
	div.innerHTML = "<img src='/common/images/loading.gif' align=absmiddle> &nbsp;<b>" + msg + "</b>";

	ifr.style.display = "block";
	div.style.display = "block";
}

function gfHiddenLoadingBar() {
	//var ifr = $(gvLoadingIFrame);
	//var div = $(gvLoadingDiv);
	var ifr = document.getElementById("gvLoadingIFrame");
	var div = document.getElementById("gvLoadingDiv");
	ifr.style.display = "none";
	div.style.display = "none";	
}

// 로그오프	
function gfDoLogout(mode) {
	if(mode == null) mode = '';
	gfSetLink("/member/logout.php?mode=" + mode);
}

// 회원가입
function gfJoin() {
	gfSetLink("/member/member.join.php");
}

// 로그인
function gfLogin() {
	if(!gfValidate(frmLogin)) return false;
	frmLogin.submit();
}

// 콤마 넣기
 function gfSetNumberFormat(value) {
	var src;
	var i;
	var factor;
	var su;
	var Spacesize = 0;
	
	var String_val = value.toString();
	
	factor = String_val.length % 3;
	su = (String_val.length - factor) /3;
	src = String_val.substring(0,factor);
	
	for(i=0; i<su ; i++)
	{
	   if ((factor==0)&&(i==0))
	    {
	         src += String_val.substring(factor+(3*i), factor+3+(3*i));
	    }
	    else 
	    {
	        if ( String_val.substring(factor+(3*i) - 1, factor+(3*i)) != "-" ) src +=",";
	        src += String_val.substring(factor+(3*i), factor+3+(3*i));
	    }
	}
	return src;
}

// 쪽지가 와써용~~~~
var gvMessageBox = "<div id=divPushMessageBox class='pushmessage'>" +
							"<table class='pushmessagetable'>" + 
							"<tr><td align=center>" +
							"<table><tr><td align=center><img src='/common/images/message.png'><br>쪽지가 도착했어요</td></tr>" +
							"<tr><td align=center><table><tr><td>" + gfGetButtonTag('btnReadLetter', '12시간 이따 확인하기', 'gfCloseLetterBox()', 'gray') + "</td>" +
							"</td><td class=button>" + gfGetButtonTag('btnReadLetter', '쪽지 확인하기', 'gfCloseBoxReadLetter()', 'red')  + "</td></tr></table></tr>" +
							"</table></td></tr></table>" +
							"</div>";
var gvPupupMessageBox = false;							
document.write(gvMessageBox);							
function gfMakeLetterBox() {

	if(gvPupupMessageBox) return ;
	gvPupupMessageBox = true;	
	var w = $(document.body).width();
	var h = $(document.body).height();
	var t = $(document.body).scrollTop();
	
	$(".pushmessage").css("visibility", "visible");
	$(".pushmessage").css("filter", "alpha(opacity=80)");
	$(".pushmessage").css("top", t);
	$(".pushmessagetable").css("visibility", "visible");
	
	$(".pushmessage").animate({width:w, height:h}, "normal");
	$(".pushmessagetable").animate({width:w, height:h}, "normal");
}

function gfCloseLetterBox(bl) {

	if(bl == null) $.cookie('NO_READ_LETTER', 'T', { expires: 0.5, path:'/' });
	
	gvPupupMessageBox = false;
		
	$(".pushmessagetable").css("width", "0");
	$(".pushmessagetable").css("height", "0");
	$(".pushmessagetable").css("visibility", "hidden");

	$(".pushmessage").animate(
		{height:0, width:0}, 
		"normal",
		function () { $(".pushmessage").css("visibility", "hidden"); }
	);
}

// 메시지 읽기
function gfReadLetter() {
	gfPopup("/member/member.receiver.letter.php", "READ_LETTER", 590, 600, 'scrollbars=yes');		
}

function gfCloseBoxReadLetter() {
	gfCloseLetterBox(true);
	gfReadLetter();
}

// 날짜 유효성 체크
function gfIsValidDate(yyyymmdd) {
	if(yyyymmdd == null || yyyymmdd == "") return true;
	yyyymmdd = yyyymmdd.replace(/[-,]/gi, "");
	
	var y = yyyymmdd.substring(0, 4);
	var m = parseInt(yyyymmdd.substring(4, 6), 10);
	var d = parseInt(yyyymmdd.substring(6, 8), 10);

	var dt = new Date(y, m-1, d, 0, 0, 0, 0);
	if(dt == null) return false;
	
	if(dt.getFullYear() != y || dt.getMonth() != (m-1) || dt.getDate() != d) return false;
	
	return true;	
}


// 단축키
function gfSetHotKey(name, url) {
	if(!confirm(name + "(으)로 이동하시겠습니까?")) return false;
	gfSetLink(url);
}

function gfViewImage(url) {
	if(url == null || url == "") return false;	
	var t = $(document.body).scrollTop() + 10;	
	
	$("<div id=divTmpViewImage style='position:absolute ; left:10 ; top:" + t + " ; display:none ; z-index:999 ; cursor:pointer ; border:solid  ; border-width:1px ; border-color:#D50000' onclick='gfHiddenImage(this.id)'><img src='" + url + "' /></div>").appendTo("body");
	$("#divTmpViewImage").show("slow");
}

function gfHiddenImage(id) {
	$("#" + id).remove();
}

function gfIsValidJumin(el) {
	var pattern = /^([0-9]{6})-?([0-9]{7})$/; 
	var num = el;
	if (!pattern.test(num)) return false; 
	num = RegExp.$1 + RegExp.$2;

	var sum = 0;
	var last = num.charCodeAt(12) - 0x30;
	var bases = "234567892345";
	for (var i=0; i<12; i++) {
		if (isNaN(num.substring(i,i+1))) return false;
		sum += (num.charCodeAt(i) - 0x30) * (bases.charCodeAt(i) - 0x30);
	}
	var mod = sum % 11;
	return ((11 - mod) % 10 == last) ? true : false;
}


// 가운데에다가 메시지 띄우기
function gfShowMessage(msg) {
	var sw = $(document.body).width();
	var sh = $(document.body).height();
	
	var w = 500;
	var h = 300;
	var l = sw / 2 - w / 2;
	var t = sh / 2 - h / 2;
	var inBox = "<table width=500 cellspacing=0 cellpadding=0 border=0 align=center><tr><td height=10><img src='/common/images/msg.p.top.jpg'></td></tr>" + 
						"<tr><td width=480 height=300 align=center style=\"background-image:url('/common/images/msg.p.bg.jpg') ; padding:45 0 45 0\"><img src='/common/emoticon/icon4_06.png' align=absmiddle><font color=#FFFFFF> " +msg + "</font></td></tr>" +
						"<tr><td height=10><img src='/common/images/msg.p.bottom.jpg'></td></tr></table>";
	var box = "<div id=divMsgBox style='font-size:16px ; position:absolute ; left:" + l + " ; top:" + t + " ; width:" + w + "; height:" + h + "; z-index:999 ; cursor:pointer ; ' onclick='gfHiddenImage(this.id)'>" + inBox + "</div>";
	
	$(box).appendTo("body");
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

// 사용자 메뉴
function gfVIewUserMenu(e, userid) {
	var x = 0;
	var y = 0;
	if(e == null) {
		x = document.body.scrollLeft + parseInt(window.event.x, 10) - 20;
		y = document.body.scrollTop + parseInt(window.event.y, 10) - 10;
		
	} else {
		x = document.body.scrollLeft + parseInt(e.clientX, 10) - 20;
		y = document.body.scrollTop + parseInt(e.clientY, 10) - 10;
	};

	gfRemoveUserMenu();
	var mn= "<div style='text-align:right'><a href=\"javascript:void gfRemoveUserMenu()\"><img src='/common/images/del.gif' border=0></a></div>" +
				"<div style='padding-bottom:5px'><a href=\"javascript:void gfSendLetter('" + userid + "')\"><font color='#303030'>쪽지보내기</font></a></div>" +
				"<div style='padding-bottom:5px'><a href=\"javascript:void gfViewUser('" + userid + "')\"><font color='#303030'>회원정보 보기</font></a></div>" +
				"<div><a href=\"javascript:void lfIDSearch('"+ userid + "')\"><font color='#303030'>아이디로 검색</font></a></div>";

	$("<div class=userMenu style='left:" + x + "px ; top:" + y + "px'>" + mn + "</div>").appendTo("body");
}

function gfRemoveUserMenu() {
	$("div.userMenu").remove();
}

 
