﻿try { document.execCommand("BackgroundImageCache",false,true) } catch (e) {};
window.onbeforeunload = function() {window.__flash__removeCallback=function(i,n){try{if(i)i[n]=null}catch(e){}}}; // Flash IE unload bug fix

/*  Ntreev Channel Navigation Bar [ 2009-09-11 ]
*   Copyright (c) 2009, ALL right reserved.
*   Script by Su-hyung, park
*
*   정식사이트용 ntreev.common.js 와 ngnb.js 파일을 합쳐서 하나의 파일로 만들어
*   채널링 사이트에서 손쉽게 NGNB를 출력할 수 있도록 만들어졌습니다.
*/

/*
document.write('<script type="text/javascript" src="http://public.gametree.co.kr/Global/js/ntreev.common.js"> </script>');
document.write('<script type="text/javascript" src="http://common.gametree.co.kr/NGNB/ngnb.js"> </script>');
*/

var Ns = window.Ntreevsoft =
{
	// 현재 접속중인 domain의 서비스코드
	rsn : function(url)
	{
		var d = url || document.domain;
		return /(\.|^)vvvic/i.test(d) ? 7	// 비비빅
			: /pcbang\./i.test(d) ? null	// 피씨방
			: 0;
	},

	// 이미지로딩 완료 여부에 상관없이 문서가 준비되는데로 실행할 함수를 예약
	ready : function(fn)
	{
		var doc = document;
		if (!doc.readyFns) {
			doc.readyFns = [];

			// trigger function closure
			var ready = function() {
				setTimeout(function() {
					for (var i = 0, f; f = doc.readyFns.shift(); f());
					doc.done = true;
				},0);
			};

			if (doc.attachEvent) {
				doc.attachEvent( "onreadystatechange", function() {
					if ( doc.readyState === "complete" )
						ready();
				});
			} else {
				doc.addEventListener( "DOMContentLoaded", ready, false );
			}
		}

		if (doc.done) fn();
		else doc.readyFns.push(fn);
	},

	getCookie : function(cn) {
		return (RegExp('(?:^|;| )'+cn+'=([^;]+)').exec(document.cookie) || [0, ''])[1];
	},

	// 현재 접속중인 domain의 secure protocol 여부
	isSecure : function(url)
	{
		return /^https/.test(url || location.href);
	},

	// 현재 접속중인 domain의 서비스 도메인 ( ui / qa / dev / local ) 추출
	getServiceDomain : function()
	{
		var service = /^(?:ui|qa|dev|local)/.exec(document.domain);
		return service ? service + '.' : '';
	},

	// 현재 접속중인 url을 기반으로 정확한 returnUrl을 추출
	returnUrl : function()
	{
		var r_url = document.getElementById('r_url');
		return escape( Ns.rsn() == 7 ? 'http://' + document.domain + '/Util/LogOut_Proc.asp' : r_url ? r_url.value : location.href );
	}
};

// Login handler
Ns.Login =
{
    is: function() {
        return !!Ns.getCookie('NMLI');
    },

    get: function() {
        var method = document.getElementById('login_method');
        var id = document.getElementById('login_id');
        var pass = document.getElementById('password');
        var secure = document.getElementById('login_secure');
        var save = document.getElementById('save_id');
        var url = (secure.checked ? 'https://' : 'http://') + 'login.gametree.co.kr/LoginProcess.aspx';

        if (!id.value) { alert('아이디를 입력해주세요.'); return !!id.focus(); }
        if (!pass.value) { alert('비밀번호를 입력해주세요.'); return !!pass.focus(); }

        if (!method || method.value != 'ajax') {
			var form = document.forms['GTLogin'] || document.forms[0];
            form.action = url;
            form.submit();
            return;
        }

        var param = [
			'login_method=' + method.value,
			'login_id=' + id.value,
			'password=' + pass.value,
			'save_id=' + (save.checked ? 'on' : 'off'),
			'r_url=' + escape('http:///www.naver.com/'),
			'rsn=' + Ns.rsn()
		].join('&');

        // Ajax로 로그인 데이타 전송
        Ns.Ajax.request(url, { param: param, onSuccess: this.process });

        return false;
    },

	process: function(res) {
        // res.ResultCode : [ 0 성공, -1 실패 ]
		alert( res.ResultCode );
        if (res.Message) alert(res.Message);
        if (res.CallbackScript) eval(res.CallbackScript);
        if (res.RedirectUrl) top.location.href = res.RedirectUrl;
        document.getElementById('password').select();
    },

    // 로그아웃
    out: function() {
		top.location.href = 'http://login.gametree.co.kr/LogoutProcess.aspx?r_url=' + Ns.returnUrl() + '&rsn=' + Ns.rsn();
    },

    // 로그인페이지로 이동
    go: function() {
        top.location.href = 'http://www.gametree.co.kr/Secure/Login/Login.aspx?r_url=' + Ns.returnUrl();
    }
};

