﻿/*******************************************************
StringBuilder 함수
********************************************************/
var StringBuilder = function()
{ 
    this.buffer = new Array();  
}

//순서대로 문자열을 추가한다.
StringBuilder.prototype.Append = function(strValue) 
{
    this.buffer[this.buffer.length] = strValue;
    // this.buffer.push( strValue ); //IE5.5 NS4
} 

// 문자열의 형식을 지정해서 추가한다. 
StringBuilder.prototype.AppendFormat = function()
{ 
    var count = arguments.length;
    if( count < 2 ) return ""; 
    var strValue = arguments[0];
    for(var i=1; i<count; i++) 
          strValue = strValue.replace("{"+ (i-1) + "}", arguments[i] );
    this.buffer[this.buffer.length] = strValue;
} 


// 해당하는 위치에 문자열을 추가한다. (문자위치가 아님);
StringBuilder.prototype.Insert = function( idx, strValue ) { 
    this.buffer.splice( idx, 0, strValue );     //IE5.5 NS4 
}


// 해당문자열을 새로운 문자열로 바꾼다. 
// (배열방 단위로 바꾸므로 배열방 사이에 낀 문자열은 바꾸지 않음)
StringBuilder.prototype.Replace = function( from, to ) { 
    for( var i=this.buffer.length-1; i>=0; i--)
        this.buffer[i] = this.buffer[i].replace(new RegExp(from, "g"), to); //IE4  NS3 
}


// 문자열로 반환한다.
StringBuilder.prototype.ToString = function() { 
        return this.buffer.join("");    //IE4 NS3
} 

/*******************************************************
checkData 함수 : 컨트롤의 Value값을 조건에 맞게 체크한다.
인수1. FormName : 페이지 폼태그 ID
    2. ObjName : 개체ID
    3. DataType :
    4. IsEssential :
    5. MaxLen : 최대 허용 길이
    6. msg : 메세지
********************************************************/
function checkData(FormName,ObjName,DataType,IsEssential,MaxLen,msg)
{
   	var obj;
   	
   	if(FormName)
   	{
   		obj=document.forms[FormName].elements[ObjName];
   	}
   	else
   	{
   		obj=eval("document.all."+ObjName);
   	}

   	if(!obj)
   	{
   		alert(CommUtilCommon_msg01);
   		return false;
   	}
   	  
   	var sVal="";
   	if(obj.length == null)
   	{
   		sVal=obj.value;		
	}
	else
	{
		for(var i=0;i<obj.length;i++)
		{
			if(obj[i].checked || obj[i].selected)
			{
				sVal=obj[i].value;
				break;
			}
		}
	}

	if(sVal.indexOf("|") > -1) { sVal=sVal.substring(0, sVal.indexOf("|")); }	
   	
   	DataType=DataType.toUpperCase();
   	IsEssential=IsEssential.toUpperCase();   	
   	
   	if(IsEssential=="Y")
   	{
   		if(!checkEssential(sVal,msg))
   		{
   			setFocus(obj);
   			return false;
   		}
   	}
   	
   	if(DataType=="S")
   	{
   		if(!checkMaxLen(sVal,MaxLen,msg))
   		{
   			setFocus(obj);
   			return false;
   		}   		
   	}
   	
   	if(DataType=="N")
   	{
   		if(!checkNumeric(sVal,msg))
   		{
   			setFocus(obj);
   			return false;
   		}   		
   	}
   	
   	return true;
}


/*******************************************************
checkEssential 함수 : 값입력여부 체크(입력값있으면 true,없으면 false)
인수1. str : 페이지 폼태그 ID
    2. msg : 메세지
********************************************************/
function checkEssential(str,msg)
{
	if(!str)
	{
		alert(CommUtilCommon_msg02.replace("[$1]", msg));
		return false;
	}
	else
	{
		return true;	
	}
}

/*******************************************************
checkNumeric 함수 : 숫자여부 체크(숫자이면 true,아니면 false)
인수1. str : 페이지 폼태그 ID
    2. msg : 메세지
********************************************************/
function checkNumeric(str,msg)
{
    var CommUtilCommon_msg03 = "[$1]에는 숫자만 입력할 수 있습니다";
    
	if(isNaN(str))
	{
		alert(CommUtilCommon_msg03.replace("[$1]", msg));
		return false;
	}
	else
	{
		return true;	
	}
}


/*******************************************************
checkMaxLen 함수 : 최대길이 체크(입력값이 최대길이를 초과하면 false)
인수1. str : 페이지 폼태그 ID
    2. MaxLen : 최대길이
    3. msg : 메세지
********************************************************/
function checkMaxLen(str,MaxLen,msg)
{
	if(parseInt(getLength(str)) > parseInt(MaxLen))
	{
//	    alert("[[$1]] 한글은 [$2]자, 영문.숫자.공백은 [$3]자를 초과할수 없습니다.".replace("[$1]", msg).replace("[$2]", (MaxLen/2)).replace("[$3]", MaxLen));
		alert(CommunityCommFunc_msg01.replace("[$1]", msg).replace("[$2]", (MaxLen/2)).replace("[$3]", MaxLen));
		return false;
	}
	else
	{
		return true;	
	}
}

