/***********************************************************
	DESC : 프레임웍 공통 JS
	     : 메소드 추가필요시 운영자에게 연락바람 
	@author HJ.Lee
	@since 2006.02.21
************************************************************/

/**
*   페이지 클릭시 해당 FORM SUBMIT
*   개발자가 별도의 작업이 필요하면 이 메소드를  Overriding한다.
*/
function paging(pageno,listCnt){
	var f = findFormElement();
	if( f == null ) {
		alert('FORM TAG NOT FOUND!')
		return;
	}
	//alert("pageno:"+pageno+", listCnt:"+listCnt)
	if( listCnt == null || listCnt == 'undefined' ) {
		listCnt = f.paging_listcnt.value
	}
	if( f.paging_facade ) {
   if(!isNullStr(f.paging_facade.value) ) {
     f.facade.value = f.paging_facade.value
    }
  }
	
    f.currpage_no.value=pageno;
	f.nextpage.value=f.paging_nextpage.value;
    f.command.value=f.paging_command.value;
    f.paging_listcnt.value=listCnt;
	f.submit();
}
/**
*   헤더 타이틀 클릭시 소트
*   해당 JSP의 JavaScript query()호출한다.
*   개발자가 별도의 작업이 필요하면 이 메소드를  Overriding한다.
*/
function headerSort(column,sortcolumn,sortcond){
	var f = findFormElement();
	if( f == null ) {
		alert('FORM TAG NOT FOUND!')
		return;
	}
    if(column == sortcolumn && sortcond == 'ASC'){
	   sortcond = 'DESC';
    }else{
	   sortcond = 'ASC';
    }
    if( f.currpage_no ) {
	    f.currpage_no.value=1;
	}
    f.sort_column.value=column;
    f.sort_cond.value=sortcond;
    try{	
	   query();
    }catch(Exception){
	   alert("query() method not found! "+ Exception.description);
    }
}

/**
* 이전 페이지로 이동
* 현재 지정되어 있는 값과 틀릴경우만 각 값을 넘긴다.
* 개발자가 별도의 작업이 필요하면 이 메소드를  Overriding한다.
* @param f formName
* @param target target (미 입력시 form의 디폴트 값 이용)
* @param facade facade (미 입력시 form의 디폴트 값 이용)
* @param command command (미 입력시 form의 디폴트 값 이용)
* @param nextpage nextpage (미 입력시 form의 디폴트 값 이용)
* @param param param (미 입력시 form의 디폴트 값 이용)
*/
function back(f,target,facade,command,nextpage,param){
	if( !isNullStr(facade) ) f.facade.value=facade
	if( !isNullStr(command)) f.command.value=command
	if( !isNullStr(nextpage)) f.nextpage.value=nextpage
	if( !isNullStr(param) ) f.action = _webapp + "/GWController?"+param;
	if( !isNullStr(target) ) f.target=target
	f.submit();
}

/**
* 프레임웍을 이용하는 Form객체를 찾아 리턴한다.
* 기준객체는 <input type='hidden' name='facade'>의 상위객체 FORM
*/
function findFormElement() {
	var facadeElement = document.all("facade" );
	if( facadeElement == null || facadeElement == "undefined" ) {
		alert("facade element not found!");
		return null;
	}
	return facadeElement.parentElement;
}

/**
 * 프린터 도움말 확인
 */
function showPrintHelp() {
    var url = _webapp + "/common/printHelp.jsp";
    var returnValue = getOpenModalPopup("print.help.title", url, null, 510, 270, "auto");
	return returnValue;
}

/**
 * 진행창 Open
 * @param  title : 출력될 제목
 * @param  message : 출력될 메세지
 */
var thisProgressModal = null;
function openProgress(title, message){
    var pregresUri  = _webapp + "/GWController?nextpage=/common/progressWindow.jsp";
    if (title != null)
    {
        pregresUri += "&title=" + encodeURI(title);
    }
    if (message != null)
    {
        pregresUri += "&message=" + encodeURI(message);
    }
    var strOption  = "dialogWidth:300px;dialogHeight:280px;";
    strOption += "center:on;scroll:off;status:off;resizable:off;help:off;unadorned:yes";
    try {
	    thisProgressModal = showModelessDialog (pregresUri, "", strOption);
	  }catch(e){
	  	//alert('팝업 차단을 해제 해주세요!');
	  }


}

