/**
 * 빈값 입력
 */
function emptyValue(obj) {
	
	obj.value = "";
	
}

/**
 * 공백 입력 체크
 */
function isEmptyValue(obj) {
	
	var returnValue = false;
	if (obj.value.replace(/^\s*|\s*$/g, "") == "") {
		returnValue = true;
	}
	
	return returnValue;
	
}

/**
 * 공백 입력 체크
 */
function isEmptyCheck( obj, objName) {
	
	var returnValue = isEmptyValue(obj);
	if( returnValue ){
		alert( "Enter " +objName);
		obj.focus();	
	}
	return returnValue;
	
}


/**
 * 정규식 체크
 */
function isRegexCheck(obj, regex) {
	
	var returnValue = false;
	
	returnValue = regex.test(obj.value);
	
	return returnValue;
	 
}

/**
 * 정규식 체크
 */
function isValidCheck( obj, regexName, msg) {

	var regex = "";
	var eMsg = "";
	
	if( regexName == "ID" ) {
		regex = /^[a-z0-9]{6,12}$/;
		eMsg = "아이디는 영문 소문자, 숫자 6~12 자리입니다.";
	} else if( regexName == "PWD" ) {		
		regex = /^[a-z0-9]{6,12}$/;
		eMsg = "비밀번호는 영문, 숫자 6~12 자리입니다.";
	} else if( regexName == "EMAIL" )	{
		regex = /^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/i;
		eMsg = "이메일 형식이 올바르지 않습니다.";

	} else if( regexName == "EMAIL1" )	{
		regex = /^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*$/;
		eMsg = "이메일 형식이 올바르지 않습니다.";
	} else if( regexName == "EMAIL2" )	 {
		regex = /^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/i;
		eMsg = "이메일 형식이 올바르지 않습니다.";

	} else {
		regex = regexName; 
		eMsg = msg;
	}
	

	var returnValue = isRegexCheck(obj, regex);
	if( returnValue == false){
		alert( eMsg );
		obj.focus();	
	}
	return returnValue;
	
}

/**
 * 체크박스, 라디오박스 선택갯수 체크
 */
function countChecked(obj) {
	
	var returnValue = 0;
	
	var checkedNum = 0;
	
	for (var i = 0; i < obj.length; i++) {
		if (obj[i].checked == true) {
			checkedNum++;
		}
	}
	
	returnValue = checkedNum;
	
	return returnValue;
	
}

/**
 * 엔터키 입력 체크
 */
function isEnterKey(obj) {
	
	var returnValue = false;
	
	if (obj.keyCode == 13) {
		returnValue = true;
	}
	
	return returnValue;
	
}

/**
 * 날짜 입력 범위 체크
 */
function checkDate(startDate, endDate) {
	
	var returnValue = false;
	
	replaceStartDate = startDate.replace(/[.]/g, "").replace(/[-]/g, "").replace(/[/]/g, "");
	replaceEndDateDate = endDate.replace(/[.]/g, "").replace(/[-]/g, "").replace(/[/]/g, "");
	
	if (parseInt(replaceStartDate) > parseInt(replaceEndDateDate)) {
		returnValue = true;
	}
	
	return returnValue;
	
}

/**
 * 이메일 주소 체크
 */
function checkEmail(email) {
	
	var returnValue = false;
	
    var reg = /^((\w|[\-\.])+)@((\w|[\-\.][^(\.)\1])+)\.([A-Za-z]+)$/;
	
	if (reg.test(email)) {
		returnValue = true;
	}
	
	return returnValue;
	
}

/**
 * 팝업창 열기
 */
function openWindow(sURL, sTarget, widthSize, heightSize, resizeableValue, scrollbarsValue) {
	
	var returnValue;
	
	var windowWidth = (screen.width - widthSize) / 4;
	var windowHeight = (screen.height - heightSize) / 1.5;
	
	var sStatus = "width=" + widthSize;
	sStatus = sStatus + "," + "height=" + heightSize;
	sStatus = sStatus + ","  + "top=" + windowWidth;
	sStatus = sStatus + ","  + "left=" + windowHeight;
	sStatus = sStatus + ","  + "resizable=" + resizeableValue;
	sStatus = sStatus + ","  + "scrollbars=" + scrollbarsValue;
	
	returnValue = window.open(sURL, sTarget, sStatus);
	
	return returnValue;
	
}


