﻿var fun_stuff = {
    'sub_categories': ['Videos', 'Screenshots', 'Music', 'Wallpaper', 'Concept Art', 'Poll'],
    'urls': ['/funstuff/Videos', '/funstuff/Screenshots', '/funstuff/Music', '/funstuff/Wallpapers', '/funstuff/Concept', '/funstuff/Poll'],
    'track': "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.FunStuff.Heading');",
    'tracks': ["nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.FunStuff.Videos');",
               "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.FunStuff.Screenshots');",
               "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.FunStuff.Music');",
               "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.FunStuff.Wallpaper');",
               "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.FunStuff.ConceptArt');",
               "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.FunStuff.Poll');"]
};
var site_map = [
    {
        'main_category': 'news',
        'sub_categories': ['Announcements', 'Events', 'Community'],
        'urls': ['/News/list', '/News/list?boardNo=300', '/News/list?boardNo=1000'],
        'track': "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.News.Heading');",
        'tracks': ["nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.News.Announcements');",
                   "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.News.Events');",
                   "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.News.Community');"]
    },
    {
        'main_category': 'guides',
        'sub_categories': ['Game Info', 'Beginner\'s Guide', 'Game Guide'],
        'urls': ['/Guide/Index', '/Guide/Beginner_Interface', '/Guide/Game_Battle'],
        'track': "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Guide.Heading');",
        'tracks': ["nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Guide.GameInfo');",
                   "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Guide.BeginnersGuide');",
                   "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Guide.GameGuide');"]
    },
    {
        'main_category': 'community',
        'sub_categories': ['Forums', 'Fan Sites'],
        'urls': ['/Community/Index', '/Community/Fansite'],
        'track': "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Community.Heading');",
        'tracks': ["nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Community.AtlanticaForum');",
                   "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Community.FanSites');"]
    },
    {
        'main_category': 'rankings',
        'sub_categories': ['Free League'],
        'urls': ['/Ranking/Ranking'],
        'track': "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Community.Ranking.Heading');",
        'tracks': ["nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Community.FreeLeague');"]
    },
    {
        'main_category': 'items',
        'sub_categories': ['Item Mall', 'Item Mall Guide', 'NX Guide', 'Review Purchases'],
        'urls': ['/Itemmall/Index', '/Itemmall/Guide', 'http://www.nexon.net/nx/guide/', 'http://www.nexon.net/nx/review-purchases/'],
        'track': "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.ItemMall.Heading');",
        'tracks': ["nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.ItemMall.ItemMall');",
                   "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.ItemMall.ItemMallGuide');",
                   "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.ItemMall.NxGuide');",
                   "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.ItemMall.ReviewPurchases');"]
    },
    {
        'main_category': 'support',
        'sub_categories': ['Account Migration', 'Client Download', 'Customer Support','FAQ', 'Game Policy', 'Security'],
        'urls': ['/Support/Migration', '/Support/Download', 'http://support.nexon.net','/Support/Faq', '/Support/Policy', '/Support/Security'],
        'track': "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Support.Heading');",
        'tracks': ["nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Support.AccountMigration');",
                   "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Support.ClientDownload');",
                   "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Support.CustomerSupport');",
                   "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Support.FAQ');",
                   "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Support.GamePolicy');",
                   "nexon.ga.recordOutboundLink(this, event, 'Navigation_Tracking', 'AO_Menu.Support.Security');"]
    }
];

