//===================================================================================
//  함 수 명 : valueNumSize()
//  작 성 자 : 김종윤
//  기    능 : frm에 입력된 값을 num과 비교하여 수치 그 이상이 되는지, 혹은 숫자인지를 검수
//  페러미터 : frm -> 폼 객체
//             num -> 숫자
//===================================================================================
function valueNumSize(frm, num)
{
	if ( !frm.value )
	{
		alert("내용을 입력하여 주십시오");
		frm.focus();
		return true;
	}

	if ( num )
	{
		if ( parseInt(frm.value) <= num )
		{
			alert(num +"이상의 수를 입력하여 주십시오");
			frm.focus();
			return true;
		}
	}

	if ( isNaN(frm.value) )
	{
		alert("숫자만 입력 가능합니다");
		frm.value = "";
		frm.focus();
		return true;
	}
}

//===================================================================================
//  함 수 명 : checkValue()
//  작 성 자 : 김종윤
//  기    능 : 입력 폼 무결성 검수
//  페러미터 : frm -> 폼 객체
//             msg -> alert메시지
//===================================================================================
function checkValue(frm, msg, chk)
{
	if (typeof(frm) == "object")
	{
		switch (frm.type)
		{
			case "select-one"	: msg = msg + " 선택하여 주십시오."; break;
			case "hidden"		: msg = msg + "하여 주십시오."; break;
			case "file"			: msg = msg + " 선택하여 주십시오."; break;
			default				: msg = msg + " 입력하여 주십시오."; break;
		}

		if (!strim(frm.value))
		{
			alert(msg);
			if (frm.type != "hidden")	frm.focus();

			return true;
		}

		if (chk)
		{
			return Word_Chk(chk, frm);
		}
	}
	else
	{
		return false;
	}
}

//=========================================================================
//  함수 명     : Word_Chk()
//  함수 설명   : flag값에 의해 str값의 유효성 검사
//  페러미터    : flag -> 구분값
//                str -> 문자열
//=========================================================================
function Word_Chk(flag, frm)
{
	switch (flag)
	{
		//영문만 유효성 검사
		case "eng" :
			Wordval = /^[a-z|A-Z]+$/
			msg = "영문만 입력 가능합니다";
			break;
		//영문,숫자 유효성 검사
		case "engnum" :
			Wordval = /^[(a-z|A-Z)0-9]+$/
			msg = "영문, 숫자만 입력 가능합니다";
			break;
		//아이디 영문,숫자,underbar(_) 사용 유효성 검사
		case "id" :
			Wordval = /^[(a-z|A-Z)0-9]+[_]*[(a-z|A-Z)0-9]+$/
			msg = "영문, 숫자, 언더바(_)만 사용 가능합니다";
			break;
		//정수 유효성 검사
		case "num" :
			Wordval = /^[0-9]+$/
			msg = "숫자만 입력 가능합니다";
			break;
		//영문,숫자 혼합사용 유효성 검사
		case "wordnum" :
			Wordval = /^([0-9]+[a-z|A-Z]+)|([a-z|A-Z]+[0-9]+)|([0-9]+[a-z|A-Z]+[0-9]+)|([a-z|A-Z]+[0-9]+[a-z|A-Z]+)$/
			msg = "영문, 숫자를 혼합하여 입력하여 주십시오";
			break;
		//이메일 유효성 검사
		case "email" :
			Wordval = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
			msg = "사용 할수 없는 이메일 주소입니다";
			break;
		//영문, 특수문자, 공백 검사
		case "etc" :
			Wordval = /^[ㄱ-ㅣ가-힣]+$/
			msg = "한글만 입력가능합니다";
			break;
		//이메일 유효성 검사(@ 앞)
		case "email1" :
			Wordval = /^\w+([-+.]\w+)*/
			msg = "사용 할수 없는 이메일 주소입니다";
			break;
		//이메일 유효성 검사(@ 뒤)
		case "email2" :
			Wordval = /\w+([-.]\w+)*\.\w+([-.]\w+)*$/
			msg = "사용 할수 없는 이메일 주소입니다";
			break;
		//한글, 영문 검사
		case "name" :
			Wordval = /^[(a-z|A-Z|ㄱ-ㅣ가-힣)]+$/
			msg = "한글과 영문만 입력 가능합니다";
			break;
	}

	if (!Wordval.test(frm.value.toString()))
	{
		alert(msg);
		frm.focus();
		return true;
	}
}

