﻿/*
 * JavaScript String 객체에 메소드 추가
 * 기존메서드(anchor(),big(),blink(),bold(),charAt(),charCodeAt(),concat(),fixed(),fontcolor(),
 * fontsize(),fromCharCode(),indexOf(),italics(),lastIndexOf(),link(),match(),replace(),search(),
 * slice(),small(),split(),strike(),sub(),substr(),substring(),sup(),toLowerCase(),toUpperCase(),toSource(),valueOf()
 */


var JyArr = {};
JyArr.PhoneNoDesc =  new Array('선택','031','032','033','041','042','043','051','052','053','054','055','061','062','063','064','070');
JyArr.PhoneNoVal =  new Array('','031','032','033','041','042','043','051','052','053','054','055','061','062','063','064','070');
JyArr.MobileNoDesc =  new Array('선택','010','011','016','017','018','019');
JyArr.MobileNoVal =  new Array('','010','011','016','017','018','019');
JyArr.BankDesc =  new Array('선택','하나은행','국민은행','신한은행','제일은행','농협','씨티은행','기업은행','산업은행');

/*
author : 이주용
version : 09.03.31
comment : 문자열의 null 값 체크
*/
String.prototype.isEmpty  = function(){
	return ( ( this == null ) || ( this.trim().length == 0 ))
};


/*
author : 이주용
version : 09.03.31
comment : 문자열의 왼쪽을 기준으로 length만큼 char로 치환
*/
String.prototype.padLeft = function ( length, char ){	
	if ( ( (! length ) || ( length < 1 ) ) || ( this.isEmpty() ) )
		return this;

	var padding = '                                                                                                    ';

	if ( char )
	{	
		padding = padding.replace( / /g, char );
	}
	return ( padding.substr ( 0, length ) + this );
};

/*
 * author  : 이주용
 * version : 09.03.20
 * comment : 문자열에서 공백을 제거한다. 
 */
String.prototype.trim = function(){
	return this.replace(/^\s*|\s*$/gi, '');
};

/*
 * author  : 이주용
 * version : 09.03.20
 * comment : 문자열을 추가한다.
 */
String.prototype.append = function(str){
	return this + str;
};


/*
 * author  : 이주용
 * version : 09.03.23
 * comment : 문자열을 추가하고 줄내림(\n)을 추가한다. 
 */
String.prototype.appendLine = function(str){

	if(!str.isEmpty())
		return this + str + "\n";
	return this;
};

/*
 * author : 이주용
 * version : 09.03.25
 * comment : 대소문자를 구분하지 않고 특정 문자열의 위치 검색(indexOf 와 비교)
 */
String.prototype.searchString = function(str){
	var thisTemp = this.toLowerCase();
	var strTemp = str.toLowerCase();
	
	return thisTemp.indexOf(strTemp);
};

String.prototype.isContain = function(str){
	return this.searchString(str) != -1;
};


/*
 * author : 이주용
 * version : 09.03.25
 * comment : 문자열에서 특정 문자(str)이 반복되어 나오는 횟수반환
 */
String.prototype.countString = function(str){
	var count = 0;
	var pos = this.indexOf(str, 0);
	
	while(pos != -1){
		count++;
		pos = this.indexOf(str, pos+1);
	}	
	return count;
};

/*
 * author : 이주용
 * version : 09.03.25
 * comment : 경로를 가지는 문자열에서 확장자 부분을 반환한다.
 */
String.prototype.getExtension = function(){
	var pos = this.lastIndexOf(".");
	
	return this.substring(pos+1);
};

/*
 * author : 이주용
 * version : 09.03.25
 * comment : 파일명을 반환한다.
 */
String.prototype.getFileName = function(){
	var pos = this.lastIndexOf("/");
	return this.substring(pos+1);
};

