/*
 * JS Common Function
 * 2008-07 KiHyun Kim
 */

/* Common Functions *******************************/

function f_getIframeHeight(){
	var agent_name	= navigator.userAgent.toLowerCase();
	var is_ie		= ((agent_name.indexOf("msie") != -1) && (agent_name.indexOf("opera") == -1));
	var is_ie7		= (is_ie && (parseFloat(navigator.appVersion.split('MSIE')[1])>=7));
	var is_ie7_2	= (is_ie7 && (document.all[0].nodeType==8));
	var is_gecko	= navigator.product;
	var is_strict	= (document.compatMode == 'CSS1Compat');
	var body		= ( ((is_ie && (is_ie7 || is_strict)) || (!is_ie)) ? self.document.documentElement : self.document.body );
	var bodyHeight	= body.scrollHeight;
	return bodyHeight;
}

function f_iframeHeightResize(iframeId, height){
	var ifrm = document.getElementById(iframeId);
	if (!ifrm) return;
	ifrm.style.height = height;
	if (navigator.userAgent.indexOf("Firefox") != -1) {
		if (ifrm.frameElement)
			ifrm.frameElement.height = height;
		else
			ifrm.height = height;
	}
}

function f_createHiddenIframe(newiFrameID) {
	if (document.getElementById(newiFrameID)) return;
	try { /* IE specific */ 
		var iFrame = document.createElement('<iframe id="' + newiFrameID + '" name="' + newiFrameID + '" src="about:blank" style="display:none;width:0px;height:0px;border:none;"></iframe>');  
		if(iFrame.nodeName.toUpperCase() == 'IFRAME') { document.body.appendChild(iFrame); }
		else { throw new Error('`createElement` error.'); }
	}catch(e){
		try { 
			var iFrame = document.createElement('iframe'); 
			iFrame.setAttribute('src', 'about:blank');
			iFrame.style.display = 'none';
			iFrame.style.width   = '0px';
			iFrame.style.height  = '0px';
			iFrame.style.border  = 'none';
			iFrame.setAttribute('id', newiFrameID);
			iFrame.setAttribute('name', newiFrameID);
			document.body.appendChild(iFrame);
			if(self.frames.length == 0) { 
				try { document.body.removeChild(iFrame); } 
				catch(e) {}
				throw new Error('`createElement` error.'); 
			}
		}catch(e){ throw new Error('`createElement` error.'); }
	}
}

function f_compareForm(form_src, form_desc) {
	var sform = document.forms[form_src];
	var dform = document.forms[form_desc];
	var objs = dform.getElementsByTagName('INPUT');
	for (var i=0; i<objs.length; i++) {
		if (!sform[objs[i].name]) return false;
		if (f_getFormValue(sform[objs[i].name])!=f_getFormValue(dform[objs[i].name])) return false;
	}
	var objs = dform.getElementsByTagName('TEXTAREA');
	for (var i=0; i<objs.length; i++) {
		if (!sform[objs[i].name]) return false;
		if (f_getFormValue(sform[objs[i].name])!=f_getFormValue(dform[objs[i].name])) return false;
	}
	return true;
}

function f_copyForm(form_src, form_desc) {
	var sform = document.forms[form_src];
	var dform = document.forms[form_desc];
	var objs = dform.getElementsByTagName('INPUT');
	for (var i=0; i<objs.length; i++) {
		if (sform[objs[i].name]) f_setFormValue(dform[objs[i].name], f_getFormValue(sform[objs[i].name]));
	}
	var objs = dform.getElementsByTagName('TEXTAREA');
	for (var i=0; i<objs.length; i++) {
		if (sform[objs[i].name]) f_setFormValue(dform[objs[i].name], f_getFormValue(sform[objs[i].name]));
	}
	return;
}

function f_getFormValue(obj) {
	if (!obj) return -1;
	if (!obj.type) { 
		if ( obj[0] && ((obj[0].type=='radio')||(obj[0].type=='checkbox')) ) { 
			for (var i=0; i<obj.length; i++) {
				if (obj[i].checked ) return obj[i].value;
			}
		}
	}else if ((obj.type=='text')||(obj.type=='password')||(obj.type=='textarea')||(obj.type=='hidden')) { 
		return obj.value;
	}else if (obj.type.match(/select*/g)) {
		if (obj.selectedIndex >= 0) return obj.options[obj.selectedIndex].value;
	}else if (((obj.type=='radio')||(obj.type=='checkbox'))&&(obj.checked)) {
		return obj.value;
	}
	return '';
} 