//===================================================================================
//  함 수 명 : DateDiffCheck()
//  작 성 자 : 김종윤
//  기    능 : 날짜 입력 폼 검수
//  페러미터 : svalue -> 시작 일
//             evalue -> 종료일
//             msg -> alert 메시지
//             frm -> 폼 객체
//===================================================================================
function DateDiffCheck(sv, ev, msg, frm)
{
	var sdate = sv.split("-");
	var edate = ev.split("-");

	var getDateS = new Date(sdate[0], sdate[1], sdate[2]);
	var getDateE = new Date(edate[0], edate[1], edate[2]);

	if ( getDateS > getDateE )
	{
		alert(msg + " 시작일이 종료일보다 늦을수 없습니다");
		frm.focus();
		return true;
	}
}

//공백 제거 함수
function strim(str)
{
	var index, len;

	while(true)
	{
		index = str.indexOf(" ");

		if(index == -1)		break;

		len = str.length;
		str = str.substring(0, index) + str.substring((index + 1), len);
	}

	return str;
}

//=========================================================================
//  함수 명     : SerialChk()
//  함수 설명   : 주민등록 번호 검수 함수
//  페러미터    : s1 -> 주민번호의 앞 6자리
//              : s2 -> 주민번호 뒤 7자리
//=========================================================================
function SerialChk (s1, s2)
{
	var jumin = s1 + s2;

	LastNum = jumin.substr(12,1);
	chk = "234567892345";
	total = 0;

	for (j = 0; j < 12; j++)
		total = total + jumin.substr(j, 1) * chk.substr(j, 1);

	tmp = total % 11;
	ChkNum = 11 - tmp;

	if (ChkNum == 10) { ChkNum = 0; }
	if (ChkNum == 11) { ChkNum = 1; }

	if (ChkNum != LastNum)	return false;
	else					return true;
}

//=========================================================================
//  함수 명     : ComSerialChk()
//  함수 설명   : 사업자 등록 번호 검수 함수
//  페러미터    : s1 -> 사업자 등록 번호 앞 3자리
//              : s2 -> 사업자 등록 번호 중간 2자리
//              : s3 -> 사업자 등록 번호 뒤 5자리
//=========================================================================
function ComSerialChk (s1, s2, s3)
{
	var cnum = s1 + s2 + s3;

	ChkNumber = cnum.substr(9, 1);
	chks = "13713713";
	total = 0;

	for (j = 0; j < 8; j++)
		total = total + (cnum.substr(j, 1) * chks.substr(j, 1));

	LastNums = cnum.substr(8, 1) * 5;
	LastNums = escape(LastNums);
	tmps = LastNums.length;

	if (tmps < 2)
		LastNums = LastNums.substr(0, 1);
	else
		LastNums = parseInt(LastNums.substr(0, 1)) + parseInt(LastNums.substr(1, 1));

	total = total + LastNums;
	total = escape(total);
	k = total.length - 1;
	total = 10 - total.substr(k, 1);

	if (ChkNumber != total)		return false;
	else						return true;
}

