﻿(function ($) {
    $.fn.navBuilder = function (json, options) { //authored by Neil
        if (json === null) {// if json is null 
            return this;
        } //return selector unmolested
        var settings = $.extend({
            listID: null,
            buildMenu: true, // set to false if you only want to build list
            headerElement: $('<ul>').attr('id', 'main'),
            dropList: $('<ul>').attr('id', 'drop')
        }, options || {});
        function buildList(o, id) {
            var ul = $('<ul>');
            if (id) {
                ul.attr('id', id);
            }
            for (var a = 0; a < o.sub_categories.length; a++) {
                ul.append($('<li>').append($('<a>').attr('href', o.urls[a]).append($('<span>').text(o.sub_categories[a]))));
            }
            return ul;
        }
        function buildMenu(ob) {
            var head = settings.headerElement;
            var drop = settings.dropList;
            for (var a = 0; a < ob.length; a++) {
                var title = ob[a].main_category;
                head.append($('<li>').attr('id', ('n-' + title.toLowerCase())).append($('<a>').attr('href', ob[a].urls[0]).text(title)));
                drop.append($('<li>').attr('id', 'd-' + ob[a].main_category.toLowerCase()).append(buildList(ob[a])));
            }
            $(this).append(head).append(drop);
        }
        return this.each(function () {
            if (settings.buildMenu) {
                buildMenu.call(this, json);
                var list = settings.dropList;
            } else {
                $(this).append(buildList(json, settings.listID));
            }
        });
    };
    $.cookie = function (name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', (options.unescape == "true" ? value : encodeURIComponent(value)), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };
    $.fn.pager = function (options) {
        var o = $.extend({
            currentPage: 1,
            totalPages: 1,
            pagesToDisplay: 5
        }, options || {});
        return this.each(function (index) {
            if (index > 0 || o.totalPages == 1) { return false; }
            // image templates / bases
            var url = (location.href.indexOf('?') > 0 ? location.href.slice(0, location.href.indexOf('?')) : location.href) + '?page=';
            var imgSrcTemplate = { prefix: 'http://nxcache.nexon.net/vindictus/img/btn/pager', offSuffix: 'i.png', onSuffix: 'a.png' };
            var firstButton = $('<img>').attr('alt', 'First');
            var prev5Button = $('<img>').attr('alt', 'Prev5');
            var prevButton = $('<img>').attr('alt', 'Prev');
            var nextButton = $('<img>').attr('alt', 'Next');
            var next5Button = $('<img>').attr('alt', 'Next5');
            var lastButton = $('<img>').attr('alt', 'Last');
            var currentThreshold = Math.floor(o.currentPage / o.pagesToDisplay) * 5;
            var currentLastPage = o.totalPages > (currentThreshold + o.pagesToDisplay) ? currentThreshold + o.pagesToDisplay : o.totalPages;
            var currentFirstPage = currentThreshold + 1;
            var pager = $('<ul>').addClass('s-pager');
            ///complete image buttons
            if (o.currentPage != 1) {//set first and prev button
                firstButton.attr('src', imgSrcTemplate.prefix + '-first-' + imgSrcTemplate.onSuffix);
                firstButton = $('<a>').attr('href', url + '1').append(firstButton);
                prevButton.attr('src', imgSrcTemplate.prefix + '-prev-' + imgSrcTemplate.onSuffix);
                prevButton = $('<a>').attr('href', url + (parseInt(o.currentPage) - 1)).append(prevButton);
            }
            else {
                firstButton.attr('src', imgSrcTemplate.prefix + '-first-' + imgSrcTemplate.offSuffix);
                prevButton.attr('src', imgSrcTemplate.prefix + '-prev-' + imgSrcTemplate.offSuffix);
            }
            if (o.currentPage != o.totalPages) {
                nextButton.attr('src', imgSrcTemplate.prefix + '-next-' + imgSrcTemplate.onSuffix);
                nextButton = $('<a>').attr('href', url + (parseInt(o.currentPage) + 1)).append(nextButton);
                lastButton.attr('src', imgSrcTemplate.prefix + '-last-' + imgSrcTemplate.onSuffix);
                lastButton = $('<a>').attr('href', url + o.totalPages).append(lastButton);
            }
            else {
                nextButton.attr('src', imgSrcTemplate.prefix + '-next-' + imgSrcTemplate.offSuffix);
                lastButton.attr('src', imgSrcTemplate.prefix + '-last-' + imgSrcTemplate.offSuffix);
            }
            if (o.currentPage > o.pagesToDisplay) {
                prev5Button.attr('src', imgSrcTemplate.prefix + '-prev5-' + imgSrcTemplate.onSuffix);
                prev5Button = $('<a>').attr('href', url + (parseInt(o.currentPage) - 5)).append(prev5Button);
            }
            else
                prev5Button.attr('src', imgSrcTemplate.prefix + '-prev5-' + imgSrcTemplate.offSuffix);
            if (o.currentPage < (o.totalPages - 5)) {
                next5Button.attr('src', imgSrcTemplate.prefix + '-next5-' + imgSrcTemplate.onSuffix);
                next5Button = $('<a>').attr('href', url + (parseInt(o.currentPage) + 5)).append(next5Button);
            }
            else
                next5Button.attr('src', imgSrcTemplate.prefix + '-next5-' + imgSrcTemplate.offSuffix);
            pager.append($('<li>').append(firstButton).append(prev5Button).append(prevButton)); //first set of buttons
            for (var i = currentFirstPage; i <= currentLastPage; i++) {
                var li = $('<li>');
                if (i == o.currentPage)
                    li.text(i);
                else
                    li.append($('<a>').attr('href', url + i).text(i));
                pager.append(li);
            }
            pager.append($('<li>').append(nextButton).append(next5Button).append(lastButton)); //last set of buttons
            $(this).append(pager);
        });
    };
    $.fn.dataset = function (name, value) {
        var PREFIX = 'data-', PATTERN = /^data\-(.*)$/;
        if (value !== undefined) {
            // dataset(name, value): set the NAME attribute to VALUE.
            return this.attr(PREFIX + name, value);
        }
        switch (typeof name) {
            case 'string':
                // dataset(name): get the value of the NAME attribute.
                return this.attr(PREFIX + name);
            case 'object':
                // dataset(items): set the values of all (name, value) items.
                return this.each(function () {
                    for (var key in name)
                        $(this).attr(PREFIX + key, name[key]);
                });
                //                set_items.call(this, name);
            case 'undefined':
                // dataset(): return a mapping of (name, value) items for the
                // first element.
                var proc = function (index, attr, result) {
                    var match = PATTERN.exec(this.name);
                    if (match) result[match[1]] = this.value;
                };
                return this.fold((this.length > 0) && this[0].attributes, proc);
                //                return get_items.call(this);
            default:
                throw 'dataset: invalid argument ' + name;
        }
    };
    $.fn.removeDataset = function (obj) {
        var idx, length = obj && obj.length, PREFIX = 'data-';
        // For any object, remove attributes named by the keys.
        if (length === undefined) {
            for (idx in obj) {
                this.removeAttr(PREFIX + idx);
            }
        }
        // For an array, remove attributes named by the values.
        else {
            for (idx = 0; idx < length; idx++) {
                this.removeAttr(PREFIX + obj[idx]);
            }
        }
        return this;
    };
    /*
    * A left-fold operator. The behavior is the same as $.each(),
    * but the callback is called with the accumulator as the third
    * argument.  The default accumulator is an empty object.
    */
    $.fn.fold = function (object, proc, acc) {
        var length = object && object.length;
        // The default accumulator is an empty object.
        if (acc === undefined) acc = {};
        // Returning an empty accumulator when OBJECT is "false"
        // makes FOLD more composable.
        if (!object) return acc;
        // Check to see if OBJECT is an array.
        if (length !== undefined) {
            for (var i = 0, value = object[i];
	                (i < length) && (proc.call(value, i, value, acc) !== false);
	                value = object[++i])
            { }
        }
        // Object is a map of (name, value) items.
        else {
            for (var name in object) {
                if (proc.call(object[name], name, object[name], acc) === false) break;
            }
        }
        return acc;
    };
    // production team plugins
    $.popuphide = function () {
        $('#popup').hide();
        $('#popup-content').html('');
        $('#screen').fadeOut(200);
        $('#popup').removeClass();
        $('#popup').addClass('processed');
    };
    $.popupinit = function () {
        /* check if the popup exists and create it */
        if ($('#popup').length == 0) {
            $('body').append('<div id="popup">');
        }
        /* check if the screen exists and create it */
        if ($('#screen').length == 0) {
            $('body').append('<div id="screen">');
        }
        /* hide the popup */
        $('#screen, #popup').hide();
        /* check if the popup has been processed and process it */
        if (!$('#popup').hasClass('processed')) {
            $('#popup').html('<div id="popup-close"></div><div id="popup-content"></div>');
            $('#screen, #popup-close').click(function (e) {
                e.preventDefault();
                $.popuphide();
            });
            $('#popup').addClass('processed');
        }
    };
    $.messageinit = function (fn) {
        /* check if the popup exists and create it */
        if ($('#popup').length == 0) {
            $('body').append('<div id="popup">');
        }
        /* check if the screen exists and create it */
        if ($('#screen').length == 0) {
            $('body').append('<div id="screen">');
        }
        /* hide the popup */
        $('#screen, #popup').hide();
        /* check if the popup has been processed and process it */
        $('#popup').html('<div id="popup-close"></div><div id="popup-content"></div>');
        function callback(fn) {
            fn.apply(this);
            $.popuphide();
        }
        $('#screen, #popup-close').click(function (e) {
            e.preventDefault();
            callback(fn);
        });
        $('#popup').addClass('processed');
    };
    $.fn.popupimage = function (instant) {
        $.popupinit();
        return this.each(function () {
            $(this).click(function (e) {
                e.preventDefault();
                $('#popup').addClass('image');
                $('#popup').css({ top: $(document).scrollTop() + 100 });
                $('#popup-content').html($('<img>').attr('src', $(this).attr('href')));
                $('#screen, #popup').fadeIn(200);
                $('#popup-content img').load(function () {
                    $('#popup').css({ 'width': $(this).width(), 'margin-left': -($(this).width() / 2) - 4 });
                });
            });
            if (instant == true) {
                $(this).click();
            }
        });
    };
    $.fn.popupgallery = function () {
        $.popupinit();
        var index = this;
        return this.each(function () {
            $(this).click(function (e) {
                e.preventDefault();
                var i = $(index).index(this);
                var le = $(index).length;
                function currentImage() {
                    //$('#popup-content img').animate({'opacity':1},200,'linear',function(){
                    $('#popup-content img').load(sizeAndFade);
                    $('#popup-content img').attr('src', $(index).eq(i).attr('href'));
                    //});
                }
                function sizeAndFade() {
                    //$('#popup-content img').css({'opacity':0});
                    $('#popup').animate({ 'width': $(this).width(), 'margin-left': -($(this).width() / 2) - 4 }, 200, 'easeInOut');
                    //$('#popup').animate({'width':$(this).width(), 'margin-left':-($(this).width()/2) - 4}, 200, 'easeInOut', function(){
                    //$('#popup-content img').animate({'opacity':1},200);
                    //});
                }
                $('#popup').addClass('gallery');
                $('#popup').css({ top: $(document).scrollTop() + 100 });
                $('#screen, #popup').fadeIn(200);
                $('#popup-content').html('<a href="#" id="popup-prev"></a><img/><a href="#" id="popup-next"></a>');
                $('#popup-prev').click(function (ex) {
                    ex.preventDefault();
                    i = (i - 1 + le) % le;
                    $('#popup-content img').attr('src', $(index).eq(i).attr('href'));
                });
                $('#popup-next').click(function (ex) {
                    ex.preventDefault();
                    i = (i + 1) % le;
                    $('#popup-content img').attr('src', $(index).eq(i).attr('href'));
                });
                currentImage();
            });
        });
    };
    $.popupmessage = function (url, fn) {
        $.messageinit(typeof fn == 'function' ? fn : null);
        $('#popup-content').load(url, function (d) {
            $('#popup').addClass('message');
            $('#popup').css({ top: $(document).scrollTop() + 100 });
            $('#screen, #popup').fadeIn(200);
        });
    };

    /*added 02/01*/
//    $.fn.popupYoutube = function (url) {
//        $.popupinit();
//        $('#popup-content').load(url, function () {
//            $('#popup').addClass('youtube');
//            $('#popup').css({ top: $(document).scrollTop() + 100 });
//            $('#screen, #popup').fadeIn(200);
//        });
    //    }

    /************************* This should be placed in the main plugin.js *************************/
    // Used to display static popups with no flash embedded, just youtube vid
    $.fn.popupStaticTube = function (url, popupName) {
        $('#popup-content').load(url, function () {
            $('#popup').addClass(popupName);
            $('#popup').css({ top: $(document).scrollTop() + 100 });
            $('#screen, #popup').fadeIn(200);
        }
	)
    }
    // Simple tabs plugin
    $.fn.simpleTabs = function (passedTabLink) {
        // Hide all our tab content
        $('.content-holder').hide();

        // When tab is clicked...
        $('#tabs li').click(function () {
            if ($(this).is('li.active') || $(this).is('li.deactivate')) {
                console.log("Do nothing...");
            } else {
                $('.active').removeClass('active');
                $(this).addClass('active');
                $('.content-holder').hide();

                var showTabContent = $(this).attr('data-tab');
                $('#' + showTabContent).fadeIn();
            }
        });

		// Switch the tab based on the query string parameter
		if (passedTabLink != null) {
			$('.active').removeClass('active');
			$('#' + passedTabLink).fadeIn();
			
			// Highlight our tab by adding a class of active
			$('#tabs li[data-tab="' + passedTabLink + '"]').addClass('active');
		} else {
			$('#tabs li:first').addClass('active'); // Show our first tab and add a class of active
			//$('.content-holder').eq(0).show(); // Show our first tab content
			$('.content-holder:last').show(); // Show our last tab
		}
    }
    /********************************************* Cesar 10-5-2011 **************************************************/
    /* Variation of popupYoutube, it was modified to work with SWFObject plugin, added 05.24.11 */
    $.fn.popupSWFObject = function (url) {
        $.popupinit();
        $('#popup-content').load(url, function () {
            $('#popup').addClass('youtube');
            $('#popup').css({ top: $(document).scrollTop() + 100 });
            $('#screen, #popup').fadeIn(200);
            // Parameters for swfobject are set on the page
            $('#flash-movie').html(swfObjectVars);
        });
    } // End popupSWFObject plugin	
    $.fn.popupvideo = function (instant) {
        $.popupinit();
        return this.each(function () {
            $(this).click(function (e) {
                e.preventDefault();
                $('#popup').addClass('video');
                $('#popup').css({ top: $(document).scrollTop() + 100 });
                /* get height and width - use defaults if not set */
                var Vwidth = $(this).dataset('width') ? parseInt($(this).dataset('width')) : 640;
                var Vheight = $(this).dataset('height') ? parseInt($(this).dataset('height')) : 360;
                var Vflashvars = { videourl: $(this).attr('href') };
                if ($(this).dataset('image')) {
                    Vflashvars.imageurl = $(this).dataset('image');
                }
                var videoobject = $.flash.create({
                    swf: 'http://nxcache.nexon.net/vindictus/swf/flex-video-player.swf',
                    width: Vwidth,
                    height: Vheight,
                    params: { allowScriptAccess: "always", wmode: "transparent" },
                    flashvars: Vflashvars
                });
                $('#popup-content').html(videoobject);
                $('#screen, #popup').fadeIn(200);
                $('#popup').css({ 'width': Vwidth, 'margin-left': -(Vwidth / 2) - 4 });
            });
            if (instant == true) {
                $(this).click();
            }
        });
    };
    $.fn.clearform = function (options) {
        var s = $.extend({
            defaultValue: '' //the text to show to show
        }, options || {});
        return this.each(function () {
            $(this).val(s.defaultValue);
            $(this).focus(function () {
                var curVal = $(this).val().split(' ').join('');
                if (curVal == '') {
                    $(this).val('');
                }
                $(this).css('background-position', '100% 0');
            });
            $(this).blur(function () {
                var curVal = $(this).val().split(' ').join('');
                var defaultStripped = s.defaultValue.split(' ').join('');
                if (curVal == '' || curVal == defaultStripped) {
                    $(this).val(s.defaultValue);
                    $(this).css('background-position', '0 0');
                }
            });
        });
    };
    $.fn.charactercount = function (options) {
        var s = $.extend({
            maxchars: 3000,
            label: '#replace'
        }, options || {});
        return this.each(function () {
            var curcount;
            var newthis = this;
            check();
            function check() {
                curcount = $(newthis).val().length;
                $(s.label).html(curcount + ' / ' + s.maxchars + ' characters');
                if (curcount <= s.maxchars) {
                    $(s.label).removeClass('error');
                    $(newthis).removeClass('error');
                } else {
                    $(s.label).addClass('error');
                    $(newthis).addClass('error');
                }
            }
            $(this).keyup(function (e) {
                check();
            });
            $(this).mouseup(function (e) {
                check();
            });
            $(this).change(function (e) {
                check();
            });
        });
    };
    $.fn.tooltip = function (options) {
        var s = $.extend({
            defaultValue: '' //the text to show to show
        }, options || {});
        return this.each(function () {
            if ($('#tooltip').length == 0) {
                $('#nx-wrap').append('<div id="tooltip"></div>');
            }
            $(this).hover(function (e) {
                e.preventDefault();
                $('#tooltip').show().html($(this).attr('alt'));
                var os = $(this).offset();
                $('#tooltip').css({ width: 'auto', left: os.left + 14, top: os.top + 40 });
                var width = Math.min($('#tooltip').width(), 200);
                $('#tooltip').css({ width: width, 'margin-left': -width / 2 - 9 });
            }, function () {
                $('#tooltip').hide().html('');
            });
        });
    };
    $.fn.tabs = function (options) { //plugin start
        var s = $.extend({
            aclass: 'active',
            tcontent: 'overwriteme',
            callbacks: ['']
        }, options || {});
        var index = this;
        $(s.tcontent).hide();
        $(s.tcontent).eq(0).show();
        $(index).eq(0).addClass('active');
        return this.each(function () {
            $(this).click(function (e) {
                var i = $(index).index(this);
                e.preventDefault();
                $(index).removeClass(s.aclass);
                $(this).addClass(s.aclass);
                $(s.tcontent).hide();
                $(s.tcontent).eq(i).show();
                if (!!s.callbacks[i] || typeof s.callbacks[i] == 'function') {
                    s.callbacks[i]();
                }
            });
        });
    };
    $.fn.newsexpand = function (options) { //plugin start
        var s = $.extend({
            activeClass: 'expanded', //the text to show to show
            childExpander: '.expander' //the items to hide
        }, options || {});
        return this.each(function () {
            var parent = this;
            $(this).find(s.childExpander).click(function (e) {
                e.preventDefault();
                $(parent).toggleClass(s.activeClass);
            });
        });
    };
    $.fn.expand = function (options) { //plugin start
        var s = $.extend({
            oHeight: 0, //collapsed height
            eHeight: 0, //expanded height
            activeClass: ' ', //the text to show to show
            hideThese: '#overridethis', //the items to hide
            youtubeID: '', //ID of the video
            flashHere: '#overridethis', //where to add the flash
            expandThis: '#overridethis', //the items to expand
            timeout: 300, //animation time
            defaultShow: false//if set to true, the expanded view will be the default state
        }, options || {});
        return this.each(function () {
            var t;
            $(this).toggle(function (e) {
                function show() {
                    // setting autoplay off because a lightbox video is playing instead.
                    $(s.flashHere).flash({//load the Youtube video
                        swf: 'http://www.youtube.com/v/' + s.youtubeID + '?version=3',
                        width: 636,
                        height: 380,
                        flashvars: {
                            hd: 0,
                            rel: 0,
                            showsearch: 0,
                            showinfo: 0,
                            iv_load_policy: 3,
                            cc_load_policy: 0,
                            autoplay: 0, //change for lightbox 10-5-2011
                            fs: 1
                        },
                        allowFullScreen: 'true',
                        allowScriptAccess: 'always'
                    });
                    $(s.expandThis).stop().animate({ height: s.eHeight }, s.timeout, 'easeOut');
                    $('#m-introvideo, #m-dlsu').fadeIn(s.timeout);
                }
                e.preventDefault();
                $(s.hideThese).fadeOut(s.timeout);
                $(this).addClass(s.activeClass);
                clearTimeout(t);
                t = setTimeout(show, s.timeout);
            }, function (e) {
                function hide() {
                    $(s.hideThese).fadeIn(s.timeout);
                    $(s.flashHere).empty();
                }
                $(s.expandThis).stop().animate({ height: s.oHeight }, s.timeout, 'easeOut');
                $('#m-introvideo, #m-dlsu').fadeOut(s.timeout);
                e.preventDefault();
                $(this).removeClass(s.activeClass);
                clearTimeout(t);
                t = setTimeout(hide, s.timeout);
            });
            if (s.defaultShow) {
                $(s.expandThis).css({ height: s.eHeight });
                $(this).click();
            } else {
                $(s.expandThis).css({ height: s.oHeight });
                $(this).removeClass(s.activeClass);
            }
        });
    };
    $.fn.funexpand = function (options) { //plugin start
        var s = $.extend({
            oHeight: 145,
            eHeight: 29,
            expandThese: '#overridethis', //the items to expand
            timeout: 200 //animation time
        }, options || {});
        return this.each(function () {
            var t;
            $(this).toggle(function (e) {
                $(s.expandThese).stop().animate({ height: s.oHeight }, s.timeout);
            }, function (e) {
                $(s.expandThese).stop().animate({ height: s.eHeight }, s.timeout);
            });
        });
    };
    $.fn.sameheight = function (options) {
        var s = $.extend({
            child: 'ul'
        }, options || {});
        return this.each(function () {
            var endheight = 0;
            $(this).find(s.child).each(function (e) {
                endheight = Math.max($(this).height(), endheight);
            });
            $(this).find(s.child).height(endheight);
        });
    };
    $.fn.hoverdropdown = function (options) {
        var s = $.extend({
            oHeight: 0, //collapsed height
            eHeight: 400, //expanded height
            timeout: 100, //animation time
            expandThese: '#overridethis'
        }, options || {});
        return this.each(function () {
            $(s.expandThese).hide().css({ height: s.oHeight });
            $(this).hover(function (e) {
                e.preventDefault();
                $(s.expandThese).show().stop().animate({ height: s.eHeight }, s.timeout, 'easeOut');
            }, function (e) {
                e.preventDefault();
                $(s.expandThese).stop().animate({ height: s.oHeight + 'px' }, s.timeout, 'easeOut', function () { $(this).hide() });
            });
        });
    };
    $.fn.pseudohover = function (options) {
        var s = $.extend({
            hover: '#overridethis',
            pseudo: '#overridethis',
            className: ''
        }, options || {});
        return this.each(function () {
            var index = $(s.hover).index(this);
            $(this).hover(function (e) {
                e.preventDefault();
                $(s.pseudo).removeClass(s.className);
                $(s.pseudo).eq(index).addClass(s.className)
            }, function (e) {
                e.preventDefault();
                $(s.pseudo).removeClass(s.className);
            });
        });
    };
    $.fn.rotban = function (options) {
        var s = $.extend({
            slides: '#m-items-carousel li', //the jquery object of items
            slider: '#m-rotban-ban', //the jquery object of the container of the banners
            buttons: '#m-items-carousel li', //the jquery object of items
            fadetimeout: 500, //use this to control length of animation
            pausetimeout: 5000, //use this to control how long between timed animations
            activeclass: 'active', //use this to control how long between timed animations
            height: 164 //height of slide
        }, options || {});
        return this.each(function () {
            var t = setTimeout(nextslide, s.pausetimeout);
            var slide = 0;
            var prevslide = 0;
            var count = $(s.slides).length;
            displayslide(0);
            $(s.slider).height(s.height * count);
            $(s.buttons).click(function (e) {
                e.preventDefault();
                displayslide($(s.buttons).index(this));
            });
            function nextslide() {
                slide = (slide + 1) % count;
                displayslide(slide);
            }
            function displayslide(number) {
                slide = number;
                var prevSelected = $(s.slides).eq(prevslide);
                var selected = $(s.slides).eq(number);
                var button = $(s.buttons).eq(number);

                $(s.buttons).removeClass(s.activeclass);
                button.addClass(s.activeclass);

                $(s.slides).not(prevSelected).css({ opacity: 0 });
                prevSelected.removeClass(s.activeclass);
                selected.addClass(s.activeclass);

                prevslide = number;
                clearTimeout(t);
                selected.stop().fadeTo('slow', 1, function () {
                    t = setTimeout(nextslide, s.pausetimeout);
                });
            }
        });
    };

    $.fn.catban = function (options) {
        var s = $.extend({
            animtimeout: 800, //use this to control length of animation
            pausetimeout: 4000, //use this to control how long between timed animations
            slider: '#overridethis', //the thing that is slid
            controls: '#overridethis', //indexed buttons
            width: 260//height of slide
        }, options || {});
        return this.each(function () {
            var count = $(s.controls).length;
            var slide = 0;
            var t = setTimeout(nextslide, s.pausetimeout);
            function nextslide() {
                slide = (slide + 1) % count;
                gotoslide(slide);
            }
            function gotoslide(number) {
                clearTimeout(t);
                t = setTimeout(nextslide, s.pausetimeout + s.animtimeout);
                $(s.slider).stop().animate({ left: (-number * s.width) }, s.animtimeout);
                $(s.controls).removeClass('active');
                $(s.controls).eq(number).addClass('active');
            }
            $(s.controls).click(function (e) {
                e.preventDefault();
                slide = $(s.controls).index(this);
                gotoslide(slide);
            });
        });
    };

    $.fn.highlightcarousel = function (options) {
        var s = $.extend({
            slides: '#m-items-carousel li', //the jquery object of items
            animtimeout: 1000, //use this to control length of animation
            pausetimeout: 5600, //use this to control how long between timed animations
            nextbtn: '.next', //next button
            prevbtn: '.prev', //previous button
            slider: '.images', //the thing that is slid
            desc: true, //set to false to disable text details
            descholder: '#m-items-display-text',
            imgholder: '#m-items-display-image',
            newicon: '#m-items-new',
            width: 76//width of slide
        }, options || {});
        return this.each(function () {
            var count = $(s.slides).length;
            $(s.slider).width(s.width * count);
            var page = 0;
            var slide = 0;
            var t = setTimeout(nextslide, s.pausetimeout);
            displayslide(0);
            $(s.slides).click(function (e) {
                e.preventDefault();
                displayslide($(s.slides).index(this));
            });
            function nextpage() {
                if (page == count - 3) {
                    page = 0
                } else {
                    page = Math.min(count - 3, slide);
                }
                gotopage(page);
            }
            function nextslide() {
                if (slide == count - 1) {
                    slide = 0
                } else {
                    slide = Math.min(count - 1, slide + 1);
                }
                //slide = (slide+1)%count;
                if (slide > page + 2 || slide < page) {
                    nextpage();
                }
                displayslide(slide);
            }
            function displayslide(number) {
                slide = number;
                var selected = $(s.slides).eq(number);
                var imglink = selected.find('a').attr('href');
                var imgpath = selected.find('a').dataset('full');
                $(s.imgholder + ' img').attr('src', imgpath);
                $(s.imgholder).attr('href', imglink);
                $(s.descholder).attr('href', imglink);
                selected.addClass('active').siblings().removeClass('active');
                clearTimeout(t);
                t = setTimeout(nextslide, s.pausetimeout + s.animtimeout);
            }
            function gotopage(number) {
                clearTimeout(t);
                t = setTimeout(nextslide, s.pausetimeout + s.animtimeout);
                $(s.slider).stop().animate({ left: -number * s.width }, s.animtimeout);
            }
            $(s.nextbtn).click(function (e) {
                e.preventDefault();
                if (count > 3) {
                    page = Math.min(count - 3, page + 3);
                    gotopage(page);
                }
            });
            $(s.prevbtn).click(function (e) {
                e.preventDefault();
                if (count > 3) {
                    page = Math.max(0, page - 3);
                    gotopage(page);
                }
            });
        });
    };
    $.fn.simplecarousel = function (options) {
        var s = $.extend({
            slides: '#m-items-carousel li', //the jquery object of items
            animtimeout: 1000, //use this to control length of animation
            pausetimeout: 5600, //use this to control how long between timed animations
            nextbtn: '.next', //next button
            prevbtn: '.prev', //previous button
            indexbtns: '.index a', //previous button
            slider: '.images', //the thing that is slid
            width: 190 //width of slide including margins
        }, options || {});
        return this.each(function () {
            var count = $(s.slides).length;
            var page = 0;
            var slide = 0;
            var t = setTimeout(nextpage, s.pausetimeout);
            $(s.slider).css({ width: count * s.width });
            for (i = 0; i < Math.ceil(count / 3); i++) {
                $(s.indexbtns).append('<a href="#"></a>');
            }
            $(s.indexbtns + ' a').eq(0).addClass('active');
            function nextpage() {
                if (page == count - 3) {
                    page = 0;
                } else {
                    page = Math.min(count - 3, page + 3);
                }
                gotopage(page);
            }
            function gotopage(number) {
                clearTimeout(t);
                t = setTimeout(nextpage, s.pausetimeout + s.animtimeout);
                var cur = Math.ceil(number / 3);
                $(s.indexbtns + ' a').removeClass('active');
                $(s.indexbtns + ' a').eq(cur).addClass('active');
                $(s.slider).stop().animate({ left: -number * s.width }, s.animtimeout, 'easeOut');
            }
            $(s.nextbtn).click(function (e) {
                e.preventDefault();
                if (count > 3) {
                    page = Math.min(count - 3, page + 3);
                    gotopage(page);
                }
            });
            $(s.prevbtn).click(function (e) {
                e.preventDefault();
                if (count > 3) {
                    page = Math.max(0, page - 3);
                    gotopage(page);
                }
            });
            $(s.indexbtns + ' a').click(function (e) {
                e.preventDefault();
                var ind = $(s.indexbtns + ' a').index(this) * 3;
                page = Math.max(Math.min(ind, count - 3), 0);
                gotopage(page);
            });
        });
    };

    $.fn.hoverAccordion = function (options) {
        // Setup s
        s = jQuery.extend({
            speed: 'fast', // Speed at which the subitems open up - valid s are: slow, normal, fast
            activateitem: 'true', // 'true': Automatically activate items with links corresponding to the current page, '2': Activate item #2
            active: 'active', // Class name of the initially active element
            header: 'header', // Class name for header items
            hover: 'hover', // Class name for hover effect
            opened: 'opened', // Class name for open header items
            closed: 'closed', // Class name for closed header items
            keepheight: 'true' // 'true': Set the height of each accordion item to the size of the largest one, 'false': Leave height as is
        }, options || {});

        // Current hover status
        var thislist = this;
        // Current URL
        var thisurl = window.location.href;

        // Interval for detecting intended element activation
        var i = 0;

        // Change display status of subitems when hovering
        function doHover(obj) {
            if ($(obj).html() == undefined)
                obj = this;

            // Change only one display status at a time
            if (!thislist.is(':animated')) {
                var newelem = $(obj).parent().children('ul');
                var oldelem = $(obj).parent().parent().children('li').children('ul:visible');
                if (s.keepheight == 'true') {
                    thisheight = maxheight;
                }
                else {
                    thisheight = newelem.outerHeight();
                }

                // Change display status if not already open
                if (!newelem.is(':visible')) {
                    //newelem.children().hide();
                    newelem.animate({
                        height: thisheight
                    }, s.speed
                    ).show();

                    oldelem.animate({
                        height: 'hide'
                    }, s.speed
                    ).hide();

                    // Switch classes for headers
                    oldelem.parent().children('a').addClass(s.closed).removeClass(s.opened);
                    newelem.parent().children('a').addClass(s.opened).removeClass(s.closed);
                }
            }
        };

        var itemNo = 0;
        var maxheight = 0;

        // Setup initial state and hover events
        $(this).children('li').each(function () {
            var thisitem = $(this);

            itemNo++;

            // Set current link to current URL to 'active' and disable anchor links
            var thislink = thisitem.children('a');

            if (thislink.length > 0) {
                // Hover effect for all links
                thislink.hover(function () {
                    $(this).addClass(s.hover);
                }, function () {
                    $(this).removeClass(s.hover);
                });

                var thishref = thislink.attr('href');

                if (thishref == '#') {
                    // Add a click event if the header does not contain a link
                    thislink.click(function () {
                        doHover(this);
                        this.blur();
                        return false;
                    });
                }
                else
                    if (s.activateitem == 'true' && thisurl.indexOf(thishref) > 0 && thisurl.length - thisurl.lastIndexOf(thishref) == thishref.length) {
                        thislink.parent().addClass(s.active);
                    }
            }

            var thischild = thisitem.children('ul');

            // Initialize subitems
            if (thischild.length > 0) {
                if (maxheight < thischild.height())
                    maxheight = thischild.height();

                // Change appearance of the header element of the active item
                thischild.children('li.' + s.active).parent().parent().children('a').addClass(s.header);

                // Bind hover events to all subitems
                thislink.hover(function () {
                    var t = this;
                    i = setInterval(function () {
                        doHover(t);
                        clearInterval(i);
                    }, 200);
                }, function () {
                    clearInterval(i);
                });


                // Set current link to current URL to 'active'
                if (s.activateitem == 'true') {
                    thischild.children('li').each(function () {
                        var m = $(this).children('a').attr('href');
                        if (m) {
                            if (thisurl.indexOf(m) > 0 && thisurl.length - thisurl.lastIndexOf(m) == m.length) {
                                $(this).addClass(s.active).parent().parent().children('a').addClass(s.opened);
                            }
                        }
                    });
                }
                else
                    if (parseInt(s.activateitem) == itemNo) {
                        thisitem.addClass(s.active).children('a').addClass(s.opened);
                    }
            }

            // Close all subitems except for those with active items
            thischild.not($(this).parent().children('li.' + s.active).children('ul')).not(thischild.children('li.' + s.active).parent()).hide().parent().children('a').addClass(s.closed);
        });

        return this;
    };
    $.preLoadImages = function () {/*an image preloader, call the function preloadImages("urls here","image url here");*/
        var cache = [];
        var args_len = arguments.length;
        for (var i = args_len; i--; ) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        }
    };

    $.fn.login = function (options) { // authored by Neil
        var o = $.extend({
            loginCookieName: 'VinPassport',
            logoutSelector: '#m-start-welcome-logout',
            idSelector: '#m-start-id',
            passSelector: '#m-start-pw',
            rememberMeSelector: '#remember-me',
            submitSelector: '#m-start-submit',
            checkbox:
                { //default is CSS controlled checkbox. if checkbox is an input, these properties should be overwritten in plugin initializer 
                    isChecked: function () { return this.hasClass('checked'); },
                    toggle: function () { $(this).toggleClass('checked'); }
                },
            moduleURL: '/Modules/Passport.aspx',
            moduleSelector: '#module'
        }, options || {});
        var parent = $(this);
        var loadPath = o.moduleURL + ' ' + o.moduleSelector;
        function attachLogout() { //makes sure logout returns user to correct page from passport by setting cookie manually
            $(o.logoutSelector).click(function (e) {
                e.preventDefault();
                $.cookie("returnURL", location.href, { expires: 1, path: "/", domain: 'nexon.net', unescape: "true" });
                location.href = "javascript:nexon.sso.logout();";
            });
        }
        function startUpdateSession() {
            setTimeout(function () { doUpdateSession(); }, 1);
        }
        function loginLoad() {
            var id = $(o.idSelector);
            var pass = $(o.passSelector);
            var idAndPass = id.add(pass);
            var remember = $(o.rememberMeSelector);
            var otherInputs = $('input').not($(this).find('input').not('[disabled=true]'));
            var cookieName = o.loginCookieName;
            var loginCookie = $.cookie(cookieName);
            otherInputs.disabled = true;
            //these functions control the css display of id/pass inputs.
            idAndPass.attr('value', '').focus(function () {
                $(this).css('background-position', '100% 0');
            }).blur(function () {
                if ($(this).val().split(' ').join('') == '') {
                    $(this).val('').css('background-position', '0 0');
                }
            }).keydown(function (e) {
                if (e.keyCode == 13) {
                    e.preventDefault();
                    $(o.submitSelector).click();
                    return false;
                }
            });
            //check for cookie
            if (loginCookie !== null) {
                id.css('background-position', '100% 0').val(loginCookie);
                remember.click();
            }
            //attach event handler for checkbox
            remember.click(function (e) { o.checkbox.toggle.apply(this); }); //e.preventDefault(); removed for weird input handling
            //handle login submit
            $(o.submitSelector).click(function (e) {
                e.preventDefault();
                var alertStr = (pass.val().split(' ').join('') == '' ? 'Please enter your Password' :
                                (id.val().split(' ').join('') == '' ? 'Please input your ID' : ''));
                if (alertStr != '') {//make sure user has entered an ID and Password
                    alert(alertStr);
                    return false;
                }
                else {//submit info
                    $.ajax({
                        url: o.moduleURL,
                        type: 'POST',
                        data: { "tbID": id.val(), "tbPass": pass.val() }, // Passport.aspx should look for tbID and tbPass
                        datatype: 'html',
                        success: function (data) {
                            var alertData = data.split('<script type=\'text/javascript\'>');
                            if (alertData[1] !== undefined) {
                                alertData = alertData[1].split('</script>');
                                eval(alertData[0]);
                            }
                            else {
                                if (o.checkbox.isChecked.apply(remember)) {
                                    $.cookie(cookieName, id.val(), { expires: 365, path: '/', domain: 'nexon.net' });
                                }
                                else {
                                    $.cookie(cookieName, null, { path: '/', domain: 'nexon.net' });
                                }
                                /*var winnercheck = data.split('<input type="hidden" name="winnercheck" value="');
                                if (winnercheck[1] != undefined) {
                                winnercheck = winnercheck[1].split('"');
                                if (winnercheck[0] != '#' && $.cookie('viralbetaMessage') == null)
                                $.popupmessage(winnercheck[0], function() {
                                if ($('.checkbox input:checked').size() > 0)
                                $.cookie('viralbetaMessage', 'true', { expires: 365, path: '/', domain: 'nexon.net' });
                                else
                                $.cookie('viralbetaMessage', null, { path: '/', domain: 'nexon.net' });
                                });
                                }*/
                                parent.load(loadPath, function () {
                                    otherInputs.removeAttr('disabled');
                                    startUpdateSession();
                                    attachLogout();
                                    if ($("#forums").length > 0) {
                                        var src = $("#forum-frame").attr("src");
                                        $("#forum-frame").attr("src", src.substring(0, src.indexOf("#")));
                                    }
                                });
                            }
                        },
                        error: function (xhr) {
                            alert('I\'m sorry. There was an error. Please Try again later. ' + xhr.status + ' ' + xhr.statusText);
                        }
                    });
                    return false;
                }
            });
        }
        return this.each(function () {
            $.ajaxSetup({ cache: false });
            $(this).load(loadPath, function () {
                if (nexon.sso.isLoggedIn) {// loggedIn needs to be defined before plugins library is loaded
                    startUpdateSession();
                    attachLogout();
                }
                else {
                    loginLoad();
                }
            });
        });
    };
})(jQuery);
// easing
jQuery.extend(jQuery.easing,
{
    easeIn: function (x, t, b, c, d) {
        return c * (t /= d) * t * t * t * t + b;
    },
    easeOut: function (x, t, b, c, d) {
        return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
    },
    easeInOut: function (x, t, b, c, d) {
        if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b;
        return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
    }
});