function openBigProgress(title, message){
    var pregresUri  = _webapp + "/GWController?nextpage=/common/progressWindow.jsp";
    if (title != null)
    {
        pregresUri += "&title=" + encodeURI(title);
    }
    if (message != null)
    {
        pregresUri += "&message=" + encodeURI(message);
    }
    var h = screen.height;
    var w = screen.width;
    var strOption  = "dialogWidth:"+ w +"px;dialogHeight:"+ h +"px;";
    strOption += "center:on;scroll:off;status:off;resizable:off;help:off;unadorned:yes";
    try {
	    thisProgressModal = showModelessDialog (pregresUri, "", strOption);
	  }catch(e){
	  	//alert('팝업 차단을 해제 해주세요!');
	  }
}

/**
 * 진행창 Close
 */
function closeProgress( index ) {
    if(thisProgressModal != null) {
        thisProgressModal.close();
        thisProgressModal = null;
         /** 2006.11.29 최태영
		    * 프로그래스 창을 닫고서 window의 focus를 잃어버리는 문제..
		    */
		    window.focus();
    } else {
		interval = 1000;
		if (index == null) {
            index = 0;
		}
        index++;
		if (index > 10) { 
			return; 
		} 
        setTimeout("closeProgress(" + index + ")", interval); 
    }
    
}

/*
* Modal팝업
*/
function getOpenModalPopup(popTitleKey, urlStr, param, iWidth, iHeight, bScroll) {

	var rtnVal;
    var arrArg = new Array(2);
		
	arrArg [0] = urlStr;
	arrArg [1] = param;

	rtnVal = window.showModalDialog(_webapp+"/common/modalDialogMain.jsp?titleKey="+popTitleKey+"&scroll="+bScroll, arrArg, "dialogHeight:"+iHeight+"px;dialogWidth:"+iWidth+"px;help:No;resizable:Yes;status:no;scroll:no;center:yes");
	//alert('rtnVal:'+rtnVal);
	try {
		if( rtnVal == 'RE-LOGIN' ) {
			top.location.href = _weburl;
		}
		//alert(rtnVal)
		if( rtnVal.length > 0 && rtnVal.indexOf("\13\14") >= 0) {
			showOpenErrWin(rtnVal.split("\13\14")[1]);
			return null;
		}
	}catch (Exception){
	}

    return rtnVal;
}

/*
* Modal팝업 - is not center
*/
function getOpenModalPopupNotCenter(popTitleKey, urlStr, param, iWidth, iHeight, iTop, iLeft, bScroll) {

	var rtnVal;
    var arrArg = new Array(2);
		
	arrArg [0] = urlStr;
	arrArg [1] = param;

	rtnVal = window.showModalDialog(_webapp+"/common/modalDialogMain.jsp?titleKey="+popTitleKey+"&scroll="+bScroll, arrArg, "dialogHeight:"+iHeight+"px;dialogWidth:"+iWidth+"px;dialogTop:"+iTop+"px;dialogLeft:"+iLeft+"px;help:No;resizable:Yes;status:no;scroll:no;center:no");
	//alert('rtnVal:'+rtnVal);
	try {
		if( rtnVal == 'RE-LOGIN' ) {
			top.location.href = _weburl;
		}
		//alert(rtnVal)
		if( rtnVal.length > 0 && rtnVal.indexOf("\13\14") >= 0) {
			showOpenErrWin(rtnVal.split("\13\14")[1]);
			return null;
		}
	}catch (Exception){
	}

    return rtnVal;
}