/**
 * 입력내용 바이트계산
 */
function getByteLength(obj) {

	var returnValue = 0;
	
	var stringValue = obj.value;
	
	var defaultByte = 1;
	var unicodeByte = 3;
	
	for (var i = 0; i < stringValue.length; i++) {
		var characterValue = escape(stringValue.charAt(i));
		    
		if (characterValue.length == 1) {
			returnValue ++;
		} else if (characterValue.indexOf("%u") != -1) {
			returnValue += unicodeByte;
		} else if (characterValue.indexOf("%") != -1) {
			returnValue += characterValue.length / 3;
		}
	}
	
	return returnValue;
	
}


/**
 * 입력 가능 바이트수 체크
 */
function maxByteCheck( obj, maxByte, objName ) {

	if( getByteLength( obj ) >  maxByte ) {
		alert( "입력가능 글자수 초과하였습니다 \n\n" + objName + "는(은) 공백포함 한글은 " + Math.floor(maxByte/3) + "자, 영문은 " + maxByte + "자 까지 입력가능합니다"  );
		return false;
	}
	return true;
}


	
/**
 * 최대 바이트이하 내용작성
 */
var oldStringValue = "";

function truncateMaxByte(obj, maxByte) {
	
	if (getByteLength(obj) > maxByte) {
		alert("입력범위를 초과하였습니다!");
		obj.value = oldStringValue;
		// return;
	} else {
		oldStringValue = obj.value;
	}
	
}


/**
 * paramsStr에 있는 변수 값들을 POST 방식으로 특정 URL로 전송하고 싶을 때. paramStr형식 :
 * 변수이름=변수값|변수이름=변수값|변수이름=변수값
 */
function sendRedirectPOST( action, paramsStr )
{
	var f = document.createElement("form");

	f.method = "post";
	f.action = action;
	var paramArr = paramsStr.split("|");
	for ( var i = 0; i < paramArr.length; i++ ) {
		var paramName = paramArr[i].split("=")[0];
		var paramVal = paramArr[i].split("=")[1];
		var inputHidden = document.createElement("input");
		inputHidden.type = "hidden";
		inputHidden.name = paramName;
		inputHidden.value = paramVal;
		f.appendChild(inputHidden);
	}
	document.body.appendChild(f);

	f.submit();
}

/**
 * URI 인코딩
 */
function encodingURI(uri, charset) {
	
	var returnValue = "";
	
	returnValue = encodeURI(uri, charset);
	
	return returnValue;
}


function copy(URL) {        
	if (window.clipboardData) 
	{ 

	// the IE-manier
	window.clipboardData.setData("Text", URL); 

	// waarschijnlijk niet de beste manier om Moz/NS te detecteren;
	// het is mij echter onbekend vanaf welke versie dit precies werkt:
	} 
	else if (window.netscape) 
	{ 

	// dit is belangrijk maar staat nergens duidelijk vermeld:
	// you have to sign the code to enable this, or see notes below
	netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); 

	// maak een interface naar het clipboard
	var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard); 
	if (!clip) return; 

	// maak een transferable
	var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable); 
	if (!trans) return; 

	// specificeer wat voor soort data we op willen halen; text in dit geval
	trans.addDataFlavor('text/unicode'); 

	// om de data uit de transferable te halen hebben we 2 nieuwe objecten nodig
	// om het in op te slaan
	var str = new Object(); 
	var len = new Object(); 

	var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString); 

	var copytext=URL; 

	str.data=copytext; 

	trans.setTransferData("text/unicode",str,copytext.length*2); 

	var clipid=Components.interfaces.nsIClipboard; 

	if (!clip) return false; 

	clip.setData(trans,null,clipid.kGlobalClipboard); 

	} 
	alert("해당 RSS주소가 복사되었습니다.");
	return false; 
} 


