function getFixDomain() {
	var s = document.domain;
	if ( s.indexOf(domainName) >= 0 ) {
		return domainName;
	} else {
		var n = s.indexOf(".");
		var test = s.split(".");
		if (test.length > 2) {
			return s.substring(n + 1, s.length);
		} else {
			return s;
		}
	}
}

function setDomain() {
	document.domain = getFixDomain();
}

setDomain();

// Common Function
function setCookie(name, value) {
	var argv = setCookie.arguments;
   	var argc = setCookie.arguments.length;
   	var expires = (2 < argc) ? argv[2] : null;
   	var path = (3 < argc) ? argv[3] : null;
   	var domain = (4 < argc) ? argv[4] : null;
   	var secure = (5 < argc) ? argv[5] : false;
   	document.cookie = name + "=" + escape(value) +
      	((expires == null) ? "" :
        ("; expires=" + expires.toGMTString())) +
      	((path == null) ? "; path=/" : ("; path=" + path)) +
      	((domain == null) ? "" : ("; domain=" + getFixDomain())) +
      	((secure == true) ? "; secure" : "");
}

function getCookie(name) {
	var aRec;
	var aCook = document.cookie.split("; ");

	for (var i=0; i<aCook.length; i++) {
		aRec = aCook[i].split("=");
		if (name.toLowerCase()==unescape(aRec[0].toLowerCase())) return aRec[1];
	}

	return "";
}

/**
 * example:
 *  fitPopupSize( [doMove] );                  <- ID가 'page_content'인 object의 clientWidth, clientHeight 값에 따라 사이즈 조절
 *  fitPopupSize( object, [doMove] );          <- 주어진 object의 clientWidth, clientHeight값에 따라 사이즈 조절
 *  fitPopupSize( "pageOuter", [doMove] );     <- ID가 'pageOuter'인 object의 clientWidth, clientHeight 값에 따라 사이즈 조절
 *  fitPopupSize( 300, 400, [doMove] );        <- 팝업 크기를 300 x 400으로 조절
 */
function fitPopupSize( arg1, arg2, arg3 ) {
	var toWidth = null;
	var toHeight = null;
	var objOut = null;
	var positionRequired = true;

	var typeArg1 = typeof(arg1);
	var typeArg2 = typeof(arg2);
	var typeArg3 = typeof(arg3);
	
	if( typeArg1 == "undefined" || typeArg1 == "boolean" ) {
		objOut = document.getElementById("page_content");
		
		if( typeArg1 == "boolean" ) {
			positionRequired = arg1;
		}
	}
	if( typeArg1 == "string" ) {
		objOut = document.getElementById(arg1);
		if( objOut == null ) { return; }
				
		if( typeArg2 == "boolean" ) {
			positionRequired = arg2;
		}
	}

	if( typeArg1 == "object" ) {
		objOut = arg1;
				
		if( typeArg2 == "boolean" ) {
			positionRequired = arg2;
		}
	}
	
	if( objOut != null ) {
		var objParent = objOut.parentNode;
		var getStyle = function(obj) {
			if( obj.currentStyle ) {
				return obj.currentStyle;
			} else if( document.defaultView.getComputedStyle ) {
				return document.defaultView.getComputedStyle(obj, null);
			}
			}

		if( objParent != null && objParent.tagName == "BODY" && getStyle(objOut).position == "absolute" ) {
			try {
				var bodyPaddingTop = 0; var outerPaddingTop = 0;
				var bodyPaddingBottom = 0; var outerPaddingBottom = 0;
				var bodyPaddingLeft = 0; var outerPaddingLeft = 0;
				var bodyPaddingRight = 0; var outerPaddingRight = 0;
				
				if( document.body.currentStyle ) {
					var bodyCurrentStyle = document.body.currentStyle;
					bodyPaddingTop = parseInt(bodyCurrentStyle.paddingTop);
					bodyPaddingBottom = parseInt(bodyCurrentStyle.paddingBottom);
					bodyPaddingLeft = parseInt(bodyCurrentStyle.paddingLeft);
					bodyPaddingRight = parseInt(bodyCurrentStyle.paddingRight);
					
					var outerCurrentStyle = objOut.currentStyle;
					outerPaddingTop = parseInt(outerCurrentStyle.paddingTop);
					outerPaddingBottom = parseInt(outerCurrentStyle.paddingBottom);
					outerPaddingLeft = parseInt(outerCurrentStyle.paddingLeft);
					outerPaddingRight = parseInt(outerCurrentStyle.paddingRight);
					
				} else if( document.defaultView.getComputedStyle ) {
					var objBodyStyle = document.defaultView.getComputedStyle(document.body, null);
					bodyPaddingTop = parseInt(objBodyStyle.getPropertyValue("padding-top"));
					bodyPaddingBottom = parseInt(objBodyStyle.getPropertyValue("padding-bottom"));
					bodyPaddingLeft = parseInt(objBodyStyle.getPropertyValue("padding-left"));
					bodyPaddingRight = parseInt(objBodyStyle.getPropertyValue("padding-right"));
					
					var outerCurrentStyle = document.defaultView.getComputedStyle(objOut, null);
					outerPaddingTop = parseInt(outerCurrentStyle.getPropertyValue("padding-top"));
					outerPaddingBottom = parseInt(outerCurrentStyle.getPropertyValue("padding-bottom"));
					outerPaddingLeft = parseInt(outerCurrentStyle.getPropertyValue("padding-left"));
					outerPaddingRight = parseInt(outerCurrentStyle.getPropertyValue("padding-right"));
				}
				
				var adjustHeight = bodyPaddingTop + bodyPaddingBottom;
				var adjustWidth = bodyPaddingLeft + bodyPaddingRight;
				
				var oWidth = objOut.clientWidth;
				var oHeight = objOut.clientHeight;
				
				// objOut.style.height = oHeight + adjustHeight;				
				objOut.style.paddingTop = outerPaddingTop + bodyPaddingTop;
				objOut.style.paddingBottom = outerPaddingBottom + bodyPaddingBottom;

				// objOut.style.width = oWidth + adjustWidth;
				objOut.style.paddingLeft = outerPaddingLeft + bodyPaddingLeft;
				objOut.style.paddingRight = outerPaddingRight + bodyPaddingRight;
			} catch(e) {
				// do nothing
				// alert( e.message );
			}
		}
		toWidth = objOut.clientWidth;
		toHeight = objOut.clientHeight;
	}

	if( typeArg1 == "number" && typeof(arg2) == "number" ) {
		toWidth = arg1;
		toHeight = arg2;
		
		if( typeArg3 == "boolean" ) {
			positionRequired = arg3;
		}
	}

	if( toWidth == null && toHeight == null ) { return; }
	
	if (toWidth > screen.availWidth) toWidth = screen.availWidth;
	if (toHeight > screen.availHeight) toHeight = screen.availHeight;


	if( positionRequired ) {
		fitPopupSize_adjustPosition( toWidth, toHeight );
	}

	fitPopupSize_resize( toWidth, toHeight );
}