function globalNavDropDown() {/*create a function to animate the main dropdown menu*/
    var animationMilliseconds = 300,
		nav = $('#nav'),
		drop = $('#drop'),
		main = $('#main li'),
		height = 0;
    /* show the drop and move it off screen */
    drop.show().css('left', -5000);
    /* get heights of the children and bind hover */
    drop.children('li').each(function (i) {
        var mainLI = main.eq(i);
        height = Math.max(height, $(this).height());
        $(this).bind('mouseenter', function () {
            main.removeClass('hover');
            mainLI.addClass('hover');
        });
        $(this).bind('mouseleave', function () {
            main.removeClass('hover');
        });
    });
    /* set heights of the children */
    drop.children('li').height(height);
    /* now use the height var for the height of the drop */
    height = drop.height()-57;
    drop.css({ 'height': 0, 'left': 0 });
    /* rollover state */
    nav.bind('mouseenter', function () {
        drop.stop().animate({ 'height': height }, animationMilliseconds);
    });
    nav.bind('mouseleave', function () {
        drop.stop().animate({ 'height': 0 }, animationMilliseconds);
    });
}
function globalFunStuffDropDown() {/*create a function for the FunStuff button*/
    var expander = $('#fun'),
		trigger = $('#fun-exp'),
		links = $('#fun-links'),
		lastLeft = expander.css('left'),
		closedHeight = expander.height(),
		listHeight = (links.height() / 2),
		openHeight = 0;
    /* show the expander and move it off screen */
    expander.css({ left: -5000, height: 'auto' });
    /* get the height */
    openHeight = 132;
    /* move the expander back and reset the height */
    expander.css({ left: lastLeft, height: closedHeight });
    trigger.click(function (e) {
        e.preventDefault();
        if (expander.hasClass('open')) {
            /* close the item */
            expander.removeClass('open').stop().animate({ height: closedHeight }, 200);
            //links.animate({opacity:0},500);
        } else {
            /* open the item */
            expander.addClass('open').stop().animate({ height: openHeight }, 200);
            //links.animate({opacity:1}, 500);
        }
    });
}
function globalLegal() {/*the legal links should open in fixed size windows. This function handles this behavior*/
    $('#legal .legal-popup').click(function (e) {
        e.preventDefault();
        var newWin = window.open($(this).attr('href'), 'legal', 'width=600, height=400, resizable=no, scrollbars=yes');
        if (!newWin) {
            alert("Your browser's pop-up blocker is currently enabled. If you wish to view the legal information, please disable the pop-up blocker temporarily and try again. Thank you.");
        }
    });
}

//Boring, reusable, external plugins below
jQuery.extend(jQuery.easing,
{
    easeInOut: function (x, t, b, c, d) {
        if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b;
        return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
    },
    easeIn: function (x, t, b, c, d) {
        return c * (t /= d) * t * t * t + b;
    },
    easeOut: function (x, t, b, c, d) {
        return -c * ((t = t / d - 1) * t * t * t - 1) + b;
    }
});

/*
* jQuery SWFObject v1.1.1 MIT/GPL @jon_neal
* http://jquery.thewikies.com/swfobject
*/