// Treecahe handler
Ns.TreeCash =
{
    recharge: function(method) {
        window.open('http://www.gametree.co.kr//Payment/AgreementState.aspx?Method=' + method, 'Recharge', 'width=460, height=550');
    }
};

// Gametree Content navigator
Ns.Content =
{
    home: function() {
        top.location.href = 'http://www.gametree.co.kr/';
    },

    join: function() {
        top.location.href = 'http://www.gametree.co.kr/SignUp/Join.aspx?rsn='+Ns.rsn();
    },

    info: function() {
        top.location.href =  'http://www.gametree.co.kr/Secure/MyPage/Default.aspx';
    },

	find: function() {
        window.open('http://www.gametree.co.kr/Secure/MyPage/Member/FindId.aspx', 'FindIdPopup', 'width=460, height=254, top=20, left=20');
    }
};

Ns.Flash =
{
    // 주어진 정보를 기반으로 flash html을 생성
	create: function(file, name, width, height, vars, wmode) {
		this.count++;
		name = name || '__swfObject__'+this.count;
		return [
			'<object width="' + width + '" height="' + height + '" id="' + name + '" name="' + name + '" ',
			(document.all
				? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="https://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0"><param name="movie" value="' + file + '" />'
				: 'type="application/x-shockwave-flash" data="' + file + '">'
			),
			'<param name="allowScriptAccess" value="always" />',
			'<param name="quality" value="high" />',
			'<param name="showMenu" value="false">',
			'<param name="Menu" value="false">',
			'<param name="wmode" value="' + (wmode || 'transparent') + '">',
			'<param name="flashVars" value="' + vars + '">',
			'</object>'
		].join('');
    }
};

// Ajax handler
Ns.Ajax =
{
	crossCount : 0,
    createXHR: function() {
        try {
            return new XMLHttpRequest();
        } catch (e) {
            return new ActiveXObject("Msxml2.XMLHTTP") || new ActiveXObject("Microsoft.XMLHTTP");
        }
    },

    // Ajax request
    request: function(url, option) {
        // 기본적으로 필요한 option property 를 생성
        var opt = option || {};
        var prop = {
            sync: opt.sync ? false : true,
            param: this.toSerialize(opt.param || ''),
            method: (opt.method || 'POST').toUpperCase(),
            type: opt.responseType || '',
            success: opt.onSuccess || Function(),
            failed: opt.onFailed || function(code, txt) { },
            ready: opt.onReady || Function(),
            complete: opt.onComplete || Function()
        };

        var file = (Ns.isSecure() ? 'https://' : 'http://') + 'public.gametree.co.kr/Global/flash/Nfu_ajax.swf?ver=' + Math.random();
        var n = this.crossCount++;
		var doc = document;

        this['f' + n] = prop.failed;
        this['r' + n] = prop.ready;
        this['c' + n] = prop.complete;
        this['s' + n] = function(res) {
            prop.success(Ns.Ajax.getResponseData(prop.type, {
                responseText: res,
                responseXML: Ns.Convert.toXML(res)
            }));
        };

		var div = doc.createElement('div');
        with (div.style) { position = 'absolute'; top = '0'; left = '0'; zIndex = '9999'; }
        div.innerHTML = Ns.Flash.create(file, '', 1, 1, [
			'url=' + escape(url),
			'param=' + escape(prop.param),
			'method=' + prop.method,
			'sn=Ns.Ajax.s' + n, 'fn=Ns.Ajax.f' + n, 'rn=Ns.Ajax.r' + n, 'en=Ns.Ajax.e' + n
		].join('&'), 'window');

		if (doc.body) {
			doc.body.insertBefore(div, doc.body.firstChild);
		} else {
			Ns.ready(function() {
				doc.body.insertBefore(div, doc.body.firstChild);
			});
		}
    },

    // Object 형식의 객체를 param값으로 주어졌을경우 string serialize 처리
    toSerialize: function(obj) {
        if (obj.constructor == Object) {
            var txt = [];
            for (var n in obj) {
                txt.push(n + '=' + escape(obj[m]));
            }

            return txt.join('&');
        }
        return obj;
    },

    // 응답받은 데이타를 지정된 형식의 객체로 변환
    // 변환가능한 객체형식 ( TEXT, XML, JSON )
    getResponseData: function(type, res) {
        var type = type.toUpperCase();
        var xml = res.responseXML;
        var txt = res.responseText;

        // selected binding
        if (!txt && !xml) return null;
        if (type == 'TEXT') return txt;
        if (type == 'XML') return xml;
        if (type == 'JSON') return Ns.Convert.toJSON(txt);

        // auto binding
        return xml && xml.documentElement && xml.documentElement.childNodes.length ? xml : Ns.Convert.toJSON(txt) || txt;
    }
};