function getOpenModalessPopup(popTitleKey, urlStr, param, iWidth, iHeight, bScroll) {

	var rtnVal;
    var arrArg = new Array(2);
		
	arrArg [0] = urlStr;
	arrArg [1] = param;
	
	if(thisProgressModal != null) {
        thisProgressModal.close();
  }
	thisProgressModal = showModelessDialog(_webapp+"/common/modalDialogMain.jsp?titleKey="+popTitleKey+"&scroll="+bScroll, arrArg, "dialogHeight:"+iHeight+"px;dialogWidth:"+iWidth+"px;help:No;resizable:Yes;status:no;scroll:no;center:yes;dialogHide:yes;");
	/*try {
		if( rtnVal.length > 0 && rtnVal.indexOf("\13\14") >= 0) {
			showOpenErrWin(rtnVal.split("\13\14")[1]);
			return null;
		}
	}catch (Exception){
	}

    return rtnVal;
    */
	return thisProgressModal;
    
}

function _openOrgPop(orgPop, oSelect, companyId ) {
	var compId = _companyId;
	if( companyId != 'undefined' && companyId != null ) {
		compId = companyId;
	}
	var params = orgPop.getParams()+"&companyId="+compId;
	var urlStr = _webapp + "/GWController?nextpage=/common/pop/orgPop.jsp"+params
	var titleKey = "org.pop.dept"
	var param  = oSelect;
	var width  = 870
	var height = 640
	if( orgPop.getMultiSelect() == false ) {
		width  = 600
		if( orgPop.getUserShow() == false ) {
			height = 580
		}
	}
	if( orgPop.getSelectPaneJsp() == "/common/pop/mailRight.jsp" ) {
		width  = 900
	}
	
	var rtnVal = getOpenModalPopup(titleKey, urlStr, param, width, height, "no");
	
	return rtnVal
}

/**
 *
 */
function openViewDialog ( dialogId , htmlSrc )
{
	var dialog = window.open ("", dialogId, "toolbar=no,resizable=yes,scrollbars=yes");
	dialog.document.write(htmlSrc);
}

/*
* 파일다운로드 
* @param downMode inline or attachment
* @param volumeId VolumeManager의 volumeId
* @param filePath 볼륨아이디의 Location 다음부터의 경로(임시파일의 경우 fullPath)
* @param saveFileName 저장파일명
*/
function fileDownLoad(downMode , volumeId, filePath , saveFileName, param) {
    if ( param == null ) {
        param = "";
    }
    //alert(saveFileName)
    if( document.all._ifrHidden ){}
    else {
        var oIframe = document.createElement("<IFRAME ID='_ifrHidden' WIDTH=0 HEIGHT=0></IFRAME>")
        document.body.insertBefore(oIframe);
    }
	if( downMode == "attachment" ) {
		_ifrHidden.location.replace(_webapp + "/DownController?down_filepath="+filePath+"&volumeId="+volumeId+"&down_filename="+encodeURI(saveFileName) + param);
	}
	else{
        var win = window.open(_webapp + "/GWController?nextpage=/common/fileDownload.jsp&down_filepath="+filePath+"&down_mode=inline&volumeId="+volumeId+"&down_filename="+encodeURI(saveFileName) + param, "", "location=no,menubar=yes,directories=no,status=no,scrollbars=1,resizable=yes");
	}
}


/**
* 에러 정보 팝업
* @param goUrl url정보
*/
function showOpenErrWin(goUrl) {
	var vWidth = 600
	var vHeight = 250
	var vTop = (screen.height - vHeight) / 2;
	var vLeft = (screen.width - vWidth) / 2;
	var errPop = window.open(goUrl, "_errorWin_", "width="+vWidth+",height="+vHeight+",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=0,resizable=0,left="+vLeft+",top="+vTop);
	errPop.focus();
}
//BOX OPEN
function initbox(id ,  msg ){	
    var oDiv = document.getElementById(id);
    oDiv.innerHTML = "<br>"+msg;
	crossobj= oDiv.style;
	crossobj.top = ((screen.height/2)/2) + 5;
	crossobj.left = ((screen.width/2)-200)/2
	crossobj.backgroundPosition = "top center";
	crossobj.display="inline"
}
//BOX CLOSE
function closebox(){
	crossobj.display="none";
}

/**
  * [일반팝업윈도우]
  * popup 윈도를 화면 중앙에 표시한다.
  * @param href - 윈도에 표시할 source
  * @param winName - window name
  * @param width - width of window
  * @param height - height of window
  * @param standard - 표준 윈도 여부 (true, false)
  * @return 오픈된 윈도 핸들러
  */