function f_getIndexByValue(obj, strValue) {
	if (!obj) return -1;
	if (!obj.type) { 
		if ( obj[0] && ((obj[0].type=='radio')||(obj[0].type=='checkbox')) ) { 
			for (var i=0; i<obj.length; i++) {
				if (obj[i].value==strValue) return i;
			}
		}
	}else if (obj.type.match(/select*/g)) {
		for (var i=0; i<obj.options.length; i++ ) {
			if (obj.options[i].value==strValue) return i;
		}
	}else if (((obj.type=='radio')||(obj.type=='checkbox'))&&(obj.value==strValue)) {
		return null; 
	}
	return -1;
}

function f_setFormValue(obj, strValue) {
	if (!obj) return;
	if (!obj.type) { 
		if ( obj[0] && ((obj[0].type=='radio')||(obj[0].type=='checkbox')) ) { 
			for(var i=0; i<obj.length; i++) {
				if (obj[i].value==strValue) obj[i].checked = true;
				else obj[i].checked = false;
			}
		}
	}else if ((obj.type=='text')||(obj.type=='password')||(obj.type=='textarea')||(obj.type=='hidden')) { 
		obj.value = strValue;
	}else if (obj.type.match(/select*/g)) {
		for (var i=0; i<obj.options.length; i++ ) {
			if (obj.options[i].value==strValue) {
				obj.selectedIndex = i;
				return;
			}
		}
		obj.selectedIndex = -1;
	}else if (((obj.type=='radio')||(obj.type=='checkbox'))&&(obj.value==strValue)) { 
		obj.checked = true; 
	}
	return;
} 

function f_addEvent (obj, evt, func, capture) {
	if (!obj) return;
	if (obj.attachEvent) { obj.attachEvent(evt, func); }
	else if (obj.addEventListener) {
		if (!capture) capture=false;
		evt = evt.replace(/^on/i,'');
		obj.addEventListener(evt, func, capture);
	}else{ obj[evt] = fnc; }
	return;
}

function f_removeEvent (obj, evt, func, capture) {
	if (!obj) return;
	if (obj.detachEvent) { obj.detachEvent(evt, func); }
	else if (obj.removeEventListener) {
		if (!capture) capture=false;
		evt = evt.replace(/^on/i,'');
		obj.removeEventListener(evt, func, capture);
	}else{ obj[evt] = null; }
	return;
}

function f_correctPNG (img) {
	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);
	//if ((version < 7) && (version >= 5.5) && (document.body.filters)) {
	if ((version >= 5.5) && (document.body.filters)) {
		var imgName = img.src.toUpperCase()
		if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
			var imgID = (img.id) ? "id='" + img.id + "' " : "";
			var imgClass = (img.className) ? "class='" + img.className + "' " : "";
			var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
			var imgStyle = "display:inline-block;" + img.style.cssText ;
			if (img.align == "left") imgStyle = "float:left;" + imgStyle;
			if (img.align == "right") imgStyle = "float:right;" + imgStyle;
			if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
			var strNewHTML = "<span " + imgID + imgClass + imgTitle
				+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
				+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
				+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" ;
			img.outerHTML = strNewHTML;
		}
	}
}

function f_getAbsolutePosition(obj) {
	for (var lx=0,ly=0; obj!=null;
	lx+=obj.offsetLeft, ly+=obj.offsetTop, obj=obj.offsetParent);
	return { x:lx, y:ly }
}

function f_getStyle(obj, style) {
	var value = '';
	if (this.document.defaultView)
		value = this.document.defaultView.getComputedStyle(obj,'').getPropertyValue(style);
	else if (obj.currentStyle) {
		style = style.replace(/\-(\w)/g, function (strMatch,p1){return p1.toUpperCase();});
		value = obj.currentStyle[style];
	}
	return value;
}
	