// Event handler
Ns.Event =
{
	// 해당 obj 에 지속성 이벤트 삽입
	add : function(obj, handler, fn)
	{
		if (obj.attachEvent) {
			obj.attachEvent("on"+handler, fn);
		} else {
			obj.addEventListener(handler, fn, false);
		}
	}
};

// Object Converter
Ns.Convert =
{
	// XMLString to XML
	toXML : function(str)
	{
		try {
			if (window.ActiveXObject) {
				var xml = new ActiveXObject('Microsoft.XMLDOM');
				xml.async = false;
				xml.loadXML(str);
				return xml;
			}
			if (window.DOMParser) {
				var xml = new DOMParser();
				return xml.parseFromString(str, 'text/xml');
			}
		} catch(e) {};
	},

	// JSONString to JSON
	toJSON : function(str)
	{
		try {
			eval('var json = ' + str.replace(/^\t+|^\s|\n|\r|\s$/mg, '').replace(/,(?=\})/mg, '').replace(/,(?=\])/mg, ''));
			return json;
		} catch(e) {
			return null;
		}
	}
};

var NGNB =
{
	css : '<link rel="stylesheet" href="$path/ngnb.css" type="text/css" />',
	html : [
		'<div><div id="ngnb">',
		'	<div class="ngnb-wrap">',
		'		<a href="javascript:Ns.Content.home()" class="ngnb-logo"><img src="$path/img/logo.gif" alt="gametree" /></a>',
		'		<a class="ngnb-game" onmouseover="NGNB.showGames()" onmouseout="NGNB.hideGames()"><img src="$path/img/txt1.gif" onmouseover="this.src=\'$path/img/txt1o.gif\'" onmouseout="this.src=\'$path/img/txt1.gif\'" alt="게임" /></a>',
		Ns.rsn() ? (
			'<a href="$home/Event/" class="ngnb-txt"><img src="$path/img/txt2.gif" onmouseover="this.src=\'$path/img/txt2o.gif\'" onmouseout="this.src=\'$path/img/txt2.gif\'" alt="이벤트" /></a>'
		) : '',
		Ns.rsn() ? (
			Ns.Login.is() && Ns.rsn() ? '<a href="javascript:Ns.Content.info()" class="ngnb-member"><img src="$path/img/btn_mypage.gif" alt="마이페이지" /></a><a href="javascript:Ns.Login.out()" class="ngnb-member"><img src="$path/img/btn_logout.gif" alt="로그아웃" /></a>'
			: Ns.getCookie('vvvic').indexOf('tStr') != -1 ? '<a href="/Util/LogOut_Proc.asp" class="ngnb-member"><img src="$path/img/btn_logouts.gif" alt="로그아웃" /></a>'
			: Ns.rsn() != 7 ? '<a href="javascript:Ns.Content.join()" class="ngnb-member"><img src="$path/img/btn_signup.gif" alt="회원가입" /></a>'
			: ''
		) : '',
		'		<p class="ngnb-banner" id="ngnb-promotions"></p>',
		'	</div>',
		'</div>',

		'<div id="ngnb-games"  onmousemove="NGNB.showGames()" onmouseout="NGNB.hideGames()">',
			'<dl class="sportCasual" id="ngnb-games-div">',
				'<dt><img src="$path/img/title_sportCasual.png" alt="스포츠/캐주얼 게임" /></dt>',
				'<dd class="nowing"><a href="http://$servicebm.gametree.co.kr"><img src="$path/img/nowing_sports.png" alt="프로야구 매니저" /></a></dd>',
				'<dd><a href="http://$servicealicia.gametree.co.kr">말과 나의 이야기, 앨리샤</a></dd>',
				'<dd><a href="http://$servicebm.gametree.co.kr">프로야구 매니저</a></dd>',
				'<dd><a href="http://$servicepangya.gametree.co.kr">팡야</a></dd>',
				'<dd><a href="http://$servicedinomachia.gametree.co.kr">디노마키아</a></dd>',
			'</dl>',
			'<dl class="gameRpg">',
				'<dt><img src="$path/img/title_rpg.png" alt="RPG 게임" /></dt>',
				'<dd class="nowing"><a href="http://$servicetrickster.gametree.co.kr/Events/201004_7th/Default.aspx"><img src="$path/img/nowing_rpg.png" alt="트릭스터" /></a></dd>',
				'<dd><a href="http://$servicetrickster.gametree.co.kr/Events/201004_7th/Default.aspx">트릭스터</a></dd>',
				'<dd><a href="http://$servicesinmadae.gametree.co.kr">신 마법의 대륙</a></dd>',
			'</dl>',
			'<dl class="gameWeb">',
			'	<dt><img src="$path/img/title_web.png" alt="웹 게임" /></dt>',
			'	<dd class="nowing"><a href="http://$servicearche.gametree.co.kr"><img src="$path/img/nowing_web.png" alt="문명전쟁 아르케" /></a></dd>',
			'	<dd><a href="http://$servicearche.gametree.co.kr">문명전쟁 아르케</a></dd>',
			'	<dt class="fps"><img src="$path/img/title_fps.png" alt="FPS 게임" /></dt>',
			'	<dd><a href="http://$serviceblackshot.gametree.co.kr">블랙샷</a></dd>',
			'</dl>',
			'<dl class="gameFlash">',
			'	<dt><img src="$path/img/title_flash.png" alt="플래시 게임" /></dt>',
			'	<dd class="nowing"><a href="http://vvvicbakery.gametree.co.kr/"><img src="$path/img/nowing_flash.png" alt="뿌띠빠띠" /></a></dd>',
			'	<dd><a href="http://vvvicbakery.gametree.co.kr/">뿌띠빠띠</a></dd>',
			'	<dd><a href="http://vvvic.gametree.co.kr">비비빅</a></dd>',
			'	<dd><a href="http://vvvicellejou.gametree.co.kr">보석소녀 엘레쥬</a></dd>',
			'	<dd><a href="http://vvvicjadoo.gametree.co.kr">자두의 성공시대</a></dd>',
			'</dl>',
			'<dl class="gameMobile">',
			'	<dt><img src="$path/img/title_mobile.png" alt="모바일 게임" /></dt>',
			'	<dd class="nowing"><a href="http://www.djmaxmobile.com"><img src="$path/img/nowing_mobile.png" alt="디제이 맥스" /></a></dd>',
			'	<dd><a href="http://www.djmaxmobile.com">디제이맥스</a></dd>',
			'	<dd><a href="http://www.gxg.com/detail/Detail_GameInfo.aspx?VPID=0030639980" target="_blank">싸이한대맞고</a></dd>',
			'	<dd><a href="http://www.gxg.com/detail/Detail_GameInfo.aspx?VPID=0030785348" target="_blank">엑소더스</a></dd>',
			'	<dd><a href="http://www.gxg.com/detail/Detail_GameInfo.aspx?VPID=0030516099" target="_blank">고스트페이스</a></dd>',
			'	<dd><a href="http://www.gxg.com/detail/Detail_GameInfo.aspx?VPID=0030243802" target="_blank">당구마스터</a></dd>',
			'	<dd><a href="http://www.whitedaymobile.com">화이트데이</a></dd>',
			'</dl>',
		'</div>'

	].join('\n'),

	http : Ns.isSecure() ? 'https://' : 'http://',
	service : Ns.getServiceDomain(),

	showGames : function() { document.getElementById('ngnb-games').style.display = 'block' },
	hideGames : function() { document.getElementById('ngnb-games').style.display = 'none' },

	Write : function()
	{
		var home =  'http://' + this.service + 'www.gametree.co.kr';
		var path = this.http + this.service + 'common.gametree.co.kr/NGNB';
		var gamelist = this.http + this.service + 'www.gametree.co.kr/NGNB/GameList.aspx';
		var promotions = this.http + this.service + 'www.gametree.co.kr/NGNB/PromotionList.aspx';
		//gamelist = 'http://qa.www.gametree.co.kr/NGNB/GameList.aspx';
		//promotions = 'http://qa.www.gametree.co.kr/NGNB/PromotionList.aspx';

		// init ngnb html
		var doc = document;
		doc.write( this.css.replace(/\$path/gm, path) );
		doc.write( this.html.replace(/\$path/gm, path).replace(/\$home/gm, home).replace(/\$service/gm, this.service));

		// init Game banners
		Ns.Ajax.request(gamelist, {
			method : 'get',
			onSuccess : function(res) {
				try {
					NGNB.initGames(res.getElementsByTagName('Item'));
				}
				catch (e) {}
			},
			onFailed : function() {
			}
		});

		// init Promotion banners
		Ns.Ajax.request(promotions, {
			method : 'get',
			onSuccess : function(res) {
				try {
					NGNB.initPromotions(res.getElementsByTagName('Item'));
				}
				catch (e) {}
			},
			onFailed : function() {
			}
		});

		// min-width fix for ie ( 998px )
		if (doc.all) {
			var ngnb = doc.getElementById('ngnb');
			var body = !doc.compatMode || doc.compatMode.indexOf('CSS1') == -1 ? doc.body : doc.documentElement || doc.body;
			Ns.Event.add(window, 'resize', function() { ngnb.style.width = Math.max(998, body.clientWidth) + 'px' });
			ngnb.style.width = Math.max(998, body.clientWidth) + 'px';
		}
	},

	clearXML : function(nodes)
	{
		for (var i = 0, n; n = nodes[i]; i++) if (n.nodeType != 1) n.parentNode.removeChild(n);
		return nodes;
	},

	/*initGames : function(items)
	{
		NGNB.clearXML(items);
		var len = items.length;
		var target = document.getElementById('ngnb-games-div');

		for (var i = 0; i < len; i++) {
			var infos = NGNB.clearXML(items[i].childNodes);
			var titKr = infos[1].firstChild.nodeValue;
			var img = infos[2].firstChild.nodeValue.replace('http://', NGNB.http);
			var url = infos[3].firstChild.nodeValue;
			var tgt = infos[4].firstChild.nodeValue;
			var dd = document.createElement('dd');
			dd.innerHTML = '<a href="'+url+'" target="'+tgt+'" title="'+titKr+' 웹사이트 바로가기"><img src="'+img+'" width="145" height="40" alt="'+titKr+'" /></a>';
			target.appendChild(dd);
			dd = null;
		}

		// 게임목록수가 홀수일시 빈 게임목록 영역 추가
		if ( len % 2 == 1 ) {
			var dummy = document.createElement('dd');
			with (dummy.style) {
				width = "144px";
				height = "40px";
				background = "#ffffff";
			}
			target.appendChild(dummy);
		}

	},
	*/

	initPromotions : function(items)
	{
		NGNB.clearXML(items);
		var len = items.length;
		var target = document.getElementById('ngnb-promotions');
		var add = function(item) {
			var infos = NGNB.clearXML(item.childNodes);
			var img = infos[0].firstChild.nodeValue.replace('http://', NGNB.http);
			var url = infos[1].firstChild.nodeValue;
			var desc = infos[2].firstChild.nodeValue;
			var method = infos[3] ? infos[3].firstChild.nodeValue : '';
			var span = document.createElement('span');
			span.innerHTML = '<a href="'+url+'" target="'+method+'"><img src="'+img+'" width="170" height="47" alt="" title="'+desc+'" /></a>';
			target.appendChild(span);
			span = null;
		}

		if (len == 1) {
			// 배너가 1개면 롤링 중지
			add(items[0]);
			return;
		} else {
			// 배너가 여러개일경우 자연스러운 롤링을 위해 첫번째 배너를 복사하여 마지막에 추가로 삽입
			for (var i = 0; i < len; i++) {
				add(items[i]);
			}
			add(items[0]);
		}

		var count = Math.ceil(target.scrollWidth / 170) , now = 1, sp, ep, loop;
		setInterval(function()
		{
			if (now == count) target.scrollLeft = 0, now = 1;
			ep = 170 * now++;
			loop = setInterval(function() {
				sp = target.scrollLeft;
				if (sp == ep) clearInterval(loop);
				target.scrollLeft += Math[sp < ep ? 'ceil' : 'floor']((ep-sp)/7);
			}, 15);
		}, 4000);

	}
};

NGNB.Write();