function openPopupWindowInCenter(href, winName, width, height, standard)
{
	var pop = null;
	var vTop = (screen.height - height) / 2;
	var vLeft = (screen.width - width) / 2;

	var sFeatures = "";

	// 표준 여부에 따라 feature의 속성이 다르다.
	// 표준인 경우에는 모든 feature가 no
	// 표준이 아닌 경우에는 scrollbar와 resize가 가능하다.
	if (standard)
	{
		sFeatures = 'width='+width+',height='+height+',top='+vTop+',left='+vLeft+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no'
	}
	else
	{
		sFeatures = 'width='+width+',height='+height+',top='+vTop+',left='+vLeft+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes'
	}

	pop = window.open(href, winName, sFeatures);

	return pop;
}

/*
* 엑셀파일다운로드 호출
* @param beanId FACADE
* @param command FACADE Method
* @param saveFileName 저장파일명
* @param param 기타파라미터
*/
function excelFileDownLoad(facade, command, saveFileName , param ) {
    if( document.all._ifrHidden ) {
    }
    else {
        var oIframe = document.createElement("<IFRAME ID='_ifrHidden' WIDTH=0 HEIGHT=0></IFRAME>")
        document.body.insertBefore(oIframe);
    }
	_ifrHidden.location = _webapp + "/ExcelDownController?facade="+facade+"&command="+command + 
                              "&nextpage=/groupware/modules/common/exceldown.jsp&down_filename="+encodeURI(saveFileName)+"&param="+param;
}

/**
* 달력팝업
* @param dtObject  dateObject 
* @param dtFormat  String : (default:"%Y-%m-%d") 
*                 -★ 반드시 칼렌더.js에 지정되어 있는 포맷을 사용할 것!
*/
function _openCalendarPopup(dtObject,dtFormat) {
    var urlStr   = _webapp+"/GWController?&nextpage=/common/pop/calendarPopup.jsp&openerDT="+encodeURI(dtObject.value)+"&dtFormat="+encodeURI(dtFormat);
    var titleKey = "calendar.pop.title"
    var param    = dtObject;
    var rtnVal 	 = getOpenModalPopup(titleKey, urlStr, param, 232, 215, "no");
    return rtnVal;
}


/////////////////////////////////////////////////////////////////////////////////////////
//
// 사용자 정의 JavaScript Class Type
//
/////////////////////////////////////////////////////////////////////////////////////////
/**
 *	Item 형태의 정보를 가지는 자바스크립트 클래스타입을 생성  
 *
 * @constructor 
 */
function ItemType()
{	
	this.item           = new Array();
	this.delimiter      = '\27';
    this.add			= _ITEM_add;
    this.getItemList    = _ITEM_getItemList;
	return this;
}

/**
 * item 에  value 값 추가
 *
 * @param value  
 */
function _ITEM_add( value )
{
	this.item[this.item.length] = value;
}

/**
 * item의 리스트를 리턴합니다.
 *
 * @param value  
 */
function _ITEM_getItemList(  )
{
    var list = "";
    for (var i = 0; i < this.item.length; i++ )
    {
        if (i > 0 )
            list += this.delimiter;
        list += this.item[i] ;
    }
    return list;
}


/**
 *	Array 형태의 정보를 가지는 자바스크립트 클래스타입을 생성  
 *
 * @constructor 
 */
function ArrayType()
{	
	this.array           = new Array();
	this.delimiter      = '\14';
    this.add			= _ARRAY_add;
    this.addItem		= _ARRAY_addItem;
    this.getArrayList   = _ARRAY_getArrayList;
	return this;
}

/**
 * array 에  value 값 추가
 *
 * @param value  
 */
function _ARRAY_add( value )
{
	this.array[this.array.length] = value;
}

/**
 * array 에  Item 추가
 *
 * @param item 
 */
function _ARRAY_addItem( item )
{
	this.array[this.array.length] = item.getItemList();
}

/**
 * array의 리스트를 리턴합니다.
 *
 * @param value  
 */