function f_getFileExt(filepath) {
	var pos = filepath.lastIndexOf('.');
	if (pos<0) return '';
	var string = filepath.substr(pos+1);
	var extArr = string.match(/^[0-9a-z\_\-]+/gi);
	return extArr[0];
}

function f_isEmailAddress(email) {
	var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	//var filter = /^[0-9a-z\_\.\-]+@[0-9a-z\_\.\-]+$/i;
	return filter.test(email);
}

function f_getCookie( name ) {
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	for ( i = 0; i < a_all_cookies.length; i++ ) {
		a_temp_cookie = a_all_cookies[i].split( '=' );
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		if ( cookie_name == name ) {
			if ( a_temp_cookie.length > 1 ) {
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			return cookie_value;
		}
	}
	return '';
}

function f_setCookie( name, value, expires, path, domain, secure ) {
	document.cookie = name + '=' +escape( value ) +
	( ( expires && (expires.constructor==Date) ) ? ';expires=' + expires.toGMTString() : '' ) + 
	( ( path ) ? ';path=' + path : '' ) + 
	( ( domain ) ? ';domain=' + domain : '' ) +
	( ( secure ) ? ';secure' : '' );
}

function f_createXHObject() {
	if (window.ActiveXObject) {
		var aVersions = ['Msxml2.XMLHTTP.7.0', 'Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
		for (var i=0; i<aVersions.length; i++) {
			try { var xmlHttp = new ActiveXObject(aVersions[i]); return xmlHttp; } catch(e) {}
		}
	}else if ( typeof(XMLHttpRequest) != 'undefined' ) {
		var xmlHttp = new XMLHttpRequest(); return xmlHttp;
	}
	return false;
}

function f_executeXHRequest(method, uri, async, postdata, callbackFunction, callbackArguments) {
	var xmlHttp = f_createXHObject();
	if (xmlHttp) {
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState==4) {
				if (xmlHttp.status==200) {
					if ((callbackFunction!=null)&&(callbackFunction.constructor == Function)) { callbackFunction(xmlHttp, callbackArguments); } xmlHttp = null;
				}
			}
			return;
		}
		xmlHttp.open(method.toLowerCase(), uri, async);
		if (method.toLowerCase()=='post') {
			xmlHttp.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
			xmlHttp.send(postdata);
		}else xmlHttp.send(null);
	}
}

function f_listXH2Array(xmlHttp) {
	var arrData = new Array();
	if (xmlHttp) {
		var xml		= xmlHttp.responseXML;
		var root	= xml.documentElement;
		var games	= root.getElementsByTagName('game');
		for (var i=0; i<games.length; i++) {
			var thisRow = new Object();
			for (var j=0; j<games[i].childNodes.length; j++) {
				if (games[i].childNodes[j].hasChildNodes()) {
					thisRow[games[i].childNodes[j].nodeName] = games[i].childNodes[j].firstChild.nodeValue;
				}else{
					thisRow[games[i].childNodes[j].nodeName] = '';
				}
			}
			arrData.push(thisRow);
		}
		xml = root = games = null;
	}
	return arrData;
}

function base64_encode( data ) {
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = ac = 0, enc="", tmp_arr = [];
    data = utf8_encode(data);
    do {
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);
        bits = o1<<16 | o2<<8 | o3;
        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);
    enc = tmp_arr.join('');
    switch( data.length % 3 ){
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }
    return enc;
}

function utf8_encode ( string ) {
    string = (string+'').replace(/\r\n/g,"\n");
    var utftext = "";
    var start, end;
    var stringl = 0;
    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
        if (c1 < 128) {
            end++;
        } else if((c1 > 127) && (c1 < 2048)) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc != null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }
    if (end > start) {
        utftext += string.substring(start, string.length);
    }
    return utftext;
}

// Xpath implement for firefox
( function() {
	if ((!window.ActiveXObject)&&(typeof(XMLHttpRequest)!='undefined')) {
		Element.prototype.selectSingleNode = function (sXPath) {
			var oEvaluator = new XPathEvaluator();
			var oResult = oEvaluator.evaluate(sXPath, this, null, 
			XPathResult.FIRST_ORDERED_NODE_TYPE, null);
			return ( (oResult != null) ? oResult.singleNodeValue : null );
		}
	}
} )();