/*******************************************************
setFocus 함수 : 컨트롤에 포커스주기
인수1. obj : 개체
********************************************************/
function setFocus(obj)
{
	if(!obj){return;}
	if(obj.disabled==true){return;}
	if(obj.type=="hidden"){return;}

	if(obj.length!=null)
		obj[0].focus();
	else
		obj.focus();
}


/*******************************************************
getLength 함수 : 문자열길이 구하기(한글은 2자리로 계산)
인수1. str : 문자
********************************************************/
function getLength(str)
{
	if(str==""){return 0;}
	
	var len=0;	
	
   	for(var i=0;i<str.length;i++)
   	{
     	var chr=str.charCodeAt(i);
     	
		if(chr>0 && chr<255)
		{
			len++;
		}
		else
		{
			len += 2;
		}
   }
   
   return len;
}

/*******************************************************
openWindow 함수 : 작성창을 팝업
인수 1 fileName : 주소
     2 windowName :윈도우이름
     3 theWidth : 창 넓이
     4 theHeight : 창 높이 
     5 etcParam : Pararam

********************************************************/
function openWindow(fileName,windowName,theWidth,theHeight, etcParam)
{ 
    var objNewWin; var x = theWidth;
    var y = theHeight;
    var sy = window.screen.height / 2 - y / 2 - 70;
	
    if (etcParam == 'fix') { 
        etcParam = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0";
        var sy = window.screen.height / 2 - y / 2 - 40; 
    } else if (etcParam == 'resize') { 
        etcParam = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1"; 
        var sy = window.screen.height / 2 - y / 2 - 40; 
    } else if (etcParam == 'scroll') {
        etcParam = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1";
    }
       else if (etcParam == 'scrolls') {
        etcParam = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0";
    } 

    var sx = window.screen.width / 2 - x / 2; 
    if (sy < 0 ) { sy = 10; } 
    var sz = ",top=" + sy + ",left=" + sx; 
    if (windowName == "newMessageWindow") { 
        windowName = new String(Math.round(Math.random() * 100000)); 
    } 
    
    objNewWin = window.open(fileName,windowName, etcParam + ",width=" + x + ",height=" + y + sz); 	
}