(function ($, flash, Plugin) {
    var OBJECT = 'object',
		ENCODE = true;

    function _compareArrayIntegers(a, b) {
        var x = (a[0] || 0) - (b[0] || 0);

        return x > 0 || (
			!x &&
			a.length > 0 &&
			_compareArrayIntegers(a.slice(1), b.slice(1))
		);
    }

    function _objectToArguments(obj) {
        if (typeof obj != OBJECT) {
            return obj;
        }

        var arr = [],
			str = '';

        for (var i in obj) {
            if (typeof obj[i] == OBJECT) {
                str = _objectToArguments(obj[i]);
            }
            else {
                str = [i, (ENCODE) ? encodeURI(obj[i]) : obj[i]].join('=');
            }

            arr.push(str);
        }

        return arr.join('&');
    }

    function _objectFromObject(obj) {
        var arr = [];

        for (var i in obj) {
            if (obj[i]) {
                arr.push([i, '="', obj[i], '"'].join(''));
            }
        }

        return arr.join(' ');
    }

    function _paramsFromObject(obj) {
        var arr = [];

        for (var i in obj) {
            arr.push([
				'<param name="', i,
				'" value="', _objectToArguments(obj[i]), '" />'
			].join(''));
        }

        return arr.join('');
    }

    try {
        var flashVersion = Plugin.description || (function () {
            return (
				new Plugin('ShockwaveFlash.ShockwaveFlash')
			).GetVariable('$version');
        } ())
    }
    catch (e) {
        flashVersion = 'Unavailable';
    }

    var flashVersionMatchVersionNumbers = flashVersion.match(/\d+/g) || [0];

    $[flash] = {
        available: flashVersionMatchVersionNumbers[0] > 0,

        activeX: Plugin && !Plugin.name,

        version: {
            original: flashVersion,
            array: flashVersionMatchVersionNumbers,
            string: flashVersionMatchVersionNumbers.join('.'),
            major: parseInt(flashVersionMatchVersionNumbers[0], 10) || 0,
            minor: parseInt(flashVersionMatchVersionNumbers[1], 10) || 0,
            release: parseInt(flashVersionMatchVersionNumbers[2], 10) || 0
        },

        hasVersion: function (version) {
            var versionArray = (/string|number/.test(typeof version))
				? version.toString().split('.')
				: (/object/.test(typeof version))
					? [version.major, version.minor]
					: version || [0, 0];

            return _compareArrayIntegers(
				flashVersionMatchVersionNumbers,
				versionArray
			);
        },

        encodeParams: true,

        expressInstall: 'expressInstall.swf',
        expressInstallIsActive: false,

        create: function (obj) {
            var instance = this;

            if (
				!obj.swf ||
				instance.expressInstallIsActive ||
				(!instance.available && !obj.hasVersionFail)
			) {
                return false;
            }

            if (!instance.hasVersion(obj.hasVersion || 1)) {
                instance.expressInstallIsActive = true;

                if (typeof obj.hasVersionFail == 'function') {
                    if (!obj.hasVersionFail.apply(obj)) {
                        return false;
                    }
                }

                obj = {
                    swf: obj.expressInstall || instance.expressInstall,
                    height: 137,
                    width: 214,
                    flashvars: {
                        MMredirectURL: location.href,
                        MMplayerType: (instance.activeX)
							? 'ActiveX' : 'PlugIn',
                        MMdoctitle: document.title.slice(0, 47) +
							' - Flash Player Installation'
                    }
                };
            }

            attrs = {
                data: obj.swf,
                type: 'application/x-shockwave-flash',
                id: obj.id || 'flash_' + Math.floor(Math.random() * 999999999),
                width: obj.width || 320,
                height: obj.height || 180,
                style: obj.style || ''
            };

            ENCODE = typeof obj.useEncode !== 'undefined' ? obj.useEncode : instance.encodeParams;

            obj.movie = obj.swf;
            obj.wmode = obj.wmode || 'opaque';

            delete obj.fallback;
            delete obj.hasVersion;
            delete obj.hasVersionFail;
            delete obj.height;
            delete obj.id;
            delete obj.swf;
            delete obj.useEncode;
            delete obj.width;

            var flashContainer = document.createElement('div');

            flashContainer.innerHTML = [
				'<object ', _objectFromObject(attrs), '>',
				_paramsFromObject(obj),
				'</object>'
			].join('');

            return flashContainer.firstChild;
        }
    };

    $.fn[flash] = function (options) {
        var $this = this.find(OBJECT).andSelf().filter(OBJECT);

        if (/string|object/.test(typeof options)) {
            this.each(
				function () {
				    var $this = $(this),
						flashObject;

				    options = (typeof options == OBJECT) ? options : {
				        swf: options
				    };

				    options.fallback = this;

				    flashObject = $[flash].create(options);

				    if (flashObject) {
				        $this.children().remove();

				        $this.html(flashObject);
				    }
				}
			);
        }

        if (typeof options == 'function') {
            $this.each(
				function () {
				    var instance = this,
					jsInteractionTimeoutMs = 'jsInteractionTimeoutMs';

				    instance[jsInteractionTimeoutMs] =
						instance[jsInteractionTimeoutMs] || 0;

				    if (instance[jsInteractionTimeoutMs] < 660) {
				        if (instance.clientWidth || instance.clientHeight) {
				            options.call(instance);
				        }
				        else {
				            setTimeout(
								function () {
								    $(instance)[flash](options);
								},
								instance[jsInteractionTimeoutMs] + 66
							);
				        }
				    }
				}
			);
        }

        return $this;
    };
} (
	jQuery,
	'flash',
	navigator.plugins['Shockwave Flash'] || window.ActiveXObject
));

// down stuff from Vindictus
function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        if (pair[0] == variable) { return pair[1]; }
    }
    return null;
}