function _ARRAY_getArrayList( )
{
    var list = "";
    for (var i = 0; i < this.array.length; i++ )
    {
        if (i > 0 )
            list += this.delimiter;
        list += this.array[i] ;
    }
    return list;
}

/*
* File 객체
*/
function File(path, name, size) {
	this.path = path
	this.name = name
	this.size = size

	this.getName = getName
	this.getSize = getSize
	this.getPath = getPath
}
function getName() {
	return this.name
}
function getPath() {
	return this.path
}
function getSize() {
	return this.size
}

/**
* 로케일 변경시 관련 필드 표시
*/
function localeFieldDisplay(oSelect,fieldName) {
	var locale = oSelect.value;
	
	var len = oSelect.length
	for(var i = 0 ; i < len; i++ ) {
		var option = oSelect.options[i]
		if( option.defaultSelected ) {
			var obj = document.getElementById(fieldName+"_"+oSelect.options[i].value);
			obj.style.display='none'
		}
	}
	
	var obj = document.getElementById(fieldName+"_"+locale);
	obj.style.display='block'
	oSelect.options[oSelect.selectedIndex].defaultSelected=true
}

/**************************************************************/
/*                [트리데이터 객체]                              */
/**************************************************************/
function TreeData(id,treeId,upTreeId,name,depth,useYn,checkValues,disabled) {
	if( checkValues.indexOf('\28') == 0 ) {
		checkValues = checkValues.substring(2);
		checkValues = stringReplace(checkValues,"\27"," ");
	}
	this.id = id  //Unique Id
	this.treeId = treeId
	this.upTreeId = upTreeId
	this.name = name
	this.depth = depth
	this.useYn = useYn
	this.checkValues = checkValues
	this.disabled = disabled
	
	this.getId = treeDataGetId
	this.getTreeId = treeDataGetTreeId
	this.getUpTreeId = treeDataGetUpTreeId
	this.getName = treeDataGetName
	this.getDepth = treeDataGetDepth
	this.getUseYn = treeDataGetUseYn
	this.getCheckValues = treeDataGetCheckValues
	this.getDisabled = treeDataGetDisabled
}

function treeDataGetId() {
	return this.id
}
function treeDataGetTreeId() {
	return this.treeId
}
function treeDataGetUpTreeId() {
	return this.upTreeId
}
function treeDataGetName() {
	return this.name
}
function treeDataGetDepth() {
	return this.depth
}
function treeDataGetUseYn() {
	return this.useYn
}
function treeDataGetCheckValues() {
	return this.checkValues
}
function treeDataGetDisabled() {
	return this.disabled
}
///////////////////////////////////TreeData객체끝!//////////////////
/**
* IFrame Resize(스크롤 안생기게)
*/
function adjustIFrameSize(id, minHeight) {
  var myIframe = document.getElementById(id);
  //alert('myIframe:'+myIframe);
  if (myIframe) {
      if (myIframe.contentDocument && myIframe.contentDocument.body.offsetHeight) {
          // W3C DOM (and Mozilla) syntax
          myIframe.height = myIframe.contentDocument.body.offsetHeight;    
      } else if (myIframe.Document && myIframe.Document.body.scrollHeight) {
          // IE DOM syntax
          myIframe.height = myIframe.Document.body.scrollHeight;
      }
      if( myIframe.height < minHeight ) {
      	myIframe.height = minHeight;
      }
      
  }
}
/**
* FORM내에서 srch로 시작하는 객체를 찾아 Param을 생성한다.
*/
function getSrchParam(form) {
	var param = "";
	if( form == null ) return
	var elements = form.elements;
	for(var i = 0; i < elements.length; i++ ) {
		if( elements[i].name.indexOf("srch") == 0) {
			param += "&"+elements[i].name+"="+elements[i].value
		}
	}
	return param;
	
}


/**
* 사용자 상세정보 팝업
* @param userid UserId
*/
function userInfoPop( userId ) {
  var urlStr  = _webapp+"/GWController?facade=ACLUserFacade&command=getUserInfo2&nextpage=/common/userInfoPop.jsp&userId="+userId;
	var title = "userinfo.title";
	var param = null;
	var rtnVal		= getOpenModalPopup(title, urlStr, param, 580, 520, "auto");

}