//=========================================================================
//  함수 명     : popup()
//  함수 설명   : 팝업 함수
//  페러미터    : geturl -> 팝업띄울 페이지의 url 경로
//                nm -> 팝업 명(window.name)
//                w -> 팝업의 width size
//                h -> 팝업의 height size
//                t -> 팝업의 Top 위치
//                l -> 팝업의 Left 위치
//                scrl -> 스크롤바의 표시 여부
//=========================================================================
function popup(geturl, nm, w, h, t, l, scrl)
{
	if (!t)	t = (screen.height - h) / 2;
	if (!l)	l = (screen.width - w) / 2;

	if (!scrl)	scrl = "no";

	var popwin = window.open(
		geturl,
		nm,
		"width=" + w + ",height=" + h + ",left=" + l + ",top=" + t + ",scrollbars=" + scrl +
		",toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no"
	);
	popwin.focus();
}

//=========================================================================
//  함수 명     : flashWrite()
//  함수 설명   : 팝업 함수
//  페러미터    : geturl -> 팝업띄울 페이지의 url 경로
//                nm -> 팝업 명(window.name)
//=========================================================================
function flashWrite(url, w, h, id, bg, vars, win)
{
	// 플래시 코드 정의
	var flashStr=
		"<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0' width='"+w+"' height='"+h+"' id='"+id+"' align='middle'>"+
		"<param name='allowScriptAccess' value='always' />"+
		"<param name='movie' value='"+url+"' />"+
		"<param name='FlashVars' value='"+vars+"' />"+
		"<param name='wmode' value='"+win+"' />"+
		"<param name='menu' value='false' />"+
		"<param name='quality' value='high' />"+
		"<param name='bgcolor' value='"+bg+"' />"+
		"<embed src='"+url+"' FlashVars='"+vars+"' wmode='"+win+"' menu='false' quality='high' bgcolor='"+bg+"' width='"+w+"' height='"+h+"' name='"+id+"' align='middle' allowScriptAccess='always' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' />"+
		"</object>";

	// 플래시 코드 출력
	document.write(flashStr);
}


//폼 글자수 표시 함수
function limitBytes(frm, maxs, tg)
{
	var bytesLength = 0;
	var validMsgLength = 0;
	var validBytesLength = 0;

	for (i = 0; i < frm.value.length; i++)
	{
		var oneChar = frm.value.charAt(i);

		if (escape(oneChar).length > 4)
			bytesLength += 2;
		else if (oneChar != '\r')
			bytesLength++;

		if (bytesLength <= maxs)
		{
			validMsgLength = i + 1;
			validBytesLength = bytesLength;
		}
	}

	if (bytesLength > maxs)
	{
		alert(maxs + "자 이상 저장 할 수 없습니다!");
		realValue = frm.value.substr(0, validMsgLength);
		frm.value = realValue;
		bytesVal = validBytesLength;

		return false;
	}
	else
		bytesVal = bytesLength;

	if (tg)
	{
		$(tg).text(bytesVal);
	}
	frm.focus();
}

//폼 글자수 표시 함수
function limit(frm, maxs, tg)
{
	var bytesLength = 0;
	var validMsgLength = 0;
	var validBytesLength = 0;

	for (i = 0; i < frm.value.length; i++)
	{
		var oneChar = frm.value.charAt(i);

		if (escape(oneChar).length > 4)
			bytesLength += 2;
		else if (oneChar != '\r')
			bytesLength++;

		if (bytesLength <= maxs)
		{
			validMsgLength = i + 1;
			validBytesLength = bytesLength;
		}
	}

	if (bytesLength > maxs)
	{
		alert(maxs + "자 이상 입력 할 수 없습니다!");
		realValue = frm.value.substr(0, validMsgLength);
		frm.value = realValue;
		bytesVal = validBytesLength;

		return false;
	}
	else
		bytesVal = bytesLength;

	if (tg)
	{
		$(tg).text(bytesVal);
	}
	frm.focus();
}

