﻿// JScript File for TextArea
// Keep user from entering more than maxLength characters
// Original Source는 http://www.codeproject.com/KB/aspnet/Textarea_Length_Validator.aspx?msg=1408846
// 서 가져왔으나,
// 한국에서 SMS 등에서 사용하는 떠돌아 다니는 소스로 수정함. by 석경.

function doKeypress_notworkOn2ByteCharacter(control){
    maxLength = control.attributes["maxLength"].value;
    value = control.value;
     if(maxLength && value.length > maxLength-1){
          event.returnValue = false;
          maxLength = parseInt(maxLength);
     }
}
// Cancel default behavior
function doBeforePaste(control){
    maxLength = control.attributes["maxLength"].value;
     if(maxLength)
     {
          event.returnValue = false;
     }
}
// Cancel default behavior and create a new paste routine
function doPaste(control){
    maxLength = control.attributes["maxLength"].value;
    value = control.value;
     if(maxLength){
          event.returnValue = false;
          maxLength = parseInt(maxLength);
          var oTR = control.document.selection.createRange();
          var iInsertLength = maxLength - value.length + oTR.text.length;
          var sData = window.clipboardData.getData("Text").substr(0,iInsertLength);
          oTR.text = sData;
     }
}

function doKeypress(control){
	var str,msg;
	var len = 0;
	var temp;
	var count = 0;
	var maxLength;
	
	maxLength = control.attributes["maxLength"].value;
	
	msg = control.value;
	str = new String(msg);
	len = str.length;

	for (k=0 ; k<len ; k++){
		temp = str.charAt(k);

		if (escape(temp).length > 4) {
			count += 2;
		}
		else if (temp == '\r' && str.charAt(k+1) == '\n') { // \r\n일 경우
			count += 2;
		}
		else if (temp != '\n') {
			count++;
		}
	}
	// alert(count);
	// control.byte.value = count;
	
 	if(count > maxLength) {
		control.blur();
		control.focus();		
		alert("이 항목은 "+maxLength+"Byte(한글" + maxLength/2 +"자) 만 입력 가능합니다."); 
		CutChar(control,maxLength);
	}	
}

function CutChar(control,maxLength) {
	var str,msg;
	var len=0;
	var temp;
	var count;

	count = 0;
	 
	msg = control.value;
	str = new String(msg);
	len = str.length;

	for(k=0 ; k<len ; k++) {
		temp = str.charAt(k);
		
		if(escape(temp).length > 4) {
			count += 2;
		}
		else if (temp == '\r' && str.charAt(k+1) == '\n') { // \r\n일 경우
			count += 2;
		}		
		else if(temp != '\n') {
			count++;
		}
		if(count > maxLength) {
			str = str.substring(0,k);
			break;
		}
	}
	control.value = str;
	CheckMsg(str);
}


