var GLB_CALENDAR = new Object();
//var HIDDEN_OBJ = 

/**
 * @type   : function
 * @access : public
 * @desc   : <xmp>form내의 element들을 확인. <input type=image>는 지원하지 않음.</xmp>
 * @param  : form - 확인하고자 하는 form 객체.
 * @return : N/A
 * @author : 강성범
 */
function cfPrintForm(form) {
    var str = 'name : ';
    str += form.name;
    str += ' action : ';
    str += form.action;
    str += ' method : ';
    str += form.method;
    str += '\nTotal ';
    str += form.elements.length;
    str += ' Form Elements...\n';

    for(inx=0; inx < form.elements.length; inx++) {
        str += '[';
        str += form.elements.item(inx).type;
        str += ' : ';
        str += form.elements.item(inx).name;
        str += ' : ';
        str += form.elements.item(inx).value;
        str += '] ';
    }

    alert(str);
}

/**
 * @type   : function
 * @access : public
 * @desc   : 공통메세지에 정의된 메세지를 alert box로 보여준 후 리턴한다. cfGetMsg 참조.
 * @sig    : msgId[, paramArray]
 * @param  : msgId - required - common.js의 공통 메세지 영역에 선언된 메세지 ID
 * @param  : paramArray - optional - 메세지에서 '@' 문자와 치환될 데이터 Array. Array의 index와 메세지 내의 '@' 문자의 순서가 일치한다.
             치환될 데이터는 [] 사이에 콤마를 구분자로 하여 기술하면 Array 로 인식된다.
 * @return : 치환된 메세지 스트링
 * @author : 임재현
 */
function cfAlertMsg(msgId, paramArray) {
  if (cfIsNull(msgId)) {
    alert("There is no message id.");
    return null;
  }

  var msg = new coMessage().getMsg(msgId, paramArray);
  alert(msg);
  return msg;
}
/**
 * @type   : function
 * @access : public
 * @desc   : 공통메세지에 정의된 메세지를 confirm box로 보여준 후 리턴한다. cfGetMsg 참조.
 * @sig    : msgId[, paramArray]
 * @param  : msgId  -     required common.js의 공통 메세지 영역에 선언된 메세지 ID
 * @param  : paramArray - optional 메세지에서 '@' 문자와 치환될 스트링 Array. (Array의 index와
 *           메세지 내의 '@' 문자의 순서가 일치한다.)
 * @return : 치환된 메세지 스트링
 * @author : 임재현
 */
function cfConfirmMsg(msgId, paramArray) {
  if (cfIsNull(msgId)) {
    alert("There is no message id.");
    return null;
  }

  return confirm(new coMessage().getMsg(msgId, paramArray));
}
/**
 * @type   : function
 * @access : public
 * @desc   : 공통메세지에 정의된 메세지를 prompt box 로 보여준다. 만약 패스워드를 입력받는 prompt box를
 *           띄우면서 공통메세지에 정의된 메세지를 보여주고 싶다면 다음과 같이 하면 된다.
 * <pre>
 *     // 공통메세지 영역
 *     var MSG_INPUT_PASSWORD = "@님, 패스워드를 입력하십시오.";
 *     ...
 *     cfPromptMsg(MSG_INPUT_PASSWORD, ["홍길동"], "입력하세요.");
 * </pre>
 * @sig    : msgId[, paramArray[, defaultVal]]
 * @param  : msgId      - required common.js의 공통 메세지 영역에 선언된 메세지 ID
 * @param  : paramArray - optional 메세지에서 '@' 문자와 치환될 스트링 Array. (Array의 index와
 *           메세지 내의 '@' 문자의 순서가 일치한다.)
 * @param  : defaultVal - optional prompt box 의 입력필드에 보여줄 기본값.
 * @return : 입력받은 String 혹은 Integer 타입의 패스워드 데이터
 * @author : 임재현
 */
function cfPromptMsg(msgId, paramArray, defaultVal) {
  if (cfIsNull(msgId)) {
    alert("There is no message id.");
    return null;
  }

  return prompt(new coMessage().getMsg(msgId, paramArray), defaultVal);
}

/**
 * @type   : function
 * @access : public
 * @desc   : 공통메세지에 정의된 메세지를 리턴한다.
 * <pre>
 * // 공통 메세지 영역
 * var MSG_NO_CHANGED        = "변경된 사항이 없습니다.";
 * var MSG_SUCCESS_LOGIN     = "@님 안녕하세요?";
 * ...
 * var message1 = cfGetMsg(MSG_NO_CHANGED);
 * var message2 = cfGetMsg(MSG_SUCCESS_LOGIN, ["홍길동"]);
 * </pre>
 * 위의 예에서 message2 의 값은 "홍길동님 안녕하세요?" 가 된다.
 * @sig    : msgId[, paramArray]
 * @param  : msgId      - required common.js의 공통 메세지 영역에 선언된 메세지 ID
 * @param  : paramArray - optional 메세지에서 '@' 문자와 치환될 데이터 Array. Array의 index와
 *           메세지 내의 '@' 문자의 순서가 일치한다. 치환될 데이터는 [] 사이에 콤마를 구분자로 하여 기술하면 Array 로 인식된다.
 * @return : 치환된 메세지 스트링
 * @author : 임재현
 */
function cfGetMsg(msgId, paramArray) {
  return new coMessage().getMsg(msgId, paramArray);
}

/**
 * @type   : object
 * @access : private
 * @desc   : 메세지를 관리하는 객체이다.
 * @author : 임재현
 */
function coMessage() {
  // method
  this.getMsg = coMessage_getMsg;
}

/**
 * @type   : method
 * @access : public
 * @object : coMessage
 * @desc   : 공통메세지에 정의된 메세지를 치환하여 알려준다.
 * @sig    : message[, paramArray]
 * @param  : message    - required common.js의 공통 메세지 영역에 선언된 메세지 ID
 * @param  : paramArray - optional 메세지에서 '@' 문자와 치환될 스트링 Array. (Array의 index와
 *           메세지 내의 '@' 문자의 순서가 일치한다.)
 * @return : 치환된 메세지 스트링
 */