/**
 * SNS 로 글 보내기
 */
var sendUrl,locUrl;
locUrl = window.location.href;

function openNewsWin(openUrl) {
	var winObj;
	winObj = window.open(openUrl,"twitter","width=1024, height=800");
}

function openNewsWin2(openUrl) {
	var winObj;
	winObj = window.open(openUrl,"facebook","width=600, height=420, scrollbars=no, resizable=no");
}

function sendNews( media, title ) {
	switch(media) {
		case "twitter":
			sendUrl = "http://twitter.com/home?status="+ encodeURIComponent(title) + " " + encodeURIComponent(locUrl);
			openNewsWin(sendUrl);
			break;
		case "facebook":
			sendUrl = "http://www.facebook.com/sharer.php?u="+ encodeURIComponent(locUrl)+"&t=" +  encodeURIComponent(title) ;
			openNewsWin2(sendUrl);
			break;
	}
}


/**
 * 메일 보내기 팝업 띄우기
 */
function goSendMailPopup( refUrl, params ){
	var url = "/common/sendMail.jsp?refUrl=" + refUrl + "&params=" + params;
	var winObj;
	winObj = window.open( url, "sendMail", "width=600, height=700, scrollbars=no, resizable=no");
}


/**
 * 사업자 등록번호 체크하기
 */
function check_companynum( bizNo ){
 
	var checkID = new Array(1, 3, 7, 1, 3, 7, 1, 3, 5, 1);
	var bizID = bizNo;
	var i, Sum=0, c2, remander;
 
	for (i=0; i<=7; i++) Sum += checkID[i] * bizID.charAt(i);

	c2 = "0" + (checkID[8] * bizID.charAt(8));
	c2 = c2.substring(c2.length - 2, c2.length);

	Sum += Math.floor(c2.charAt(0)) + Math.floor(c2.charAt(1));

	remander = (10 - (Sum % 10)) % 10 ;
 
	if (Math.floor(bizID.charAt(9)) != remander)
	{
		alert ("정확한 사업자 등록번호를 입력하세요");
		return false;
	}else{
		return true;
	}
}


/**
 * 왼쪽 공백 채우기
 */
function lpad(str,n,ch) {
	str = String(str);
	var result = "";
	var len = str.length;
	if ( len < n ) {
		for ( var i=0; i<(n-len); i++ ) {
		result += ch;
		}
		result += str;
	}
	else {
	result = str;
	}
	return result;
}


/**
 * 왼쪽 공백 채우기
 */
function lpad(str,n,ch) {
	str = String(str);
	var result = "";
	var len = str.length;
	if ( len < n ) {
		for ( var i=0; i<(n-len); i++ ) {
		result += ch;
		}
		result += str;
	}
	else {
	result = str;
	}
	return result;
}


/**
 * 팝업창 크기 자동조정
 */
function winResize(){
    var Dwidth = parseInt(document.body.scrollWidth);
    var Dheight = parseInt(document.body.scrollHeight);
    var divEl = document.createElement("div");
    divEl.style.position = "absolute";
    divEl.style.left = "0px";
    divEl.style.top = "0px";
    divEl.style.width = "100%";
    divEl.style.height = "100%";
    
    document.body.appendChild(divEl);
    
    window.resizeBy(Dwidth-divEl.offsetWidth, Dheight-divEl.offsetHeight);
    document.body.removeChild(divEl);
}

/**
 * Replace All
 */
function replaceAll(str, searchStr, replaceStr){
	
	 while(str.indexOf(searchStr) != -1){
		 str = str.replace(searchStr, replaceStr);
	 }
	 
	 return str;
}

/**
 * 좌우 공백 제거
 * 
 * @param s
 * @return
 */
function trim(s){
	s += '';
	return s.replace(/^\s*|\s*$/g,'');
}