function fitPopupSize_adjustPosition( toWidth, toHeight ) {
	var posLeft = (window.screenLeft) ? window.screenLeft : window.screenX;
	var posTop = (window.screenTop) ? window.screenTop : window.screenY;
	var adjustLeft = 0;	var marginWidth = 50;
	var adjustTop = 0;	var marginHeight = 50;
	var movingRequired = false;

	if( posTop + toHeight + marginHeight > screen.availHeight ) {
		adjustTop = -(posTop + toHeight + marginHeight - screen.availHeight);
		movingRequired = true;
	}
	if( posLeft + toWidth + marginWidth > screen.availWidth ) {
		adjustLeft = -(posLeft + toWidth + marginWidth - screen.availWidth);
		movingRequired = true;
	}
	if( movingRequired ) {
		window.moveBy( adjustLeft, adjustTop );
	}
}

function fitPopupSize_resize( toWidth, toHeight ) {
	var oBody = document.body;
	if( oBody == null ) { return; }

	if( typeof(window.innerHeight) != "undefined" && typeof(window.innerWidth) != "undefined" ) {
		window.innerHeight = toHeight;
		window.innerWidth = toWidth;
	} else {
		var clientWidth = Math.max( document.documentElement.clientWidth, oBody.clientWidth );
		var clientHeight = Math.max( document.documentElement.clientHeight, oBody.clientHeight );
	
		var diffX = toWidth - clientWidth;
		var diffY = toHeight - clientHeight;

		window.resizeBy( diffX, diffY );
	}
/*	
	var posLeft = (window.screenLeft) ? window.screenLeft : window.screenX;
	var posTop = (window.screenTop) ? window.screenTop : window.screenY;

	if( oBody.clientHeight > screen.availHeight ) {
		var adjustHeight = screen.availHeight - (oBody.clientHeight + 50);
		window.moveTo(posLeft, 0);
		window.resizeBy( 0, adjustHeight );
	}
*/		
}