function coMessage_getMsg(message, paramArray) {
  if (cfIsNull(message)) {
    return null;
  }

  var index = 0;
  var re = /@/g;
  var count = 0;

  if (paramArray == null) {
    return message;
  }

  while ( (index = message.indexOf("@", index)) != -1) {
    if (paramArray[count] == null) {
      paramArray[count] = "";
    }

    message = message.substr(0, index) + String(paramArray[count]) +
              message.substring(index + 1);

    index = index + String(paramArray[count++]).length;
  }

  return message;
}

/**
 * @type   : function
 * @access : public
 * @desc   : 값이 null 이거나 white space 문자로만 이루어진 경우 true를 리턴한다.
 * <pre>
 *     cfIsNull("  ");
 * </pre>
 * 위와같이 사용했을 경우 true를 리턴한다.
 * @sig    : value
 * @param  : value - required 입력값
 * @return : boolean. null(혹은 white space) 여부
 * @author : 임재현
 */
function cfIsNull(value) {
  if (value == null ||
      (typeof(value) == "string" && value.trim() == "")
     ) {
    return true;
  }

  return false;
}
/**
 * @type   : prototype_function
 * @access : public
 * @desc   : 자바스크립트의 내장 객체인 String 객체에 trim 메소드를 추가한다. trim 메소드는 스트링의 앞과 뒤에
 *           있는 white space 를 제거한다.
 * <pre>
 *     var str = " abcde "
 *     str = str.trim();
 * </pre>
 * 위의 예에서 str는 "abede"가 된다.
 * @return : trimed String.
 * @author : 임재현
 */