/**
 * Text형식 체크
 * - TAG의 title속성으로 Alert처리
 * - TAG의 checkYn(임의속성)이 Y일때 체크
 * @param formName
 * @returns
 */
function validationText(formName){
	
	var flag = true;
	var title = "";
	var value = "";
	var checkYn = "";
	var reg = "";
	
	$("#"+formName).each(function(){

		// Text 형식 검증
		$(this).find(":text,:input[type=textarea]").each(function(){
			
			checkYn = $(this).attr("checkYn");
			valiType = $(this).attr("valiType");
			title = $(this).attr("title");
			maxlength = $(this).attr("maxlength");
			value = $(this).val().replace(/^\s*|\s*$/g, "");
			
			if(checkYn)
			{
				// 공백 체크
				if(value == ""){
					alert("Enter "+title);
					$(this).focus();
					flag = false;
				}
				
				// 숫자 체크
				if( valiType == 'num' && !isRegexCheck(this,/^\d*$/) ){
					alert("The "+title+" you entered is incorrect");
					$(this).focus();
					flag = false;
				}
				
				// 이메일 체크
				if( flag && valiType == 'mail')
				{
					reg = /^((\w|[\-\.])+)@((\w|[\-\.][^(\.)\1])+)\.([A-Za-z]+)$/;
					if(!reg.test(value)){
						alert("The "+title+" you entered is incorrect");
						$(this).focus();
						flag = false;
					}
				}
				
				/* 추후에 작업...
				 * 
				//전화번호 체크
				if(title.indexOf("전화번호") < 0)
				{
					reg = /^((\w|[\-\.])+)@((\w|[\-\.][^(\.)\1])+)\.([A-Za-z]+)$/;
					if(!reg.test(value)){
						alert(title+" 형식이 맞지 않습니다.");
						$(this).focus();
						flag = false;
					}
				}
				*/
			}
			
			// 스크립트 체크
			if(flag)
			{
				if(
					value.toLowerCase().indexOf('<script') >= 0 ||
					value.toLowerCase().indexOf('script>') >= 0 ||
					value.toLowerCase().indexOf('<body') >= 0 ||
					value.toLowerCase().indexOf('/body') >= 0 
				){
					alert('you entered is incorrect');
					$(this).focus();
					flag = false;
				}
				
			}
			
			if(!flag) return false;
			
		});		
	});
	
	return flag;
}

//******************************************
//미리보기 이미지 팝업창 팝업
//******************************************
function popImg(img){
	imgControll(img);
}

//******************************************
//미리보기 이미지 팝업창 팝업 - 스틸이미지일경우 /s_를 치환한다.
//******************************************
function popImg1(img){
	img = img.replace("/s_","/");
	imgControll(img);   
}

function imgControll(img){
	var imgObj = new Image();
	imgObj.src=(img);
	
	if((imgObj.width!=0)&&(imgObj.height!=0)){
		viewImage(img);
	}else{
		controller="imgControll('"+img+"')";
		intervalID=setTimeout(controller,20);
	}
}  

function viewImage(img){
	var imgObj = new Image();
	imgObj.src=(img);
	var imgW = 0;
	var imgH = 0;
	imgW = imgObj.width;
	imgH = imgObj.height;
	
  var Opt = "width=" + imgW + ", height=" + imgH;
  imgW = imgObj.width + 20;
	imgH = imgObj.height;
	
	Opt = "width=" + imgW + ", height=" + imgH + ",scrollbars=yes";
	
  var imgWin = window.open("", "", Opt);   
  imgWin.document.write("<html><head><title>이미지 미리보기</title></head>");  
  imgWin.document.write("<body topmargin=0 leftmargin=0 align = 'center'>");
  imgWin.document.write("<img src="+img+" onclick='self.close()' style='cursor:hand;' align = 'center'>");
  imgWin.document.write("</body>");
  imgWin.document.close();  

}

function openPopup(url, width, height){
	var winObj;
	winObj = window.open( url, "sendMail", "width="+width+", height="+height+", scrollbars=no, resizable=no");
}

