/*     
	02/04/2009
	KLIB Javascript Library based jquery
	Copyright (C) 2009 Keon-Jun Lee(ch4feel@naver.com)

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

try {
	jQuery.jquery;
} 
catch (e) {
	alert('KLIB have to use jQury.js');
}

/**
 * $k 객체는 클립라이브러리에 대한 정보와 유틸리티 함수를 제공한다.
 */
var $k = { 

	// KLIB version
	klib : '0.2.6',
	
	// Get Array Location
	index: function(arr, str){
  	for (i = 0; i < arr.length; i++) {
  		if (arr[i] == str) 
  			return i;
  	}
		return -1;
  },
	
	// Get ClassName Variable
	getClassVar : function(str, strClassName) {
		var arrClass = str.split(' ');
		var i;
		var regex = new RegExp('^'+strClassName, 'g');
		for (i=0; i < arrClass.length; i++)
			if(regex.test(arrClass[i])) {
				if(arrClass[i].replace(strClassName,'').length != 0)
					return arrClass[i].replace(strClassName,'');
			}
		
		return null;
	},
	
	// get Cookie
	getCookie : function(name){
		var nameOfCookie = name + '=';
		var x = 0;
		while ( x <= document.cookie.length ) {
			var y = (x+nameOfCookie.length);
			if ( document.cookie.substring( x, y ) == nameOfCookie ) {
				if ( (endOfCookie=document.cookie.indexOf( ';', y )) == -1 )
				endOfCookie = document.cookie.length;
				return unescape( document.cookie.substring( y, endOfCookie ) );
			}
			x = document.cookie.indexOf(' ', x ) + 1;
			if ( x == 0 )
				break;
		}
		return '';
	},
	
	// set Cookie
	setCookie : function(name, value, expiredays){
		var todayDate = new Date();
		var domainDocument = window.location.href;
		todayDate.setDate( todayDate.getDate() + expiredays );
		
		domainDocument = domainDocument.replace(/(http(s)?:\/\/)?/gi, '');
		domainDocument = domainDocument.split('/')[0];
		
		document.cookie = name + '=' + escape( value ) + '; path=/; domain='+domainDocument+'; expires=' + todayDate.toGMTString() + ';';
		
	}
}

jQuery.extend ({klib: $k.klib});
jQuery.fn.extend ({klib : $k.klib});

/**
 * 문자의 좌, 우측 공백을 제거한 문자열을 리턴한다.
 * @return {string}
 */
String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/g, '');
}


/**
 * 문자의 좌측 공백을 제거한 문자열을 리턴한다.
 * @return {string}
 */
String.prototype.ltrim = function() {
	return this.replace(/(^\s*)/, '');
}


/**
 * 문자의 우측 공백을 제거한 문자열을 리턴한다.
 * @return {string}
 */
String.prototype.rtrim = function() {
	return this.replace(/(\s*$)/, '');
}


/**
 * 문자열의 바이트수를 정수로 리턴한다.
 * @return {number}
 */
String.prototype.bytes = function() {
	var cnt = 0;
	for (var i = 0; i < this.length; i++) {
		if (this.charCodeAt(i) > 127) 
			cnt += 2;
		else
			cnt++;
	}
	return cnt;
}


/**
 * 숫자로된 문자열을 정수형으로 변환하여 리턴한다.
 * @return {number}
 */
String.prototype.parseInt = function() {
	if(!isNaN(this)) {
		return parseInt(this);
	} else {
		return null;
	}
}


/**
 * 숫자만 가져 오기
 * @return {string}
 */
String.prototype.getNumber = function() {
	return this.trim().replace(/[^0-9]/g, '');
}


/**
 * 숫자로 된 문자열에 3자리마다 , 를 찍어서 리턴한다.
 * @return {string}
 */
String.prototype.money = function() {
	var num = this.trim();
	if (num)
  	while ((/(-?[0-9]+)([0-9]{3})/).test(num)) {
  		num = num.replace((/(-?[0-9]+)([0-9]{3})/), '$1,$2');
  	}
  	return num;
}


/**
 * 숫자의 자리수에 맞도록 0을 채워 리턴한다.
 * @param {number} Number
 * @return {number}
 */
String.prototype.digits = function(iCnt) {
	var digit = '';
	if (this.length < iCnt) {
		for(var i = 0; i < iCnt - this.length; i++) {
			digit += '0';
		}
	}
	return digit + this;
}


/**
 * 문자열에 HTML 태그를 삭제한 후 순수 문자열만 리턴한다.
 * @return {string}
 */
String.prototype.stripTags = function() {
	return this.replace(/<\/?[^>]+>/gi, '');
}


/**
 * HTML 태그를 escape한 문자열을 리턴한다.
 * @return {string}
 */
String.prototype.escapeHTML = function() {
	var div = document.createElement('div');
	var text = document.createTextNode(this);
	
	div.appendChild(text);
	return div.innerHTML;
}


/**
 * escape된 문자열을 HTML태그로 변환하여 리턴한다.
 * @return {string}
 */
String.prototype.unescapeHTML = function() {
	var strEscape = {'quot':'"','amp':'&','lt':'<','gt':'>'};
	return this.replace(/&([a-z]+);/g, function(el0,el1){
		return strEscape[m1]?strEscape[el1]:el0;});
}


/**
 * 문자열을 정해진 자리수만큼 정리하여 리턴.
 * @param {[Number, String]} [number | String]
 * @return {string}
 */
String.prototype.truncate = function(iLength, sTruncation) {
	iLength = iLength || 30;
	sTruncation = (sTruncation == undefined) ? '...' : sTruncation;
	return (this.length > iLength) ?	this.slice(0, iLength - sTruncation.length) + sTruncation : this;
}


/**
 * 정규표현식에 쓰이는 문자를 escape한다.
 */
String.prototype.meta = function() {
	var str = this;
	var result = ""
	for(var i = 0; i < str.length; i++) {
		if((/([\$\(\)\*\+\.\[\]\?\\\^\{\}\|]{1})/).test(str.charAt(i))) {
			result += str.charAt(i).replace((/([\$\(\)\*\+\.\[\]\?\\\^\{\}\|]{1})/), "\\$1");
		} else {
			result += str.charAt(i);
		}
	}
	return result;
}