function countBytes(frm, maxs)
{
	var bytesLength = 0;
	var validMsgLength = 0;
	var validBytesLength = 0;

	for (i = 0; i < frm.txtaContent.value.length; i++)
	{
		var oneChar = frm.txtaContent.value.charAt(i);

		if (escape(oneChar).length > 4)
			bytesLength += 2;
		else if (oneChar != '\r')
			bytesLength++;

		if (bytesLength <= maxs)
		{
			validMsgLength = i + 1;
			validBytesLength = bytesLength;
		}
	}
	bytesVal = bytesLength;
	frm.count.value = bytesVal;
	frm.txtaContent.focus();
}

//=========================================================================
//  함수 명     : day_set()
//  함수 설명   : 선택 월(month)에 대한 일(day) 값을 뿌려줌
//  페러미터    : yr -> 년(year)값
//                mh -> 월(month)값
//                e -> 객체
//                sday -> selected되어야 되는 날짜 값
//=========================================================================
function day_set(yr, mh, e, sday)
{
	var Day = 24 * 60 * 60 * 1000;

	if (mh < 12)
		mh++;
	else
	{
		mh = 1;
		yr++;
	}

	switch (parseInt(mh))
	{
		case 1 : en_mh = "jan"; break;
		case 2 : en_mh = "feb"; break;
		case 3 : en_mh = "mar"; break;
		case 4 : en_mh = "apr"; break;
		case 5 : en_mh = "may"; break;
		case 6 : en_mh = "jun"; break;
		case 7 : en_mh = "jul"; break;
		case 8 : en_mh = "aug"; break;
		case 9 : en_mh = "sep"; break;
		case 10 : en_mh = "oct"; break;
		case 11 : en_mh = "nov"; break;
		case 12 : en_mh = "dec"; break;
	}

	var date = new Date(en_mh+" 1, "+yr);
	date.setTime(date.getTime() - Day);
	var cnt = e.length - 1;

	for (i = parseInt(cnt); i >= 0; i--)
	{
		e.options[i].value = null;
		e.options[i] = null;
	}

	for (i = 0; i < date.getDate(); i++)
	{
		var op = new Option(i+1, i+1);
		e.options[i] = op;

		if (sday && sday == (i + 1)) e[i].selected = true;
	}
}

//=========================================================================
//  함수 명     : set_comma()
//  함수 설명   : 값에 대한 천단위 , 를 찍어준다.
//  페러미터    : val = int형 값
//=========================================================================
function set_comma(val)
{
	str = ""+str+"";
	var retValue = "";

	for (i = 0; i < str.length; i++)
	{
		if (i > 0 && (i % 3) == 0)
			retValue = str.charAt(str.length - i -1) + "," + retValue;
		else
			retValue = str.charAt(str.length - i -1) + retValue;
	}
	return retValue;
}