String.prototype.isForbid = function(forbiden){
	// 모든 태그 제거
	var source = this.replace(/(<[//]?[^>]+>)/gi,'');		
	var pattern = eval('/' + forbiden + '/gi');
	
	return pattern.test(source);
};

/*
 * author : 이주용
 * version : 09.06.15
 * comment : 숫자만 반환한다.
 */
String.prototype.num = function(){
	return (this.trim().replace(/[^0-9]/g,""));
};

Array.prototype.remove = function(index)
{
	var temp = new Array();
	var i = this.length;
	
	while(i > index){
		var item = this.pop();
		temp.push(item);
		i--;
	}
	
	for(var i=temp.length-2; i >= 0;i--){
		this.push(temp[i]);
	}
};

function fn_Next(current,next,length)
{
	if(typeof(current) != "object")
		current = $(current);
	if(typeof(next) != "object")
		next = $(next);
			
	if(current.value.trim().length == length)
		next.focus();
}


function processKey(evt) 
{   
   
    var evt = event;
    	
	var node = (evt.target != null) ? evt.target : ((evt.srcElement != null) ? evt.srcElement : null);
		
    if( (event.ctrlKey == true && (event.keyCode == 78 || event.keyCode == 82)) || (event.keyCode >= 112 && event.keyCode <= 123) || (event.keyCode == 8 && node.type!="text" && node.type != "textarea" && node.type != "password")) 
    {   
		event.keyCode = 0; 
		event.cancelBubble = true; 
		event.returnValue = false; 
    }
    
    if ((evt.keyCode == 13) && ((node.type=="text") || (node.type=="password")) ) {return false;}
			
	if ((evt.keyCode == 13) && node.type == null)
	{
		event.returnValue = false;
	}
}
document.onkeydown = processKey; 


function OnUploadCompleted(errorNumber, fileUrl, fileName, customMsg, callBack, thumbnail){

	if(errorNumber != 0 && errorNumber != 201)
	{
		fileUrl = fileName = thumbnail = "";
	}
		
	switch ( errorNumber )
	{
		case 0 :	// No errors
			//alert( '이미지가 업로드 되었습니다.' ) ;
			break ;
		case 1 :	// Custom error
			alert( customMsg ) ;
			break;
		case 101 :	// Custom warning
			alert( customMsg ) ;
			break ;
		case 201 :
			//alert( '서버에 동일한 파일명이 존재합니다. 파일명은 다음으로 변경됩니다. "' + fileName + '"' ) ;
			break ;
		case 202 :
			alert( '이미지 파일만 업로드 가능합니다.' ) ;
			break;
		case 203 :
			alert( "인터넷 옵션의 보안설정을 보통으로 설정하세요." ) ;
			break;
		default :
			alert( '업로드 중 오류가 발생했습니다. 오류번호 : ' + errorNumber ) ;
			break;
	}
			
	if(typeof(callBack) == "string")
	{
		var o = eval(callBack);
		if(typeof(o) == "function")
		{
			var oParam = {};
						
			oParam.errorNumber = errorNumber;
			oParam.fileUrl = fileUrl;
			oParam.fileName = fileName;
			oParam.customMsg = customMsg;
			oParam.thumbnail = "/UserFiles/thumbnail/57X57/"+thumbnail;
			o(oParam);
		}
	}
}


function sleep(naptime){
	naptime = naptime * 1000;
      var sleeping = true;
      var now = new Date();
      var alarm;
      var startingMSeconds = now.getTime();
      
      while(sleeping){
         alarm = new Date();
         alarmMSeconds = alarm.getTime();
         if(alarmMSeconds - startingMSeconds > naptime){ sleeping = false; }
      }      
      alert("Wakeup!");
}

function FlashmEmbed(url, width, height, retFlag,id)
{
	
    var contents = "";
    var flashName = "afct_Player";
    
    if(id && typeof(id) == "string"){
    	flashName = id;
    } 
    
    contents += "<object width=\""+ width +"\" height=\""+ height +"\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0\" id=\""+flashName+"\">";
    contents += "	<param name=\"movie\" value=\""+url+"\" />";
    contents += "	<param name=\"allowScriptAccess\" value=\"always\" />";
    contents += "   <param name=\"allowFullScreen\" value=\"true\" />";
    contents += "   <param name=\"wmode\" value=\"transparent\" />";
    contents += "	<embed src=\""+url+"\" width=\""+ width +"\" height=\""+ height +"\" quality=\"high\" allowFullScreen=\"true\"  pluginspage=\"http://www.macromedia.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" name=\""+flashName+"\" allowScriptAccess=\"always\" wmode=\"transparent\"></embed>";
    contents += "</object>";
  
  	if(typeof(retFlag) == "undefined" || retFlag == false)
    	document.write(contents);
    else if(retFlag == true)
    {
    	return contents;
    }    	
}

function fn_getWantSizeImageUrl(file,size){
	var newFile = "";
	var ext = file.substring(file.indexOf('.')+1);
	
	if(ext.toLowerCase() != "gif")
	{		
		newFile = '/UserFiles/thumbnail/' + size + '/' + file.substring(file.lastIndexOf('/')+1);
	}
	else
	{
		newFile = '/UserFiles/Image/' + file.substring(file.lastIndexOf('/')+1);
	}
	return newFile;
}

//함수명: fn_checkLength(obj, len, str)
//설  명: 문자열의 길이에 따른 처리 함수
//인  자: obj : 해당 객체, len : 지정길이, str: 항목명
//--------------------------------------------------------------------------------------------
//사용법:
//     <textarea name="ta" rows="4" cols=20 class="td_input" style="width:100%"  onblur= "fn_checkLength(this, 100, '항목')" >
//			</textarea>
//--------------------------------------------------------------------------------------------
function fn_checkLength(obj, len, str)
{
  obj.value = obj.value.trim();
  complen = fn_checkByte(obj.value);
  if ( complen > len)
  {
      alert(str + len + 'Byte를 초과할수 없습니다. 현재 ' + complen + 'Byte입니다.');
      obj.focus();
      return false;
  }
  return true;
}

//함수명: fn_checkByte(str)
//설  명: 지정된 객체의 문자열의 길이를 계산하는 부분
//인  자: str : 문자
function fn_checkByte(str)
{
	var byteLength= 0;
	for(var inx=0; inx < str.length; inx++)
	{
		var oneChar = escape(str.charAt(inx));
		if( oneChar.length == 1 )
			byteLength ++;
		else if(oneChar.indexOf("%u") != -1)
			byteLength += 2;
		else if(oneChar.indexOf("%") != -1)
			byteLength += oneChar.length/3;
	}
	return byteLength;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function fnBindSelectByItems(ctl,arrDesc,arrValue,selectVal){
    var obj = ctl;
    
    if( typeof(ctl) == "string" ){
        obj = $(ctl);
    }
    
    if(obj == null || typeof(obj) != 'object' || obj.tagName.toLowerCase() != "select")
        return;
    
    obj.options.length = 0;
    
    for(i=0; i < arrDesc.length; i++)
    {
        if(arrValue != null)
            obj.options[obj.options.length] = new Option(arrDesc[i],arrValue[i]);
        else
            obj.options[obj.options.length] = new Option(arrDesc[i]);
    }
    
    if(selectVal != null)
        obj.value = selectVal.trim();
}

function fnMove(url,bid){
    var frm = document.frmCommon;    
    frm.bid.value = bid;
    frm.action = url;
    //frm.method = "post";
    frm.submit();
}

/*
	* author : 이주용
	* version : 09.09.04
	* comment : cellIdx 값을 기준으로 수직으로 merge
	param
	table : 리스트 객체, 또는 ID
	startRowIdx : 머지를 실행할 row의 Index
	cellIdx : 머지 대상 cell Index
	*/
function mergeVerticalCell(table, startRowIdx, cellIdx){

	if(typeof(table) == 'String')
		table = document.getElementById(table);

	var rows = table.getElementsByTagName('tr');
	var numRows = rows.length;
	var numRowSpan = 1;
	var currentRow = null;
	var currentCell = null;
	var currentCellData = null;
	var nextRow = null;
	var nextCell = null;
	var nextCellData = null;

	for(var i = startRowIdx; i < (numRows-1); i++){
		if(numRowSpan <= 1){
			currentRow = table.getElementsByTagName('tr')[i];
			currentCell = currentRow.getElementsByTagName('td')[cellIdx];
			currentCellData = getCellValue(currentCell);
		}

		if(i < numRows - 1){
			if(table.getElementsByTagName('tr')[i+1]){
				nextRow = table.getElementsByTagName('tr')[i+1];
				nextCell = nextRow.getElementsByTagName('td')[cellIdx];
				nextCellData = getCellValue(nextCell);
			}

			if(currentCellData == nextCellData){
				numRowSpan += 1;
				currentCell.rowSpan = numRowSpan;
				nextCell.style.display = 'none';
			}else{
				numRowSpan = 1;
			}
		}
	}
}

/*
	* author : 이주용
	* version : 09.09.04
	* comment : basicCellIdx 기준으로 머지되어 있는 리스트에서 특정 cellIdx의 cell을 다시 merge한다.
	param
	table : 리스트 객체, 또는 ID
	startRowIdx : 머지를 실행할 row의 Index
	basicCellIdx : 기준 머지 cell의 Index
	cellIdx : 머지 대상 cell Index
	*/
function mergeDependentVerticalCell(table, startRowIdx, basicCellIdx, cellIdx){

	if(typeof(table) == 'String')
		table = document.getElementById(table);
		
	var rows = table.getElementsByTagName('tr');
	var numRows = rows.length;
	var numRowSpan = 1;
	var countLoopInBasicMerge = 1;
	var currentRow = null;
	var currentCell = null;
	var currentCellData = null;
	var nextRow = null;
	var nextCell = null;
	var nextCellData = null;
	var basicRowSpan = null;

	for(var i = startRowIdx; i < (numRows - 1); i++){

		if(i == startRowIdx || (countLoopInBasicMerge == 1)){
			basicRowSpan = table.getElementsByTagName('tr')[i].getElementsByTagName('td')[basicCellIdx].rowSpan;
		}
		if(numRowSpan <= 1){
			currentRow = table.getElementsByTagName('tr')[i];
			currentCell = currentRow.getElementsByTagName('td')[cellIdx];
			currentCellData = getCellValue(currentCell);
		}

		if(i < numRows - 1){
			if(countLoopInBasicMerge < basicRowSpan)
			{
				if(table.getElementsByTagName('tr')[i+1]){
					nextRow = table.getElementsByTagName('tr')[i+1];
					nextCell = nextRow.getElementsByTagName('td')[cellIdx];
					nextCellData = getCellValue(nextCell);

					if(currentCellData == nextCellData){
						numRowSpan += 1;
						currentCell.rowSpan = numRowSpan;
						nextCell.style.display = 'none';
					}
					else
					{
						numRowSpan = 1;
					}
				}

				countLoopInBasicMerge++;
			}
			else{
				countLoopInBasicMerge = 1;
				numRowSpan = 1;
			}
		}
	}
}

/*
* author : 이주용
* version : 09.09.04
* comment : cell 값 가져오기
*/
function getCellValue(cell){
	var cellText = '';
	
	if(typeof(cell) == 'undefined')
		return cellText;

	if( typeof(cell.tagName) == 'undefined' ){
		cellText = cell.data;
	}
	else{
		cellText = cell.innerText;
	}
	return cellText;
}

/*
* author : 이주용
* version : 09.09.04
* comment : node의 이전 element node를 가져온다.
*/
function getPreviousElementNode(node)
{       
	while(node.previousSibling){
		node = node.previousSibling;
		
		if(node.nodeType == 1){
			break;
		}
	}
	return node;
}