/*******************************************************
dateFormat 함수 : 
********************************************************/
/*** dateFormat
	Accepts a date, a mask, or a date and a mask.
	Returns a formatted version of the given date.
	The date defaults to the current date/time.
	The mask defaults ``"ddd mmm d yyyy HH:MM:ss"``.
*/
var dateFormat = function () {
	var	token        = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloZ]|"[^"]*"|'[^']*'/g,
		timezone     = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (value, length) {
			value = String(value);
			length = parseInt(length) || 2;
			while (value.length < length)
				value = "0" + value;
			return value;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask) {
		// Treat the first argument as a mask if it doesn't contain any numbers
		if (
			arguments.length == 1 &&
			(typeof date == "string" || date instanceof String) &&
			!/\d/.test(date)
		) {
			mask = date;
			date = undefined;
		}

		date = date ? new Date(date) : new Date();
		if (isNaN(date))
			throw "invalid date";

		var dF = dateFormat;
		mask   = String(dF.masks[mask] || mask || dF.masks["default"]);

		var	d = date.getDate(),
			D = date.getDay(),
			m = date.getMonth(),
			y = date.getFullYear(),
			H = date.getHours(),
			M = date.getMinutes(),
			s = date.getSeconds(),
			L = date.getMilliseconds(),
			o = date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
			};

		return mask.replace(token, function ($0) {
			return ($0 in flags) ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":       "ddd mmm d yyyy HH:MM:ss",
	shortDate:       "m/d/yy",
	mediumDate:      "mmm d, yyyy",
	longDate:        "mmmm d, yyyy",
	fullDate:        "dddd, mmmm d, yyyy",
	shortTime:       "h:MM TT",
	mediumTime:      "h:MM:ss TT",
	longTime:        "h:MM:ss TT Z",
	isoDate:         "yyyy-mm-dd",
	isoTime:         "HH:MM:ss",
	isoDateTime:     "yyyy-mm-dd'T'HH:MM:ss",
	isoFullDateTime: "yyyy-mm-dd'T'HH:MM:ss.lo"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask) {
	return dateFormat(this, mask);
}
	
/*------------------------------------------------------------------------------------------------------------------------------------------/

    /*******************************************************
    작성목적 :  NonBlank() 에서 사용하는 함수
    Parameter :
                       control  (control : 체크할 Control)
                       displayText  (displayText  : 출력할 컨트롤 Text)   
                       checkingFlag (bool : 체크 옵션, true - 필수, false - 선택)
    반환 값  :  bool (true or false)
    *******************************************************/
    function NonBlank(control, displayText, checkingFlag) 
	{
	    control.value= control.value.trim();
	    var controlValue = control.value;	
       
	    try
	    {
		    if (checkingFlag)
			    if (!IsNonBlank(controlValue, displayText))	
				    if (control.disabled == false) 
				    {
					    if (control.type != "hidden")
					        control.focus();
    					    
					    return false;	
				    }
    				
		    return true;
	    }
	    catch (exception)
	    {
		    alert(exception.description);	
		    return false;
	    }
    }
    
    /*******************************************************
    작성목적 :  trim() 는 함수
    Parameter :
    반환 값  :  공백을 뺀 값
    *******************************************************/    
    String.prototype.trim = _private_trim;

    function _private_stringvb_isSpace(inChar)
    {
      return (inChar == ' ' || inChar == '\t' || inChar == '\n');
    }

    function _private_trim()
    {
      var tmpStr, atChar;
      tmpStr = this;
      if (tmpStr.length > 0) atChar = tmpStr.charAt(0);
      while (_private_stringvb_isSpace(atChar))
      {
        tmpStr = tmpStr.substring(1, tmpStr.length);
        atChar = tmpStr.charAt(0);
      }
      if (tmpStr.length > 0) atChar = tmpStr.charAt(tmpStr.length-1);
      while (_private_stringvb_isSpace(atChar))
      {
        tmpStr = tmpStr.substring(0,( tmpStr.length-1));
        atChar = tmpStr.charAt(tmpStr.length-1);
      }
      
      return tmpStr;
    }    
    
    /*******************************************************
    작성목적  :  NonBlank() 에서 사용하는 공통 함수
    Parameter   :
                         objectValue  (object : 체크할 Control의 value)
                         displayText  (displayText  : 출력할 컨트롤 Text)   
    반환 값   :  bool (true or false)
    *******************************************************/
    function IsNonBlank(objectValue, displayText)
    {
        var NON_BLANK_INFO_MESSAGE = " 을(를) 입력하시기 바랍니다."; 
        var strInfoMessage = displayText + NON_BLANK_INFO_MESSAGE ;
        
	    try
	    {
		    if (CheckValueEqualLength(objectValue, 0))	
		    {
			    alert(strInfoMessage );		
			    return false;
		    }
    		
		    return true;
	    }
	    catch (exception)
	    {
		    return false;
	    }
    }
    
    /*******************************************************
    작성목적  :  검사할 object 값의 길이(length)가 comparedLength와 같은지 체크한 후 리턴하는 함수
    Parameter   :
                         objectValue         (object  : 체크할 string Value)
                         comparedLength  (number  : 검사할 문자 길이)
    반환 값   :  bool (true or false)
    *******************************************************/
    function CheckValueEqualLength(objectValue, comparedLength)
    {
	    try
	    {
		    if (objectValue == null)
			    return false;
		    if (objectValue.length == comparedLength)     
			    return true;
		    else
			    return false;
	    }
	    catch (exception)
	    {
		    return false;
	    }
    }  			
    
    /*******************************************************
    작성목적  :  alert 띄운후 리스트 페이지로 이동
    Parameter :  
    반환 값   :  
    *******************************************************/      
    function AlertGoList(message, list)
    {   
        alert(message);
        window.opener.location.href= list;
        self.close();
    } 
    
    /*******************************************************
    작성목적  :  자식창 닫고 리스트 페이지로 이동
    Parameter :  
    반환 값   :  
    *******************************************************/      
    function GoList(list)
    {   
        window.opener.location.href= list;
        self.close();
    }  
    
    /*******************************************************
    작성목적  :  [삭제]버튼 클릭시 유효성검사
    Parameter :  
    반환 값   :  
    *******************************************************/           
    function uChkDel()
    {
	    try
	    {
		    if(confirm("삭제하시겠습니까?"))
		    {	
		        return true;
		    }
		    else
		    {
                return false;
		    }
	    }
	    catch(exception)
	    {
		    alert(exception.desription);
	    }
    }
    
    /*******************************************************
    작성목적  :  개발자가 입력한 URL로 이동하는 함수
    Parameter   : url (string : 이동하기 위한 URL)
    반환 값   : 
    *******************************************************/
    function MovePage(url)
    {
	    self.location.href = url;
	    return false;
    }         
   
       //숫자체크 함수
    function CheckNumberTextBox()
    {
        try
       { 
	        // 허용키 : 8, 13, 27, 48 ~ 57
	        if ( window.event.keyCode >= 48 && window.event.keyCode <= 57 )
	        {
		        window.event.returnValue = true;
		        return;
	        }
	        if ( window.event.keyCode == 8 && window.event.keyCode == 13 && window.event.keyCode == 27 )
	        {
		        window.event.returnValue = true;
		        return;
	        }
	        window.event.returnValue = false;
	    }
	    catch(exception)
	    {
		    alert(exception.description);
	    }
    }     