String.prototype.trim = function() {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

/**
 * @type   : function
 * @access : public
 * @desc   : choice 이름의 checkBox의 상태를 flag값으로 전환한다.
 * <pre>
 *     cfToggleBox(true, "choice", "toggleCheck");
 *     cfToggleBox(true, "choice");
 *     cfToggleBox(true);
 * </pre>
 * 위의 예에서 checkbox "choice"는 모두 checked 상태가 된다.
 * @return : N/A
 * @author : 한주석
 */
function cfToggleBox(flag, chkBoxName){
  if(chkBoxName == null) chkBoxName="choice";
  for (var i=0; i<document.getElementsByName(chkBoxName).length; i++) {
      document.getElementsByName(chkBoxName)[i].checked=flag;
  }
}

/**
 * @type   : function
 * @access : public
 * @desc   : 텍스트 박스내의 모든 문자를 대문자로 변환해준다.
 * <pre>사용예 :
 *
 *     cfCharToUpper( txt_empCd );
 * </pre>
 * @sig    : txt_obj
 * @param  : HTML Text
 * @return : 대문자
 * @author : 조동진
 */
function cfCharToUpper( textObj ) {
  var code = textObj.value;

  for ( i = 0; i < textObj.value.length; i++ ) {
    if ((code.charAt(i)>unescape('%60')) && (code.charAt(i)<unescape('%7b'))) {
      textObj.value = code.toUpperCase();
      break;
    }
  }
}

/**
 * @type   : function
 * @access : public
 * @desc   : 문자열 중간의 공백을 없애는 함수
 * <pre>
 *     var resultStr = cfSkipSpaces("ab  cd");
 * </pre>
 * 위의 예에서 resultStr 은 "abcd" 가 된다.
 * @sig    : str
 * @param  : str      - 공백이 포함된 문자열
 * @return : 공백이 제거된 문자열
 * @author : 이은화
 */
function cfSkipSpaces(str) {
  var newStr = "";
    for (var i=0; i< str.length; i++) {
    if ( (str.substr(i,1) != " ") && str.substr(i,1) != " ") {
      newStr = newStr + str.substr(i,1);
    }
  }
  return newStr;
}

/**
 * @type   : function
 * @access : public
 * @desc   : 문자열 중간의 공백을 없애는 함수
 *           yy.mm.dd(yyyy.mm.dd, yyyymmdd, yymmdd) --> yyyymmdd 형식으로 바꿔줌
 * <pre>
 *     var resultStr = cfStringDateToNum("2003.12.22");
 * </pre>
 * 위의 예에서 resultStr 은 "20031222" 가 된다.
 * @sig    : str
 * @param  : str     -  날짜
 * @return : 변환된 날짜 문자열(실패시 ""를 리턴)
 * @author : 이은화
 */
 /*    사용하지 않음 !!!!!!!!!!!
function cfStringDateToNum(str) {
  var str = cfSkipSpaces(str);
  var dateNum = "";
  // 숫자만 분리
  for (var i=0; i<str.length;i++ ) {
    if ((str.substr(i,1) >= '0') && (str.substr(i,1) <= '9'))
      dateNum = dateNum + str.substr(i,1);
  }
  if (dateNum.length < 1) {
    cfAlertMsg(MSG_COM_ERR_001);
    return "";
  }
  if ((dateNum.length != 6) && (dateNum.length != 8)) {
    cfAlertMsg(MSG_COM_ERR_002);
    return "";
  }
  if (dateNum.length == 6) {
    if (parseInt(dateNum.substr(0,2),10) >= 50 )
      dateNum = "19" + dateNum;
    else
      dateNum = "20" + dateNum;
  }
  return dateNum;

}*/

/**
 * @type   : function
 * @access : public
 * @desc   : Date String 에서 / . - 를 제거한다.
 * <pre>
 *     var resultDate = cfGetUnmaskDate("2004/12/12");
 * </pre>
 *  위의 예에서 resultDate 는 20041212 가 된다.
 *
 * @sig    : dateObj
 * @param  : dateObj     -  YYYYMMDD 형식의 지정일자
 * @return : YYYYMMDD 형식의 String
 * @author : 이은화
 */
function cfGetUnmaskDate(str) {
    if(str == "" )
        return "";	
    var dateStr = str.replace(/[\/.-]/g, "");
    
    return dateStr;
	
}
/**
 * @type   : function
 * @access : public
 * @desc   : O_DATE_FORMAT에 정의된 형식의 String을 Date Object로 변환
 * <pre>
 *     var resultDate = cfGetDateObject("2004/12/12");
 * </pre>
 * 위의 예에서 resultDate는 Date Object 가 된다.
 * @sig    : dateObj
 * @param  : dateObj     -  YYYYMMDD 형식의 지정일자
 * @return : YYYYMMDD 형식의 String
 * @author : 이은화
 */
function cfGetDateObject(dateStr) {
  if(dateStr == "") 
      return null;
      	
  var dateFormat = O_DATE_FORMAT;
  var yearIndex = dateFormat.indexOf("YYYY");
  var monthIndex = dateFormat.indexOf("MM");
  var dayIndex = dateFormat.indexOf("DD");
  
  dateStr = cfGetUnmaskDate(dateStr);

  var dateObj = new Date();
  dateObj.setFullYear( parseInt(dateStr.substr(yearIndex,4),10),
                     parseInt(dateStr.substr(monthIndex,2),10)-1,
                     parseInt(dateStr.substr(dayIndex,2),10) );
  
  return dateObj;
}

/**
 * @type   : function
 * @access : public
 * @desc   : O_YMDATE_FORMAT에 정의된 형식의 String을 Date Object로 변환
 * <pre>
 *     var resultDate = cfGetDateObject("12/2004");
 * </pre>
 * 위의 예에서 resultDate는 Date Object 가 된다.
 * @sig    : dateObj
 * @param  : dateObj     -  O_YMDATE_FORMAT에 형식의 지정일자
 * @return : date
 * @author : 이은화
 */
function cfGetYmDateObject(dateStr) {
  if(dateStr == "") 
      return null;
      	
  var dateFormat = O_YMDATE_FORMAT;
  var yearIndex = dateFormat.indexOf("YYYY");
  var monthIndex = dateFormat.indexOf("MM");
  
  dateStr = cfGetUnmaskDate(dateStr);

  var dateObj = new Date();
  dateObj.setFullYear( parseInt(dateStr.substr(yearIndex,4),10),
                     parseInt(dateStr.substr(monthIndex,2),10)-1,
                     01 );
  
  return dateObj;
}

/**
 * @type   : function
 * @access : public
 * @desc   : Date Object를 O_DATE_FORMAT 에 정의된 형식의 String으로 변환하여 리턴한다.
 * <pre>
 *     var resultDate = cfGetDateString(todayObj);
 * </pre>
 * 위의 예에서 resultDate는 "20031223" 이 된다.
 * @sig    : dateObj
 * @param  : dateObj      - YYYYMMDD 형식의 지정일자
 * @return : YYYYMMDD 형식의 String
 * @author : 이은화
 */
function cfGetDateString(dateObj) {
  if( dateObj == null )
      return "";
      
  var year, mon, day;

  year = dateObj.getFullYear().toString();
  mon = (dateObj.getMonth() + 1).toString();
  day = dateObj.getDate().toString();

  if (mon.length == 1) mon = '0'+mon;
  if (day.length == 1) day = '0'+day;

  var dateFormat = O_DATE_FORMAT;
  var dateStr = ""
  dateStr = dateFormat.replace(/YYYY/, year)
  dateStr = dateStr.replace(/MM/, mon);
  dateStr = dateStr.replace(/DD/, day);

  return dateStr;
}

/**
 * @type   : function
 * @access : public
 * @desc   : Date Object를 O_YMDATE_FORMAT 에 정의된 형식의 String으로 변환하여 리턴한다.
 * <pre>
 *     var resultDate = cfGetDateString(todayObj);
 * </pre>
 * 
 * @sig    : dateObj
 * @param  : dateObj      
 * @return : O_YMDATE_FORMAT 형식의 String
 * @author : 이은화
 */
function cfGetYmDateString(dateObj) {
  if( dateObj == null )
      return "";
      
  var year, mon;

  year = dateObj.getFullYear().toString();
  mon = (dateObj.getMonth() + 1).toString();

  if (mon.length == 1) mon = '0'+mon;

  var dateFormat = O_YMDATE_FORMAT;
  var dateStr = ""
  dateStr = dateFormat.replace(/YYYY/, year)
  dateStr = dateStr.replace(/MM/, mon);

  return dateStr;
}
/**
 * @type   : function
 * @access : public
 * @desc   : 지정일자부터 지정일 이전의 날짜를 구한다.
 * <pre>
 *     var resultDate = cfGetPrevDayNum("20031225", 5);
 * </pre>
 * 위의 예에서 resultDate는 "20031220" 이 된다.
 * @sig    : date, days
 * @param  : date     - O_DATE_FORMAT에 정의된 형식의 지정일자
 * @param  : days     - 계산할 기간
 * @return : YYYYMMDD 형식의 String
 * @author : 이은화
 */
function cfGetPrevDayNum(date, days) {
  if ( days == '0') return date;
  date = cfGetUnmaskDate(date);

  var dateObj = cfGetDateObject(date);

  dateObj.setDate(dateObj.getDate() - parseInt(days,10));

  return cfGetDateString(dateObj);
}

/**
 * @type   : function
 * @access : public
 * @desc   : 지정일자부터 지정일 이후의 날짜를 구한다.
 * <pre>
 *     var resultDate = cfGetNextDayNum("2004/12/12", 5);
 * </pre>
 * 위의 예에서 resultDate는 "20031230" 이 된다.
 * @sig    : date, days
 * @param  : date    -  O_DATE_FORMAT에 정의된 형식의 지정일자
 * @param  : days    -  계산할 기간
 * @return : YYYYMMDD 형식의 String
 * @author : 이은화
 */
function cfGetNextDayNum(date, days) {
  if ( days == '0') return date;
  date = cfGetUnmaskDate(date);
    if (date == "") return "";
    var dateObj = cfGetDateObject(date);

  dateObj.setDate(dateObj.getDate()+ parseInt(days,10));

  return cfGetDateString(dateObj);
}

/**
 * @type   : function
 * @access : public
 * @desc   : 공통으로 사용하는 달력창을 띄운다.
 * <xmp>
 *    달력의 선택값을 셋팅할 text object는 반드시 id를 지정해야 한다.
 *
 *  <td width="10%" class="search_left">시작날짜</td>
 *  <td width="24%" class="search_right">
 *     <table  border="0" cellspacing="0" cellpadding="0">
 *        <tr align="left" valign="middle">
 *          <td ><input name="startDate" id="startDate" type="text" class="textarea" size="12" date></td>
 *          <td ><img src="/images/common/calendar.gif" width="40" height="19" onmouseover="this.style.cursor='hand'" onClick="cfShowCalendar(startDate);"></td>
 *        </tr>
 *     </table>
 *  </td>
 *
 * </xmp>
 * @sig    : oItem[,ymFlag[, oDayItem]]]
 * @param  : oItem    - 달력창으로부터 선택된 날짜를 Text값으로 가지는 오브젝트.
 * @param  : ymFlag   - 년월까지만 보여주도록 하는 플래그
 * @param  : oDayItem - 달력창으로부터 선택된 날짜에 해당하는 요일명을 가질 오브젝트
 * @author : 이은화
 */
function cfShowCalendar(oItem, ymFlag, oDayItem) { //, month, year) {
    var dateFormat = O_DATE_FORMAT; 
    var ymdateFormat = O_YMDATE_FORMAT; 
    var sToday = "";
    var sYear = "";
    var sMonth = "";
    var sDay = ""; 
    var month ="";
    var year = "";

    //서버의 현재 날짜 가져오기
    if(opener != null ) {
        sToday = opener.parent.hidden.hInfoFrm.today.value;
        sYear = parent.hidden.hInfoFrm.todayYear.value;
        sMonth = parent.hidden.hInfoFrm.todayMonth.value;
        sDay = parent.hidden.hInfoFrm.todayDay.value;
    }
    else {
	
        sToday = parent.hidden.hInfoFrm.today.value;
        sYear = parent.hidden.hInfoFrm.todayYear.value;
        sMonth = parent.hidden.hInfoFrm.todayMonth.value;
        sDay = parent.hidden.hInfoFrm.todayDay.value;
    }

    var inputDate = oItem.value;

    if(cfIsNull(inputDate) == false) {

      inputDate = cfGetUnmaskDate(inputDate);

      if( ymFlag == true ) {
      	var yearIndex = ymdateFormat.indexOf("YYYY");
        var monthIndex = ymdateFormat.indexOf("MM");
        month = inputDate.substr(monthIndex,2);
        year = inputDate.substr(yearIndex,4);
      	
      }
      else {
	var yearIndex = dateFormat.indexOf("YYYY");
        var monthIndex = dateFormat.indexOf("MM");
        month = inputDate.substr(monthIndex,2);
        year = inputDate.substr(yearIndex,4);
	
      }
      
      if( year > 2043 || year < 1881) {
            year = sYear;
            month = sMonth;

        }
        if( month > 12 || month < 1 )  {
             year = sYear;
             month = sMonth;
        }

    }
    else {
      //월
      if (cfIsNull(month)) {
            month = sMonth;
      }
      else {
  if( month >12 || month < 1)
      month = sMonth;
      }

      //년도
      if (cfIsNull(year)) {
            year = sYear;
      }
      else {
  if( year > 2043 || year < 1881)
      year = sYear;
      }
    }

    GLB_CALENDAR.eventSrc = event.srcElement;
    GLB_CALENDAR.oItem = oItem.id;
    GLB_CALENDAR.month = month;
    GLB_CALENDAR.year = year;
    GLB_CALENDAR.dateFormat = dateFormat;
    GLB_CALENDAR.ymdateFormat = ymdateFormat;
    GLB_CALENDAR.ymFlag = ymFlag;
    GLB_CALENDAR.sToday = sToday;

    if(oDayItem == null)
        GLB_CALENDAR.oDayItem = "";
    else
      GLB_CALENDAR.oDayItem = oDayItem.id;

    var dwn = document.createElement("DOWNLOAD");
    dwn.style.behavior="url(#default#download)";
    dwn.startDownload("/html/common/calendar.html", cfOnDoneDownLoadCalendar);
}

function cfOnDoneDownLoadCalendar(src) {
    GLB_CALENDAR.popup = window.createPopup();
    GLB_CALENDAR.popup.document.write(src);

    GLB_CALENDAR.popup.document.all("oItem").value = GLB_CALENDAR.oItem;
    GLB_CALENDAR.popup.document.all("oDayItem").value = GLB_CALENDAR.oDayItem;
    GLB_CALENDAR.popup.document.all("oMonth").value = GLB_CALENDAR.month - 1;
    GLB_CALENDAR.popup.document.all("oYear").value = GLB_CALENDAR.year;
    GLB_CALENDAR.popup.document.all("oDateFormat").value = GLB_CALENDAR.dateFormat;
    GLB_CALENDAR.popup.document.all("oYmdateFormat").value = GLB_CALENDAR.ymdateFormat;
    GLB_CALENDAR.popup.document.all("oYmFlag").value = GLB_CALENDAR.ymFlag;
    GLB_CALENDAR.popup.document.all("oSToday").value = GLB_CALENDAR.sToday;
    GLB_CALENDAR.popup.document.all("oRefreshBtn").fireEvent("onclick");
    GLB_CALENDAR.popup.show(0, 0, 240, 220, GLB_CALENDAR.eventSrc);
}

/**
 * @type   : function
 * @access : public
 * @desc   : input 필드나 textarea 의 사이즈를 제한하여 지정된 길이 이상
 *           입력할 경우 추가입력된 메세지를 출력하고 추가 입력된 문자는 삭제함
 *
 * <xmp>
 *  <INPUT TYPE="text" NAME="txtDesc" OnKeyUp="cfLengthCheck(this, 100);">
 *  <TEXTAREA name="txtDesc" rows="10" cols="60" OnKeyUp="cfLengthCheck(this, 4000);"></TEXTAREA>
 * </xmp>
 * @param  : targetObj - Textarea Object
 * @param  : maxLength - Max Length(영문기준)
 * @return :
 * @author : 이은화
 */
function cfLengthCheck(targetObj, maxLength) {
    var len = 0;
    var newtext = "";
    for(var i=0 ; i < targetObj.value.length; i++) {
        var c = escape(targetObj.value.charAt(i));

        if ( c.length == 1 ) len ++;
        else if ( c.indexOf("%u") != -1 ) len += 2;
        else if ( c.indexOf("%") != -1 ) len += c.length/3;

        if( len <= maxLength ) newtext += unescape(c);
    }

    if ( len > maxLength ) {
        cfAlertMsg(JMSG_COMF_ERR_007, [maxLength]);
        targetObj.value = newtext;
        targetObj.focus();
        return false;
    }
}


/**
 * @type   : function
 * @access : public
 * @desc   : 날짜 스트링을 입력 받아 해당하는 요일명이나 요일 코드를 리턴한다.
 *
 * @sig    : dateStr, typeChr
 * @param  : dateStr - O_DATE_FORMAT에 정의된 형식의 지정일자
 * @param  : typeChr - "c" 이면 날짜코드를 리턴하고 "n" 이면 요일명을 리턴한다. 값이 없으면 디폴트는 "c"
 * @return : day     - 요일명이나 요일코드를 리턴
 * @author : 이은화
 */
function cfGetDay(dateStr, typeChr){
    var orgDateStr = cfGetUnmaskDate(dateStr);

    var orgDate = cfGetDateObject(dateStr);
    var day = orgDate.getDay();

    if(typeChr != null && typeChr == "n") {
      var week = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
      return week[day];
    }
    else {
        return day;
    }
}

/**
 * @type   : function
 * @access : public
 * @desc   : 기본적으로 입력받은 두 날짜값 (yyyymmdd 형태)을 비교하여
 *           첫번째 날짜 값이 두번째 날짜 값보다 큰 경우 메세지를 띄우고
 *           false를 반환한다.
 *           만약, 기간제한값을 파라미터로 같이 넘기는 경우에는 두 일시의
 *           차이가 기간제한값 보다 크면 메세지를 띄우고 false를 반환한다.
 *
 * @sig    : startDateStr, endDateStr[, limit]
 * @param  : startDateStr  - O_DATE_FORMAT 형식의 Date
 * @param  : endDateStr    - O_DATE_FORMAT 형식의 Date
 * @param  : limit         - 기간제한값(일) optional
 * @return :  true or false 리턴
 * @author : 이은화
 */
function cfCheckTwoDateStr(startDateStr, endDateStr, limit){
    var startStr = cfGetServerDateStr(startDateStr, "YYYYMMDD");
    
    var endStr = cfGetServerDateStr(endDateStr, "YYYYMMDD");

    if (startStr > endStr) {
        cfAlertMsg(JMSG_COMF_ERR_002);
        return false;
    }
    
    var startDateObj = cfGetDateObject(startDateStr);
    var endDateObj = cfGetDateObject(endDateStr);
    var diff = parseInt((endDateObj - startDateObj) / 86400000, 10);
    
    if (limit != null) {
        if (diff > limit - 1) {
            cfAlertMsg(JMSG_COMF_ERR_003, [limit]);
            return false;
        }
    }

    return true;
}


/**
 * @type   : function
 * @access : public
 * @desc   : 기본적으로 입력받은 두 날짜값 (O_YMDATE_FORMAT 형태)을 비교하여
 *           첫번째 날짜 값이 두번째 날짜 값보다 큰 경우 메세지를 띄우고
 *           false를 반환한다.
 *           두 일시의 개월 차이가 차이가 기간제한값 보다 크면 메세지를 띄우고 false를 반환한다.
 *
 * @sig    : startDateStr, endDateStr[, limit]
 * @param  : startDateStr  - 날짜스트링으로 YYYYMMDD or YYYY/MM/DD
 * @param  : endDateStr    - 날짜스트링으로 YYYYMMDD or YYYY/MM/DD
 * @param  : limit         - 기간제한값(월) optional
 * @return :  true or false 리턴
 * @author : 이은화
 */
function cfCheckTwoYmMonthStr(startDateStr, endDateStr, limit){
  var startStr = cfGetServerYmDateStr(startDateStr, "YYYYMM") + "01";
  var endStr = cfGetServerYmDateStr(endDateStr, "YYYYMM") + "01";

  if (startStr > endStr) {
      cfAlertMsg(JMSG_COMF_ERR_002);
      return false;
  }

  if (cfIsNull(limit) == false && limit != 0 ) {
    var validEndStr = cfGetNextYmMonthNum(startDateStr, limit - 1);
    validEndStr = cfGetServerYmDateStr(validEndStr, "YYYYMM") + "01";

      if ( endStr > validEndStr) {
          cfAlertMsg(JMSG_COMF_ERR_004, [limit]);
          return false;
      }
  }

  return true;
}

/**
 * @type   : function
 * @access : public
 * @desc   : Date String 을 DB 서버에서 인식하는 포맷으로 변경한다.
 *           serverDateFormat 값을 지정하지 않으면 O_SERVER_DATE_FORMAT 포맷으로 변경하고
 *           지정해주면 특정포맷으로 변경한다.
 *
 * @sig    : dateStr[, limit]
 * @param  : dateStr  - O_DATE_FORMAT 형식의 Date
 * @param  : serverDateFormat    - YYYYMMDD 등의 포맷
 * @param  : limit         - 기간제한값(일) optional
 * @return :  true or false 리턴
 * @author : 이은화
 */
function cfGetServerDateStr(dateStr, serverDateFormat) {
  
  var dateFormat = O_DATE_FORMAT;
  var yearIndex = dateFormat.indexOf("YYYY");
  var monthIndex = dateFormat.indexOf("MM");
  var dayIndex = dateFormat.indexOf("DD");

  dateStr = cfGetUnmaskDate(dateStr);

  var year = dateStr.substr(yearIndex,4);
  var month = dateStr.substr(monthIndex,2);
  var day = dateStr.substr(dayIndex,2);
  
  var serverFormat = O_SERVER_DATE_FORMAT;
  if( typeof(serverDateFormat) != 'undefined' ) 
      serverFormat = serverDateFormat;
      
  var dateStr = ""
  dateStr = serverFormat.replace(/YYYY/, year)
  dateStr = dateStr.replace(/MM/, month);
  dateStr = dateStr.replace(/DD/, day);
  
  return dateStr;
}

/**
 * @type   : function
 * @access : public
 * @desc   : Date String 을 DB 서버에서 인식하는 포맷으로 변경한다.
 *           serverDateFormat 값을 지정하지 않으면 O_SERVER_DATE_FORMAT 포맷으로 변경하고
 *           지정해주면 특정포맷으로 변경한다.
 *
 * @sig    : dateStr[, limit]
 * @param  : dateStr  - O_DATE_FORMAT 형식의 Date
 * @param  : serverDateFormat    - YYYYMMDD 등의 포맷
 * @param  : limit         - 기간제한값(일) optional
 * @return :  true or false 리턴
 * @author : 이은화
 */
function cfGetServerYmDateStr(dateStr, serverDateFormat) {
  
  var dateFormat = O_YMDATE_FORMAT;
  var yearIndex = dateFormat.indexOf("YYYY");
  var monthIndex = dateFormat.indexOf("MM");

  dateStr = cfGetUnmaskDate(dateStr);

  var year = dateStr.substr(yearIndex,4);
  var month = dateStr.substr(monthIndex,2);
  
  var serverFormat = O_SERVER_YMDATE_FORMAT;
  if( typeof(serverDateFormat) != 'undefined' ) 
      serverFormat = serverDateFormat;
      
  var dateStr = ""
  dateStr = serverFormat.replace(/YYYY/, year)
  dateStr = dateStr.replace(/MM/, month);
  
  return dateStr;
}

/**
 * @type   : function
 * @access : public
 * @desc   : DB를 기준으로 한 오늘 날짜를 O_DATE_FORMAT 포맷으로 가져옴
 *
 * @sig    :
 * @return :  오늘날짜(년월일)
 * @author : 이은화
 */
function cfGetToday() {
    if(opener != null ) {
        return opener.parent.hidden.hInfoFrm.today.value;
    }
    else {
        return parent.hidden.hInfoFrm.today.value
    }
}

/**
 * @type   : function
 * @access : public
 * @desc   : DB를 기준으로 한 오늘 년월을 O_YMDATE_FORMAT  포맷으로 가져옴
 *           YYYYMM or MMYYYY
 *            
 * @sig    :
 * @return :  오늘날짜(년월)
 * @author : 이은화
 */
function cfGetYmToday() {
    var year, mon;

    year = cfGetTYear();
    mon = cfGetTMonth();
  
    var dateFormat = O_YMDATE_FORMAT;
    var dateStr = ""
    dateStr = dateFormat.replace(/YYYY/, year)
    dateStr = dateStr.replace(/MM/, mon);
    
    return dateStr;
}

/**
 * @type   : function
 * @access : public
 * @desc   : DB를 기준으로 한 년도를 가져옴
 *
 * @sig    :
 * @return :  년도
 * @author : 이은화
 */
function cfGetTYear() {
    if(opener != null ) {
        return opener.parent.hidden.hInfoFrm.todayYear.value;
    }
    else {
        return parent.hidden.hInfoFrm.todayYear.value;
    }
}

/**
 * @type   : function
 * @access : public
 * @desc   : DB를 기준으로 한 월을 가져옴
 *
 * @sig    :
 * @return :  월
 * @author : 이은화
 */
function cfGetTMonth() {
    if(opener != null ) {
        return opener.parent.hidden.hInfoFrm.todayMonth.value;
    }
    else {
        return parent.hidden.hInfoFrm.todayMonth.value;
    }
}

/**
 * @type   : function
 * @access : public
 * @desc   : DB를 기준으로 한 날짜를 가져옴
 *
 * @sig    :
 * @return :  날짜
 * @author : 이은화
 */
function cfGetTDay() {
    if(opener != null ) {
        return opener.parent.hidden.hInfoFrm.todayDay.value;
    }
    else {
        return parent.hidden.hInfoFrm.todayDay.value;
    }
}

/**
 * @type   : function
 * @access : public
 * @desc   : 두 날짜 오브젝트에 현재날짜를 기준으로 입력 weeks 차이 만큼 날짜를 셋팅
 *
 * @sig    : startDate, endDate, weeks
 * @param  : startDateStr  - 시작날짜 입력 Object
 * @param  : endDateStr    - 종료날짜 입력 Object
 * @param  : limit         - 기간제한값 (week 기준)
 * @return : N/A
 * @author : 이은화
 */
function cfSetWeeks(startDate, endDate, weeks) {

  startDate.value =   cfGetPrevDayNum(cfGetToday(), weeks*7 - 1);
  endDate.value = cfGetToday();

  startDate.focus();
  startDate.blur();
  endDate.focus();
  endDate.blur();
}

/**
 * @type   : function
 * @access : public
 * @desc   : 두 날짜 오브젝트에 현재날짜를 기준으로 입력 months 차이 만큼 날짜를 셋팅
 *
 * @sig    : startDate, endDate, months
 * @param  : startDateStr  - 시작날짜 입력 Object
 * @param  : endDateStr    - 종료날짜 입력 Object
 * @param  : months         - 기간제한값 (Month 기준)
 * @return : N/A
 * @author : 이은화
 */
function cfSetMonths(startDate, endDate, months) {
  startDate.value =  cfGetNextDayNum(cfGetPrevMonthNum(cfGetToday(), months), 1);
  endDate.value = cfGetToday();

  startDate.focus();
  startDate.blur();
  endDate.focus();
  endDate.blur();
}

/**
 * @type   : function
 * @access : public
 * @desc   : 두 날짜 오브젝트에 현재날짜를 기준으로 입력 months 차이 만큼 날짜를 셋팅
 *           ymdate 키워드에만 사용한다.
 *
 * @sig    : startDate, endDate, months
 * @param  : startDateStr  - 시작날짜 입력 Object
 * @param  : endDateStr    - 종료날짜 입력 Object
 * @param  : months         - 기간제한값 (Month 기준)
 * @return : N/A
 * @author : 이은화
 */
function cfSetYmMonths(startDate, endDate, months) {
  startDate.value =   cfGetNextYmMonthNum(cfGetPreYmMonthNum(cfGetYmToday(), months), 1);
  endDate.value = cfGetYmToday();

  startDate.focus();
  startDate.blur();
  endDate.focus();
  endDate.blur();
}

/**
 * @type   : function
 * @access : public
 * @desc   : 지정일자부터 지정 월 이전의 날짜를 구한다.
 * <pre>
 *     var resultDate = cfGetPrevMonthNum("20040605", 2);
 * </pre>
 * 위의 예에서 resultDate는 "20040405" 이 된다.
 *
 * @sig    : date, months
 * @param  : date    -  YYYYMMDD or YYYY/MM/DD 형식의 지정일자
 * @param  : months    -  계산할 기간(월)
 * @return : YYYYMMDD 형식의 String
 * @author : 이은화
 */
function cfGetPrevMonthNum(date, months) {
  if ( months == '0') return date;
  date = cfGetUnmaskDate(date);

  var dateObj = cfGetDateObject(date);

  dateObj.setMonth(dateObj.getMonth() - months);

  return cfGetDateString(dateObj);
}

/**
 * @type   : function
 * @access : public
 * @desc   : 지정일자부터 지정 월 이전의 날짜를 구한다.
 *           ymdate 키워드 입력값에 대해서만 사용한다.
 * <pre>
 *     var resultDate = cfGetPrevMonthNum("200406", 2);
 * </pre>
 * 위의 예에서 resultDate는 "200404" 이 된다.
 *
 * @sig    : date, months
 * @param  : date    -  YYYYMM or MM/YYYY 등 형식의 지정일자
 * @param  : months    -  계산할 기간(월)
 * @return : O_YMDATE_FORMAT 형식의 String
 * @author : 이은화
 */
function cfGetPreYmMonthNum(date, months) {
  if ( months == '0') return date;
  date = cfGetUnmaskDate(date);

  var dateObj = cfGetYmDateObject(date);

  dateObj.setMonth(dateObj.getMonth() - months);

  return cfGetYmDateString(dateObj);
}

/**
 * @type   : function
 * @access : public
 * @desc   : 지정일자부터 지정 월 이후의 날짜를 구한다.
 * <pre>
 *     var resultDate = cfGetNextMonthNum("20040605", 2);
 * </pre>
 * 위의 예에서 resultDate는 "20040805" 이 된다.
 *
 * @sig    : date, months
 * @param  : date    -  YYYYMMDD or YYYY/MM/DD 형식의 지정일자
 * @param  : months    -  계산할 기간(월)
 * @return : YYYYMMDD 형식의 String
 * @author : 이은화
 */
function cfGetNextMonthNum(dateStr, months) {
  if ( months == '0') return dateStr;
  dateStr = cfGetUnmaskDate(dateStr);

  var dateObj = cfGetDateObject(dateStr);

  dateObj.setMonth(dateObj.getMonth() + months);

  return cfGetDateString(dateObj);
}

/**
 * @type   : function
 * @access : public
 * @desc   : 지정일자부터 지정 월 이후의 날짜를 구한다.
 *           ymdate 키워드 입력값에 대해서만 사용한다. 
 * <pre>
 *     var resultDate = cfGetNextMonthNum("122004", 2);
 * </pre>
 * 위의 예에서 resultDate는 "022004" 이 된다.
 *
 * @sig    : date, months
 * @param  : date    -  YYYYMM or MM/YYYY 등 형식의 지정일자
 * @param  : months    -  계산할 기간(월)
 * @return : YYYYMMDD 형식의 String
 * @author : 이은화
 */
function cfGetNextYmMonthNum(dateStr, months) {
  if ( months == '0') return dateStr;
  dateStr = cfGetUnmaskDate(dateStr);

  var dateObj = cfGetYmDateObject(dateStr);

  dateObj.setMonth(dateObj.getMonth() + months);

  return cfGetYmDateString(dateObj);
}

/**
 * @type   : function
 * @access : public
 * @desc   : 기본적으로 입력받은 두 날짜값 (yyyymmdd 형태)을 비교하여
 *           첫번째 날짜 값이 두번째 날짜 값보다 큰 경우 메세지를 띄우고
 *           false를 반환한다.
 *           두 일시의 개월 차이가 차이가 기간제한값 보다 크면 메세지를 띄우고 false를 반환한다.
 *
 * @sig    : startDateStr, endDateStr[, limit]
 * @param  : startDateStr  - 날짜스트링으로 YYYYMMDD or YYYY/MM/DD
 * @param  : endDateStr    - 날짜스트링으로 YYYYMMDD or YYYY/MM/DD
 * @param  : limit         - 기간제한값(월) optional
 * @return :  true or false 리턴
 * @author : 이은화
 */
function cfCheckTwoMonthsStr(startDateStr, endDateStr, limit){
  var startStr = cfGetServerDateStr(startDateStr, "YYYYMMDD");
  var endStr = cfGetServerDateStr(endDateStr, "YYYYMMDD");

  if (startStr > endStr) {
      cfAlertMsg(JMSG_COMF_ERR_002);
      return false;
  }

  if (cfIsNull(limit) == false && limit != 0 ) {
    var validEndStr = cfGetPrevDayNum( cfGetNextMonthNum(startDateStr, limit) , 1);
    validEndStr = cfGetServerDateStr(validEndStr, "YYYYMMDD");
      if ( endStr > validEndStr) {
          cfAlertMsg(JMSG_COMF_ERR_004, [limit]);
          return false;
      }
  }

  return true;
}

/**
 * @type   : function
 * @access : public
 * @desc   : MS IE 의 버전을 리턴
  *
 * @sig    : 
 * @return : version
 * @author : 이은화
 */
function cfGetIEVer() {
 	var version=0;

	if (navigator.appVersion.indexOf("MSIE") != -1) {
		temp = navigator.appVersion.split("MSIE");
		version = parseFloat(temp[1]);
	}
	
	return version;
}

/**
 * @type   : function
 * @access : public
 * @desc   : OZ Viewer 화면을 띄운다.
 * <pre>
 *     cfOpenOzWindow('/jsp/mgt/user/UserListRO.jsp?userId=', 660, 690);
 *
 *     만약, xjos 키워드가 사용되어 validation 및 unmasking 한 값이 파라미터로
 *     전송되어야 한다면 다음과 같이 사용한다.
 *     if ( document.frmUserRM.validate() == true ) {  //validation 수행
 *       var targetUrl =  "/jsp/mgt/user/UserListRO.jsp?startDate="
 *                         + document.frmUserRM.startDate.getUnmasked();   //unmasking 된 값을 파라미터로 넘겨준다.
 *
 *       cfOpenOzWindow(targetUrl, 660, 690);
 *      }
 *
 *     ※ 화면 사이즈 참고사항
 *        A4 용지 기준으로 보고서를 만들 경우,
 *
 *        가로 화면 - 890 x 690 (가로, 세로 스크롤이 생기지 않는 사이즈)
 *        세로 화면 - 660 x 690 (세로 스크롤만 생기는 사이즈)
 *
 * </pre>
 *
 * @sig    : targetUrl, wid, heig
 * @param  : targetUrl  open 할 jsp 페이지 주소
 * @param  : wid      넓이
 * @param  : heig     높이
 * @return : N/A
 * @author : 이은화
 */
 function cfOpenOzWindow(targetUrl, wid, hei) {
     var winLeft   = (screen.width - wid) / 2;
     var winTop = 10; //(screen.height - hei) / 2;
     var winProps = 'height=' + hei + ',width=' + wid + ',top='+winTop+',left='+winLeft+',scrollbars=no, toolbar=no, resize=no, status=no';

     //window.open(targetUrl,'', winProps);
     cfOpenWindowPost(targetUrl,'', winProps);
}


/**
 * @type   : function
 * @access : public
 * @desc   : Select Box 의 선택값을 지정한다.
 *
 * @sig    : setValue, obj
 * @param  : setValue  - 선택되어야 하는 값
 * @param  : obj    - Select Box Object
 * @return : N/A
 * @author : 이은화
 */
function cfSetSelected(setValue, obj){
     
     if(cfIsNull(setValue) == false) {
         for(var i = 0; i < obj.options.length ; i++ ) {
             if(obj.options[i].value == setValue) {
                 obj.options[i].selected = true; 
                 break;
             }   
         }
     
     }
}

/**
 * @type   : function
 * @access : public
 * @desc   : checkbox의 배열들중에 하나라도 선택된 것이 있는지 체크한다.
 *
 * @sig    : obj
 * @param  : obj    - Check Box Object
 * @return : true or false
 * @author : 이은화
 */
function cfIsChecked(obj){
     
     var total = 0;
      
      if( obj != null ) {
      	  if( typeof(obj.length) == 'undefined' )
      	      return obj.checked;
      	      
          for( var i = 0 ; i < obj.length ; i++ ) {
              if(obj[i].checked == true)
                  total++;
          }
      }
      
      if(total == 0)
        return false;
      else
      	return true;
}

/**
 * @type   : function
 * @access : public
 * @desc   : Open Window Popup : get -> Post
 *
 * @sig    : url, winName, winProps
 * @param  : url      - target url
 * @param  : winName  - window name
 * @param  : winProps - window Properties
 * @return : window
 * @author : Seo Sung-il
 * @Date   : 2006-11-08
 */
function cfOpenWindowPost(url, winName, winProps) {

	var urlString = url;
	var urlPage   =""
	var urlQuery  ="";
	var tmp       =""
	var tmp2      ="";
	var farWindow, oInput;

	if (urlString.indexOf("?") > -1) {  // QueryString exist
		
		farWindow = window.open('about:blank', winName, winProps);    
		farWindow.document.write("<form name='frmfarWindowForm' method='post'>");
		farWindow.document.write("</form>");
	
		urlPage = urlString.substring(0, urlString.indexOf("?"));
		urlQuery= urlString.substring(urlString.indexOf("?")+1);
		
		tmp = urlQuery;
		
		if(tmp != null) {
			tmp = tmp.split("&");
			
			for(var i = 0; i<tmp.length; i++) {
				tmp2 = tmp[i].split("=");
				
				oInput = farWindow.document.createElement("<INPUT TYPE='hidden'>");
				oInput.name  = tmp2[0];
				oInput.value = tmp2[1];
				farWindow.document.frmfarWindowForm.appendChild(oInput);				
			}
		}
		
		farWindow.document.frmfarWindowForm.action = urlPage;
		farWindow.document.frmfarWindowForm.submit();

	} else {  // QueryString not exist
	
		farWindow = window.open(url, winName, winProps);
	    
	}
	
	return farWindow;
}