String.prototype.Contains = function(textToCheck){
	return ( this.indexOf( textToCheck ) > -1 ) ;
}

String.prototype.Equals = function(){
	for ( var i = 0 ; i < arguments.length ; i++ )
		if ( this == arguments[i] ) return true ;
	return false ;
}

String.prototype.ReplaceAll = function(searchArray, replaceArray){
	var replaced = this ;
	for (var i=0; i<searchArray.length; i++){
		replaced = replaced.replace(searchArray[i], replaceArray[i]);
	}
	return replaced ;
}

String.prototype.startsWith = function(value){
	return (this.substr(0, value.length)==value);
}

String.prototype.endsWith = function(value, ignoreCase){
	var L1 = this.length;
	var L2 = value.length;
	if (L2>L1) return false;
	if ( ignoreCase ){
		var oRegex = new RegExp(value+'$', 'i');
		return oRegex.test(this);
	}else
		return (L2==0||this.substr(L1-L2,L2)==value);
}

String.prototype.remove = function(start, length){
	var s='';
	if (start>0) s=this.substring(0, start);
	if (start+length<this.length) 
		s += this.substring(start+length, this.length);
	return s ;
}

String.prototype.trim = function(){
	return this.replace( /(^\s*)|(\s*$)/g, '' ) ;
}

String.prototype.ltrim = function(){
	return this.replace( /^\s*/g, '' ) ;
}

String.prototype.rtrim = function(){
	return this.replace( /\s*$/g, '' ) ;
}

String.prototype.replaceNewLineChars = function(replacement){
	return this.replace( /\n/g, replacement ) ;
}

String.prototype.is2bytes = function(index){
	if ( this.length >= (index+1) ) {
		var c = this.charCodeAt(index);
		if ((c >= 0x0000) && (c <= 0x0080)) return false;
		if ((c >= 0x00A1) && (c <= 0x00DF)) return false;
		if ((c >= 0x00F0) && (c <= 0x00FF)) return false;
		return true;
	}
	return false;
}

String.prototype.blength = function(){
	var count = 0;
	for (var i=0; i<this.length; i++) {
		if (this.is2bytes(i)) count=count+2;
		else count++;
	}
	return count;
}

String.prototype.bsubstr = function(start,length){
	var value = this.substr(start,length);
	if ( value.is2bytes(0) && (!value.is2bytes(1)) ) value = value.substr(1);
	if ( value.is2bytes(value.length-1) && (!value.is2bytes(value.length-2)) ) value = value.substr(0,value.length-1);
	return value;
}

Number.prototype.formatCipher = function(cipher) {
    var txtNumber = this.toString();
	if (txtNumber != '') {
		var txtLenth = txtNumber.length;
		if (txtLenth < cipher) {
			for (var i=0; i<(cipher-txtLenth); i++) txtNumber = '0' + txtNumber;
		}
		return txtNumber;
	}
	return '';
}

Number.prototype.comma3 = function () {
    var txtNumber = this.toString();
	if (txtNumber != '') {
		var rxSplit = new RegExp('([0-9])([0-9][0-9][0-9][,.])');
		var arrNumber = txtNumber.split('.');
		arrNumber[0] += '.';
		do {
			arrNumber[0] = arrNumber[0].replace(rxSplit, '$1,$2');
		} while (rxSplit.test(arrNumber[0]));
		if (arrNumber.length > 1) {
			return arrNumber.join('');
		}else{
			return arrNumber[0].split('.')[0];
		}
	}
	return '';
}

Array.prototype.indexOf = function(value) {
	for (var i=0; i<this.length; i++){
		if (this[i]==value) return i;
	}
	return -1;
}

Array.prototype.abstraction = function(value) {
	var result = new Array();
	for (var i=0; i<this.length; i++) {
		if (this[i] != value) result.push(this[i]);
	}
	return result;
}

Array.prototype.filterNull = function() {
	var result = new Array();
	for (var i=0; i<this.length; i++) {
		if (this[i]) result.push(this[i]);
	}
	return result;
}