// jQuery swfobject plugin //
(function (F, C) { var D = function (H) { var G, I = []; for (G in H) { if (/string|number/.test(typeof H[G]) && H[G] !== "") { I.push(G + '="' + H[G] + '"') } } return I[A]("") }, E = function (I) { var G, K, J = [], H; if (typeof I == "object") { for (G in I) { if (typeof I[G] == "object") { H = []; for (K in I[G]) { H.push([K, "=", encodeURIComponent(I[G][K])][A]("")) } I[G] = H[A]("&amp;") } if (I[G]) { J.push(['<param name="', G, '" value="', I[G], '" />'][A]("")) } } I = J[A]("") } return I }, B = false, A = "join"; F[C] = (function () { try { var G = "0,0,0", H = navigator.plugins["Shockwave Flash"] || ActiveXObject; G = H.description || (function () { try { return (new H("ShockwaveFlash.ShockwaveFlash")).GetVariable("$version") } catch (J) { } } ()) } catch (I) { } G = G.match(/^[A-Za-z\s]*?(\d+)[\.|,](\d+)(?:\s+[d|r]|,)(\d+)/); return { available: G[1] > 0, activeX: H && !H.name, version: { major: G[1] * 1, minor: G[2] * 1, release: G[3] * 1 }, hasVersion: function (K) { var N = this.version, L = "major", M = "minor", J = "release"; K = (/string|number/.test(typeof K)) ? K.toString().split(".") : K || [0, 0, 0]; K = [K[L] || K[0] || N[L], K[M] || K[1] || N[M], K[J] || K[2] || N[J]]; return (K[0] < N[L]) || (K[0] == N[L] && K[1] < N[M]) || (K[0] == N[L] && K[1] == N[M] && K[2] <= N[J]) }, expressInstall: "expressInstall.swf", create: function (J) { if (!F[C].available || B || !typeof J == "object" || !J.swf) { return false } if (J.hasVersion && !F[C].hasVersion(J.hasVersion)) { J = { swf: J.expressInstall || F[C].expressInstall, attrs: { id: J.id || "SWFObjectExprInst", name: J.name, height: Math.max(J.height || 137), width: Math.max(J.width || 214) }, params: { flashvars: { MMredirectURL: location.href, MMplayerType: (F[C].activeX) ? "ActiveX" : "PlugIn", MMdoctitle: document.title.slice(0, 47) + " - Flash Player Installation"}} }; B = true } else { J = F.extend(true, { attrs: { id: J.id, name: J.name, height: J.height || 180, width: J.width || 320 }, params: { wmode: J.wmode || "opaque", flashvars: J.flashvars} }, J) } if (F[C].activeX) { J.attrs.classid = J.attrs.classid || "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"; J.params.movie = J.params.movie || J.swf } else { J.attrs.type = J.attrs.classid || "application/x-shockwave-flash"; J.attrs.data = J.attrs.data || J.swf } return ["<object ", D(J.attrs), ">", E(J.params), "</object>"][A]("") } } } ()); F.fn[C] = function (G) { if (typeof G == "object") { this.each(function () { var I = document.createElement(C); var H = F[C].create(G); if (H) { I.innerHTML = H; if (I.childNodes[0]) { this.appendChild(I.childNodes[0]) } } }) } else { if (typeof G == "function") { this.find("object").andSelf().filter("object").each(function () { var I = this, H = "jsInteractionTimeoutMs"; I[H] = I[H] || 0; if (I[H] < 660) { if (I.clientWidth || I.clientHeight) { G.call(this) } else { setTimeout(function () { F(I)[C](G) }, I[H] + 66) } } }) } } return this } } (jQuery, "flash"));