//=========================================================================
//  함수 명     : number_format()
//  함수 설명   : 문자열(int형)에 천단위로 ,를 찍어 리턴
//  페러미터    : str -> 문자열(숫자)
//=========================================================================
function number_set_comma(num)
{
	num = num.replace(/,/g , "");
	num = num.replace(/ /g , "");

	var num_str = num.toString();
	var result = "";

	if (isNaN(num))
	{
		alert("숫자만 입력 가능합니다");
	}
	else
	{
		for(i = 0; i < num_str.length; i++)
		{
			var tmp = num_str.length - (i + 1);
			if (i % 3 == 0 && i != 0) result = ',' + result;
			result = num_str.charAt(tmp) + result;
		}
	}

	return result;
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


//=========================================================================
//  함수 명     : str_replace()
//  함수 설명   : str의 문자열 중 str_tg에 해당하는 모든 문자열은 str_ch로 변환
//  페러미터    : str, str_tg, str_ch 모두 문자열
//=========================================================================
function str_replace(str, str_tg, str_ch)
{
	for (i = 0; i < str.length; i++)
	{
		if (str.indexOf(str_tg) >= 0)
		{
			str = str.replace(str_tg, str_ch);
		}
	}

	return str;
}

//=========================================================================
//	로그인 페이지로 이동
//=========================================================================
function GoLoginPage(url)
{
	location.href = "/member/login.php?returnPage="+ url;
}

function setPng24(obj)
{
	obj.width=obj.height=1;
	obj.className=obj.className.replace(/\bpng24\b/i,'');
	obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+ obj.src +"',sizingMethod='image');"
	obj.src='';
	return '';
}

//=========================================================================
//	Share 관련 함수 Start
//=========================================================================


//Share시 로그
function ShareLog(flag, title, linkURL, num)
{
	$.ajax(
	{
		global: false,
		cache: false,
		url: "/common/share_log_proc.php",
		type: "POST",
		dataType: "json",
		data:
		{
			share_target: flag,
			ads_idx: num
		},
		success: function(json)
		{
			if (json.result == "success")
			{
				var wp = "";

				if (flag == "twitter")
				{
					wp = window.open("http://twitter.com/home?status=" + encodeURIComponent(title) + " " + encodeURIComponent(linkURL+json.share_idx), 'twitter', '');
				}
				else if (flag == "facebook")
				{
					wp = window.open("http://www.facebook.com/sharer.php?s=100&p[url]="+ encodeURIComponent(linkURL+json.share_idx) +"&p[summary]=ADMOBI,%20Inc.&p[title]="+ encodeURIComponent(title) +"&p[images][0]="+ encodeURIComponent(json.banner_img) , 'facebook', '');
				}
				else if (flag == "me2day")
				{
					//wp = window.open("http://me2day.net/posts/new?new_post[body]=" + encodeURIComponent(title) + " " + encodeURIComponent(linkURL+json.share_idx) + "&new_post[tags]=" + encodeURIComponent("ADmobi"), 'me2Day', '');
                    wp = window.open("http://me2day.net/plugins/post/new?new_post[body]=" + encodeURIComponent(title) + " " + encodeURIComponent(linkURL+json.share_idx) + "&new_post[tags]=" + encodeURIComponent("ADmobi"), 'me2Day', '');


				}
				else if (flag == "yozm")
				{
					wp = window.open("http://profile.daum.net/api/popup/Share.daum?service_name=yozm&prefix="+ encodeURIComponent(title) +"&link="+ encodeURIComponent(linkURL+json.share_idx) +"&meta_type=IMG&image_path="+ encodeURIComponent(json.banner_img), 'yozm', '');
				}
				else
				{
					popup("/inc/pop_send_mail.php?title="+ title +"&url="+ encodeURIComponent(linkURL+json.share_idx) +"&banner_img="+ encodeURIComponent(json.banner_img), "_mail", 388, 296, "", "", "no");
				}

				if (wp) wp.focus();
			}
			else if (json.result == "demo")
			{
				alert("데모 광고는 Share 할수 없습니다.");
			}
		}
	});
}
//=========================================================================
//	Share 관련 함수 End
//=========================================================================


jQuery(document).ready(function()
{
	//jQuery datepicker 기본 설정
	$.datepicker.regional['ko'] = {
		closeText: 'close',
		prevText: '이전달',
		nextText: '다음달',
		currentText: 'Today',
		monthNames: ['1월','2월','3월','4월','5월','6월', '7월','8월','9월','10월','11월','12월'],
		monthNamesShort: ['1월','2월','3월','4월','5월','6월', '7월','8월','9월','10월','11월','12월'],
		dayNames: ['일','월','화','수','목','금','토'],
		dayNamesShort: ['일','월','화','수','목','금','토'],
		dayNamesMin: ['일','월','화','수','목','금','토'],
		dateFormat: 'yy-mm-dd',
		firstDay: 0,
		isRTL: false,

		showOn: "button",
		buttonImage: "/images/comm/calendar.jpg",
		buttonImageOnly: true,
		buttonText: '달력',
		showAnim: "blind",
		duration: 100,
		changeMonth: true,
		changeYear: true,
		showButtonPanel: true
	};

	$.datepicker.setDefaults($.datepicker.regional['ko']);

	$("a").focus(function() { $(this).blur();} );
});