var formatImageName = function (string) {//returns a string in lowercase, without apostrophes, and with hyphens replacing whitespace and underscores
    var regExp = /\s|[_]/g;
    var regExp2 = /[^\w_]/g;
    var str = string.toLowerCase().replace(regExp, "-").replace(regExp2, "-");
    return str;
};
function getCookie(c_name) { //relies on cookie plugin
    return $.cookie(c_name) !== null ? $.cookie(c_name) : "";
}
function getDownloadLinks(callback) {
    var downloadUrl = 'http://nxcache.nexon.net/atlantica/js/download_data.js';
    return $.getScript(downloadUrl, function () {
        if (typeof dl == 'undefined') {
            dl = { LiteLink: "#", FullLink: "#" };
        }
        callback.apply(dl);
    });
}
function startGameCheck() {
    $.getScript('http://nxcache.nexon.net/publisher/atlantica/publisher_start_game.js', function () {
        if (typeof DATA_start_game == 'undefined') { return false; }
        var d = DATA_start_game;
        if (d[0].content_category == '3' || (d[0].content_category == '1' && d[0].progress_type == '1')) {
            $('#m-play').addClass('maintenance')
        }
    });
}
function NxLanuchGame() {
    _gaq = (typeof _gaq != "undefined") ? _gaq : [];
    _gaq.push(["sdt._trackEvent", "AtlWebLaunch", "StartGame"]);
    _gaq.push(["cdt._trackEvent", "AtlWebLaunch", "StartGame"]);
    nexon.play("33587714");
}
function DownloadGame() {
    getDownloadLinks(function () { location.href = this.pandoLink; });
}
function ManualDownload() {
    getDownloadLinks(function () { location.href = this.manualLink; });
}
function NxLaunchGameMain() {
    $.getScript('http://nxcache.nexon.net/publisher/atlantica/publisher_start_game.js', function () {
        if (typeof DATA_start_game == 'undefined') { return false; }
        var d = DATA_start_game;
        var arg = "";
        switch (d[0].content_category) {
            case '1':
                if (d[0].progress_type != '1') {
                    //CheckLoginAndGameStart();
                    NxLanuchGame();
                }
                else {
                    alert(d[0].content_title);
                }
                break;
            case '2':
                //CheckLoginAndGameStart();
                NxLanuchGame();
                break;
            case '3':
                alert(d[0].content_title);
                break;
        }
    });
}

function UpdateLogin() {
    $.ajax({
        type: "POST",
        url: "/WebService/LoggedIn.asmx/LoggedInCheck",
        dateType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            var json = (typeof response.d) == 'string' ? eval('(' + response.d + ')'): response.d;

            switch(json.response_code){
                case 0:
                    loggedIn = json.data.logginResult;
                    break;
                default:
                    alert(json.response_message);
            }
        },
        fail: function (msg) {
            alert('Query failed!');
        }
    });
}

function UpdateNXBalance() {
    if ($('#m-nx-info').length <= 0) return;
    $.ajax({
        type: "POST",
        url: "/WebService/Billing.asmx/GetNXBalance",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            var json = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

            switch (json.response_code) {
                case 0:
                    var nCredit = json.data.nCredit;
                    var nPrepaid = json.data.nPrepaid;
                    $('.pre-login').addClass('dn');
                    $('.post-login').removeClass('dn');
                    //$('.post-login input:eq(0)').val(addCommas(nPrepaid));
                    //$('.post-login input:eq(1)').val(addCommas(nCredit));
                    $('#prepaid').text(addCommas(nPrepaid));
                    $('#credit').text(addCommas(nCredit));
                    break;
                case 10:
                    $('.pre-login').removeClass('dn');
                    $('.post-login').addClass('dn');
                    break;
                default:
                    alert(json.response_message);
            }
        },
        fail: function (msg) {
            alert('Query failed!');
        }
    });
}

function addCommas(input) {
    var x, x1, x2, rgx = /(\d+)(\d{3})/;
    input += '';
    x = input.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function globalLoad() {
    startGameCheck();
    $("#m-play").bind('click', function (e) {
        e.preventDefault();
        NxLaunchGameMain();
    });
    $('#nxlinks-games').flash({ swf: 'http://nxcache.nexon.net/vindictus/swf/m-nxlinks-games.swf', width: 259, height: 55, params: { allowScriptAccess: "always", wmode: "transparent"} });
    $('#nxlinks-cards').flash({ swf: 'http://nxcache.nexon.net/vindictus/swf/m-nxlinks-cards.swf', width: 259, height: 55, params: { allowScriptAccess: "always", wmode: "transparent"} });
    $('#m-crumb span:last').addClass('active');
}