function openWin(sURL, sWindowName, w, h, sScroll, reSize, status) {
	// 화면 중앙으로 Popup 띄우기.. 스크롤바는 옵션..
	// ex)
	//			openWin("test.asp", "winTest", 400, 300);			☞ 스크롤바 없음
	//			openWin("test.asp", "winTest", 400, 300, "yes");	☞ 스크롤바 있음
	//			openWin("test.asp", "winTest", 400, 300, "auto");	☞ 스크롤바 자동

	//var _sWindowName = typeof(sWindowName) != "undefined" ? sWindowName : "";
	
	var x = (screen.width - w) / 2;
	var y = (screen.height - h) / 2;

	if (sScroll==null) sScroll = "no";
	if (screen.width == 800 && screen.height== 600 ) sScroll = "yes"; // 해상도 800*600일 때 스크롤 생기도록 함 
	
	var sOption = "";
	sOption = sOption + "toolbar=no, channelmode=no, location=no, directories=no, menubar=no";
	sOption = sOption + ", scrollbars=" + sScroll + ", resizable=" + reSize + ", status=" + status +", left=" + x + ", top=" + y + ", width=" + w + ", height=" + h;

	//var win = controlOpenWindow(sURL, sWindowName, sOption);
	var win = window.open(sURL, sWindowName, sOption);
	return win;
}

function getDomainHeaderCommon()	{
	var isDev=location.host.indexOf("dev-") > -1;
	var isAlpha=location.host.indexOf("alpha-") > -1;
	var isBeta=location.host.indexOf("beta-") > -1;
	var add="";
	if( isDev ) {
		add = "dev-";
	}
	if( isAlpha ) {
		add = "alpha-";
	}
	if( isBeta ) {
		add = "beta-";
	}
	return "http://" + add;			
}

// Ajax
var JSONAjax=new Object();
JSONAjax.READY_STATE_UNINITIALIZE=0;
JSONAjax.READY_STATE_LOADING=1;
JSONAjax.READY_STATE_LOADED=2;
JSONAjax.READY_STATE_INTERACTIVE=3;
JSONAjax.READY_STATE_COMPLETE=4;
JSONAjax.SERIALNO = 0;
JSONAjax.ContentLoader=function(url,onload,isForcedIFrame, onerror, isHTML){
	this.url = url;
	this.req=null;
	this.onload= onload;
	this.onerror=(onerror)? onerror : this.defaultError;
	this.IFrameObj = null;
	this.isForcedIFrame=(isForcedIFrame)? true : false;
	this.isHTML= (isHTML)? true : false;
}

JSONAjax.ContentLoader.prototype={
	loadContent:function(bAfterComplete){
		var targetHost = this.getHost(this.url);
		var thisHost = this.getHost(document.location.href);
		if(!this.isForcedIFrame && (targetHost == null || targetHost == thisHost)) {
			this.loadAjaxContent(); //same server
		}
		else { //different server
			if(document.readyState && document.readyState != 'complete' && bAfterComplete != 'undefined' && bAfterComplete == true ) { //ie and delayed
				var loader = this;
				attachEvent("onload", function(){loader.loadIFrameContent();});
			}
			else {
				this.loadIFrameContent();
			}
		}
	},
	loadContentAfterComplete:function(){
		this.loadContent(true);
	},
	loadAjaxContent:function(){
		if(window.XMLHttpRequest) {
			this.req = new XMLHttpRequest();
		}
		else if(window.ActiveXObject) {
			this.req=new ActiveXObject("Microsoft.XMLHTTP");
		}

		if(this.req){
			try{
				var loader = this;
				this.req.onreadystatechange=function(){
					loader.onReadyState();
				};

				this.req.open('GET', this.url, true);
				this.req.send(null);
			}
			catch ( err ) {
				this.onerror();
			}
		}
	},
	loadIFrameContent:function(){
		//alert('ready:' +  document.readyState);
		var iframeURL = this.url + ((!this.url.match("\\?"))? "?" : "&") +  "callback=" + this.onload;

		if (!this.IFrameObj) {
			try {
				var iframeID = 'JSONIFrame' + JSONAjax.SERIALNO ++;
				if(document.readyState) { // IE
					var iframeHTML='<iframe id="' + iframeID + '" style="';
					iframeHTML+='border:0px;';
					iframeHTML+='width:0px;';
					iframeHTML+='height:0px;';
					iframeHTML+='"></iframe>';

					if(document.readyState == 'complete') {
						document.body.insertAdjacentHTML("afterEnd", iframeHTML);
					}
					else {
						document.write(iframeHTML);
					}

					this.IFrameObj = document.getElementById(iframeID);
				}
				else { // for firefox
						var tempIFrame=document.createElement('iframe');
						tempIFrame.setAttribute('id', iframeID);
						tempIFrame.style.border='0px';
						tempIFrame.style.width='0px';
						tempIFrame.style.height='0px';
						this.IFrameObj = document.body.appendChild(tempIFrame);
				}
			} catch(exception) {
				alert('json_ajax.js: debugging' + exception);
			}
		}
		if( this.IFrameObj ) this.IFrameObj.src = iframeURL;
	},
	onReadyState:function() {
		var req = this.req;
		var ready = req.readyState;
		if( ready == JSONAjax.READY_STATE_COMPLETE) {
			var httpStatus = req.status;
			if( httpStatus == 200 || httpStatus == 0) {
				var onload = eval( this.onload );
				if(req.responseText){
					if (this.isHTML == false) {
						onload(eval('(' + req.responseText + ')'));
					} else {
						onload(req.responseText);
					}
				}
			}
			else {
				this.onerror();
			}
		}
	},
	defaultError:function(){
	/* for debugging
		alert("error fetching data!"
			+"\n\nreadyState:" + this.req.readyState
			+"\nStatus:" + this.req.status
			+"\nheaders: " + this.req.getAllResponseHeaders());
	*/
	},
	getHost:function(url) {
		var reg = /^http:\/\/([^\/]*)\/.*/i;
		var matched = reg.exec(url);
		var host = null;
		if(matched != null && matched.length == 2) {
			host = matched[1];
		}
		return host;
	}
};

function ajaxHttpRequest(url, callback, isForcedIFrame, isHTML) {
  var contentLoader = new JSONAjax.ContentLoader(url, callback, isForcedIFrame, null, isHTML);
  contentLoader.loadContentAfterComplete();
}

var serviceDomainName = document.domain;
var domainName = ".karosgame.com";
var USER_SELECTED_LOCALE = "i18n_userSelectedLocale";

//var currentLang = getCookie(USER_SELECTED_LOCALE);
var currentLang = "en";

function setLangCode(langCode) {
	var expires = 1000 * 60 * 60 * 24 * 365 * 10;
	var expires_date = new Date( (new Date()).getTime() + (expires) );
	setCookie(USER_SELECTED_LOCALE, langCode, expires_date, null, domainName);
}

function setLangCodeNReload(langCode) {
	setLangCode(langCode);
	setChangeLangLog(langCode);
	location.reload(true);
}	

function setLangCodeNGoPage(langCode, page) {
	setLangCode(langCode);
	setChangeLangLog(langCode);
	location.href = page;
}	

function setChangeLangLog(lang_code) {
	var page_code = getPageCode(location)
	insertLog(lang_code,page_code);
}

function insertLog(lang_code,page_code){
	var param = "page_code=" + page_code + "&lang_code=" + lang_code;
	var urls = getDomainHeaderCommon() + "www.karosgame.com/langchglog.nhn?" + param;
	var loader = new JSONAjax.ContentLoader(urls,doEmptyResult);
	loader.loadContent();	
}

function doEmptyResult(originalRequest) {
	return true;
}	

function getPageCode(location){
	var host = location.host;
	var pathname = location.pathname;
	if(pathname.indexOf("bridge.nhn") > -1) return "B";
	else if(pathname == '/' || (host.indexOf("www") > -1 && pathname.indexOf("index.nhn") > -1)) return "M";
	else return "S";
}

function nclickFunc(arg1,arg2,arg3,arg4,arg5,arg6){
	if(getFixDomain() == domainName) {
		if(getPageCode(location) == 'M'){
			if(arg6){
				clickcr(arg1,arg2,arg3,arg4,arg5,arg6)
			} else {
				clickcr(arg1,arg2,arg3,arg4,arg5);
			}
		}
	}
}

/**
* String을 조합하여 생성하는 클래스 (String을 +로 연결하는 것보다 성능 향상)
*/
function StringBuilder() {
	var _buffer = [];
	for(var i=0;i<arguments.length; i++) {
		_buffer.push(arguments[i]);
	}
	
	/**
	 * 문자열을 추가함
	 * @param {String|Number|Boolean} sMessage... 조합할 문자열
	 * @return {Object} StringBuilder 객체
	 */
	this.append = function() {
		for(var i=0;i<arguments.length; i++) {
			_buffer.push(arguments[i]);
		}
		return this;
	};
	
	/**
	 * 현재 추가된 문자열이 없는지 여부
	 * @return {Boolean}
	 */
	this.isEmpty = function() {
		return _buffer.length <= 0;
	};
	
	/**
	 * 마지막으로 추가한 문자열 제거
	 * @return {Object} StringBuilder 객체
	 */
	this.deleteLastAppended = function() {
		_buffer.pop();
		return this;
	};
	
	/**
	 * String으로 완성하여 리턴
	 * @return {String} 최종 완성된 문자열
	 */
	this.toString = function() {
		return _buffer.join("");
	};
	
	return this;
}
