var mintroflash = $.flash.create({ swf: 'http://nxcache.nexon.net/dungeonfighter/swf/default-videoplayer.swf', width: 452, height: 251, params: { allowScriptAccess:

"always"
}, flashvars: { videourl: 'http://nxcache.nexon.net/dungeonfighter/video/default.flv', imageurl:

'http://nxcache.nexon.net/dungeonfighter/video/default.jpg'
}
});
var initialCookie = $.cookie("DFOInitial");
if (getQueryVariable('intro') == 'false')
    initialCookie = 'false';
function checkPartnerKey() {
    var pk = getQueryVariable('PARTNERKEY');
    if (pk != null) {
        $.cookie('PARTNERKEY', pk, { expires: 7, path: '/', domain: 'nexon.net' });
    }
}
function getClass(num, n) {
    if (typeof n == 'undefined') { n = false; }
    switch (num) {
        case "1":
            return n ? "slayer_" : "Slayer";
        case "2":
            return n ? "fighter_" : "Fighter";
        case "3":
            return n ? "gunner_" : "Gunner";
        case "4":
            return n ? "mage_" : "Mage";
        case "5":
            return n ? "priest_" : "Priest";
        case "8":
            return n ? "femalegunner_" : "FemaleGunner";
        case "9":
            return n ? "thief_" : "Thief";
        default:
            return "";
    }
}
function getBoardNo(directory, category) {
    switch (directory) {
        case "116":
            return "101";
        case "117":
            return "102";
        case "118":
        case "136":
            return "200";
        case "183":
            return "103";
        case "184":
            switch (category) {
                case "1":
                    return "600";
                case "2":
                    return "601";
                case "3":
                case "6":
                    return "602";
                case "4":
                case "5":
                    return "603";
            };
            break;
    }
}
function heroBanner() {
    $.getJSON('JS/publisher_hero_banner.js', function (d) {
        $('#m-rotban').append($('<ul>').attr('id', 'm-rotban-ban')).append($('<ul>').attr('id', 'm-rotban-btn'));
        var slides = $('#m-rotban-ban');
        var controls = $('#m-rotban-btn');
        for (var i = 0; i < d.length; i++) {
            var _class = i === 0 ? 'active' : '';
            var url = d[i].href.indexOf('http://dungeonfighter.nexon.net') > -1 ? '.' + d[i].href.slice(31) : d[i].href; 
            slides.append($('<li>').append($('<a>').attr({ href: url, target: d[i].target }).append($('<img>').attr({ src: d[i].imgSrc, alt: d[i].alt }))));
            controls.append($('<li>').addClass('btn' + (i + 1)).append($('<a>').attr('href', '#').addClass(_class).append($('<span>').text(i + 1))));
        }
        $('#m-rotban').rotban({
            slides: '#m-rotban-ban li', //the jquery object of items
            buttons: '#m-rotban-btn li a', //the jquery object of items
            fadetimeout: 500, //use this to control length of animation
            pausetimeout: 5600, //use this to control how long between timed animations
            activeclass: 'active'//use this to control how long between timed animations
        });
    });
}
function rankings() {
    $.getJSON('JS/publisher_ArenaRankings.js', function (d) {
        var divEl2 = $('<div>').addClass('dn');
        divEl2.append($('<img>').attr({ src: 'http://nxcache.nexon.net/dungeonfighter/img/home/rankings/m-rankings-thumb-' + d[0].cclass + '.png', alt: ' ' }));
        var table1 = $('<table>').addClass('m-rankings-specs');
        table1.append($('<tr>').html('<th>Rank :</th><td class="c-ltblue">1</td>'));
        table1.append($('<tr>').html('<th>Character :</th><td class="c-tan">' + d[0].name + '</td>'));
        table1.append($('<tr>').html('<th>Win Rate :</th><td>' + d[0].level + '%</td>'));
        //table1.append($('<tr>').html('<th>Class :</th><td>' + getClass(d[0].cclass) + '</td>'));
        table1.append($('<tr>').html('<th>Class :</th><td>' + d[0].job_name + '</td>'));
        table1.append($('<tr>').html('<th>Arena pts. :</th><td>' + commaFormat(d[0].exp) + '</td>'));
        divEl2.append(table1);
        var table2 = $('<table>').addClass('m-rankings-top5').html('<colgroup><col style="width:15px;" /><col style="width:45px;" /><col style="width:20px;" /><col style="width:20px;" /></colgroup><tr><th>Rank</th><th>Character</th><th>Win Rate</th><th>Class</th></tr>');
        for (var i = 1; i < 5; i++) {
            //var trEl = $('<tr>').html('<td class="c-ltblue">' + d[i].rank + '</td><td class="c-tan">' + d[i].name + '</td><td>' + d[i].level + '%</td><td>' + getClass(d[i].cclass) + '</td>');
            var trEl = $('<tr>').html('<td class="c-ltblue">' + d[i].rank + '</td><td class="c-tan">' + d[i].name + '</td><td>' + d[i].level + '%</td><td>' + d[i].job_name + '</td>');
            table2.append(trEl);
        }
        divEl2.append(table1).append(table2).appendTo('#m-rankings-details');
        $('#m-rankings-tabs a').tabs({
            tabs: '#m-rankings-details > div'
        });

        $.getJSON('JS/publisher_DungeonRankings.js', function (d) {
            var divEl = $('<div>');
            $(divEl).css("display", "none");
            divEl.append($('<img>').attr({ src: 'http://nxcache.nexon.net/dungeonfighter/img/home/rankings/m-rankings-thumb-' + d[0].cclass + '.png', alt: ' ' }));
            var table1 = $('<table>').addClass('m-rankings-specs');
            table1.append($('<tr>').html('<th>Rank :</th><td class="c-ltblue">1</td>'));
            table1.append($('<tr>').html('<th>Character :</th><td class="c-tan">' + d[0].name + '</td>'));
            table1.append($('<tr>').html('<th>Level :</th><td>' + d[0].level + '</td>'));
            //table1.append($('<tr>').html('<th>Class :</th><td>' + getClass(d[0].cclass) + '</td>'));
            table1.append($('<tr>').html('<th>Class :</th><td>' + d[0].job_name + '</td>'));
            table1.append($('<tr>').html('<th>EXP pts. :</th><td>' + commaFormat(d[0].exp) + '</td>'));
            divEl.append(table1);
            var table2 = $('<table>').addClass('m-rankings-top5').html('<colgroup><col style="width:15px;" /><col style="width:45px;" /><col style="width:20px;" /><col style="width:20px;" /></colgroup><tr><th>Rank</th><th>Character</th><th>Level</th><th>Class</th></tr>');
            for (var i = 1; i < 5; i++) {
                //var trEl = $('<tr>').html('<td class="c-ltblue">' + d[i].rank + '</td><td class="c-tan">' + d[i].name + '</td><td>' + d[i].level + '</td><td>' + getClass(d[i].cclass) + '</td>');
                var trEl = $('<tr>').html('<td class="c-ltblue">' + d[i].rank + '</td><td class="c-tan">' + d[i].name + '</td><td>' + d[i].level + '</td><td>' + d[i].job_name + '</td>');
                table2.append(trEl);
            }
            divEl.append(table1).append(table2).appendTo('#m-rankings-details');

        });
    });
}
function sortEffectiveDate(a, b) {
    var a = new Date(a.effective_start_datetime),
        b = new Date(b.effective_start_datetime);
    return (b.getTime() - a.getTime());
}
function loadEvent() {
    $.getJSON('JS/publisher_110.js', function (d) {
        //d = d.sort(sortEffectiveDate);
        var ulEl = $('<ul>').attr('id', 'm-news-items');
        for (var i = 0; i < 10; i++) {
            var liEl = $('<li>');
            var contentTitle = d[i].content_title.length > 60 ? (d[i].content_title.slice(0, 56) + '...') : d[i].content_title;
            liEl.append('<a href="#" class="expander"></a><span class="type-' + (d[i].category_name.toLowerCase()).replace(' ', '') + '"></span>');

            var articleUrl = "http://dungeonfighter.nexon.net/" + (d[i].directory_no.toString() == "184" ? 'Magazine' : 'News') + '/Content.aspx?boardNo=' + getBoardNo(d[i].directory_no, d[i].content_category) + '&contentNo=' + d[i].content_no;

            //var content = $('<div>').addClass('content').html('<h3>' + contentTitle + '</h3><div class="date">' + d[i].effective_start_datetime + '</div>');
            var content = $('<div>').addClass('content').html('<h3><a href="' + articleUrl + '">' + contentTitle + '</a></h3><div class="date">' + d[i].effective_start_datetime + '</div>');

            var shareCode = '<a name="fb_share" type="button_count" share_url="' + articleUrl + '"></a>';
            var share = $('<div>').addClass('share').html((d[i].directory_no.toString() == "183" ? '' : shareCode));
            var splashImage = d[i]['articleImage'];
            var img = (splashImage == "" ? '' : $("<img>").addClass('img').attr("src", splashImage));
            var imghref = $('<a>').attr("href", articleUrl).html(img);
            var summary = $('<div>').addClass('summary');
            var blurb = $('<a>').attr("href", articleUrl).html( //ie8 was doing something funky so break this out
					(d[i].summary_text.length > 200 ? (d[i].summary_text.slice(0, 196) + '...') : d[i].summary_text)
				);


            var readmore = $('<a>').attr("href", articleUrl).addClass('readmore').html("&gt;&nbsp;Read&nbsp;more");
            summary.append(imghref).append(blurb).append(readmore); 
            content.append(share).append(summary);

            if (d[i].expand_content.toString() == "1" || i == 0) { liEl.addClass('expanded'); }
            liEl.append(content).appendTo(ulEl);
        }
        ulEl.find('li:first').addClass('first');
        ulEl.find('li:last').addClass('last');
        //$('#m-news-footer').before(ulEl);
        $('#m-news-key').before(ulEl);
        $('#m-news-items li').newsexpand({ childExpander: '.expander' });
        $('<script>').attr({ type: 'text/javascript', src: 'http://static.ak.fbcdn.net/connect.php/js/FB.Share' }).appendTo('body');
    });
}

function loadNews() {
    $.getJSON('JS/publisher_100.js', function (d) {
        var ulEl = $('<ul>').attr('id', 'm-notice-items');
        for (var i = 0; i < 6; i++) {
            var liEl = $('<li>');
            var contentTitle = d[i].content_title.length > 35 ? (d[i].content_title.slice(0, 31) + '...') : d[i].content_title;
            var articleUrl = "http://dungeonfighter.nexon.net/" + (d[i].directory_no.toString() == "184" ? 'Magazine' : 'News') + '/Content.aspx?boardNo=' + getBoardNo(d[i].directory_no, d[i].content_category) + '&contentNo=' + d[i].content_no;
            var title = $('<div>').addClass('title').html('<span class="type-' + d[i].category_name.toLowerCase() + '"></span><a href="' + articleUrl + '">' + contentTitle + '</a>' + ((d[i].isNew == "1") ? '<span class="m-notice-icon"></span>' : ''));
            liEl.append(title).appendTo(ulEl);
        }
        ulEl.find('li:first').addClass('first');
        ulEl.find('li:last').addClass('last');
        $('#m-notice').append(ulEl);
    });
}

function loadKeyword() {
    $.getJSON('JS/publisher_keyword.js', function (d) {
        var keyword = $('#m-news-keyword');
        var html = "";
        for (var i = 0; i < d.length; i++) {
            if (i != 0)
                html += ", ";
            html += '<a href="' + d[i].url + '" >' + d[i].context.replace("?", "") + '</a>';
        }
        keyword.html(html);
    });
}

function pollImage() {
    $.getJSON('JS/publisher_poll_image.js', function (d) {
        if (d.imgUrl != '#') {
            $('#m-poll').css('backgroundImage', 'url(' + d.imgUrl + ')');
        }
    });
}
function createThumbs(JSON) {
    var ul = $('<ul>');
    var j = JSON.items;
    for (var i = 0; i < j.length; i++) {
        var li = $('<li>');
        var anchor = $('<a>').addClass('hzbtn').attr('href', '/ItemShop/Detail.aspx?order=' + j[i].order_no + '&cat=' + j[i].category + '&subCat=-1&class=' + j[i].sales_type);
        var imgSrc = 'http://nxcache.nexon.net/dungeonfighter/img/home/featured/featured_' + getClass(j[i].sales_type, true) + formatImageName(j[i].name) + '_tn.png';
        var div = $('<div>').addClass('dn').html('<strong>' + getClass(j[i].sales_type) + '</strong><br />' + j[i].name);
        anchor.append($('<img>').attr({ src: imgSrc, alt: imgSrc.replace('_tn.png', '.png'), width: '63', height: '36' }));
        anchor.appendTo(li);
        div.appendTo(li);
        li.appendTo(ul);
    }
    return ul;
}
function featuredItems() {
    $.getJSON('JS/publisher_featured_items.js', function (d) { // featured items
        $('#m-feat-items').append(createThumbs(d));
        $('#m-feat-items').highlightcarousel({
            slides: '#m-feat-items li',
            animtimeout: 1000,
            pausetimeout: 5600,
            nextbtn: '#m-feat-right',
            prevbtn: '#m-feat-left',
            slider: '#m-feat-items ul',
            classholder: '#m-feat-detail',
            descholder: '#m-feat-detail-text',
            imgholder: '#m-feat-detail-img',
            width: 77
        });
    });
}

function showHeaderTeaser() {
    $('#m-header').css({ height: 380 });
    $('#m-rotban').hide();
    $('#m-headerteaser').show();
}
function hideHeaderTeaser() {
    $('#m-header').animate({ height: 164 }, 200, 'easeOut');
    $('#m-rotban').fadeIn(200);
    $('#m-headerteaser').fadeOut(200);
}
function toggleTeaserCheckbox() {
    var teaserChecked = document.getElementById("teaserCheckbox").checked;
    if (teaserChecked) {
        $.cookie("DFOTeaser", "true", { expires: 10, path: "/", domain: "nexon.net" });
    } else {
        $.cookie("DFOTeaser", "false", { expires: 10, path: "/", domain: "nexon.net" });
    }
}

function toggleLightBox() {
    var lightboxChecked = document.getElementById("toggleLight").checked;
    if (lightboxChecked) {
        $.cookie("DFOInitialPTS", "true", { expires: 7, path: "/", domain: "nexon.net" });
    } else {
        $.cookie("DFOInitialPTS", "false", { expires: 7, path: "/", domain: "nexon.net" });
    }
}

function loadLightBox(chosenUser) {
    if (chosenUser) {
        $("#pts-redirect").popup({
            width: 600,
            contents: "<div class='pts-popup'>\
							<p class='question'>Congratulations! You have been chosen as a player for DFO's Public Test Server.</p>\
							<p class='answer'><strong>Now you have the option to either play:</strong><br>\
							1. The live DFO server, for which you simply close this window and click on the Start Game button. OR<br>\
							2. You can play the DFO Public Test Server, which features brand new content that we have not yet released on the live server. We would like to get your first impression of our upcoming content, help us find bugs, provide us with your opinion, etc. To enter the public test server, click on the button below, or close out this window and click on the \"Enter the Public Test Server\" link under your Nexon ID name in the login module. Thank you, Dungeon Fighter. Fight on! </p>\
							<label><input id='toggleLight' type='checkbox' onclick='toggleLightBox();'>Skip this message the next time I come here.</label>\
							<a href='http://dungeonfighter.nexon.net/PTS/TestServerMain.aspx' target='_blank'>enter the public test server</a>\
							<div class='cfix'></div>\
						</div>",
            type: 'static'
        });
        var initialPTSCookie = $.cookie("DFOInitialPTS");
        if (initialPTSCookie == null)
            $.cookie("DFOInitialPTS", "false", { expires: 10, path: "/", domain: "nexon.net" });
    } else {
        $("#pts-redirect").popup({
            width: 400,
            contents: "<div class='pts-popup'>\
							<p>We're sorry, you are trying to access the Dungeon Fighter Online Public Test Server but have not been selected as one of our official Public Test Server players. We encourage you to play our live server by closing this window and clicking the \"Start Game\" button. </p>\
						</div>",
            type: 'static'
        });
    }
    $("#pts-redirect").click();
}

function loadXmasBox() {
    var dfo_xmas_cookie = $.cookie("dfo_xmas_cookie");
    if (dfo_xmas_cookie == null || dfo_xmas_cookie.value == false) {
        $('#winter-event').popup({
            width: 600, //width of popup
            contents: "<div id='dec-event'>\
			    <a href='http://dungeonfighter.nexon.net/News/Content.aspx?boardNo=200&contentNo=00AX5'></a>\
				<p><input id='xmas-check-box' name='xmas-check-box' type='checkbox' onclick='setXmasCookie()' />Please do not show me this message again today. </p>\
			 </div>",
            type: 'event'
        }).click();
    }
}

function setXmasCookie() {
    if ($('#xmas-check-box').is(':checked')) {
        var dfo_xmas_cookie = $.cookie("dfo_xmas_cookie");
        if (dfo_xmas_cookie == null)
            $.cookie("dfo_xmas_cookie", "true", { expires: 1, path: "/", domain: "nexon.net" });
    } else {
        var dfo_xmas_cookie = $.cookie("dfo_xmas_cookie");
        if (dfo_xmas_cookie != null)
            $.cookie("dfo_xmas_cookie", "false", { expires: 1, path: "/", domain: "nexon.net" });
    }
}

function defaultLoad() {
    heroBanner();
    rankings();
    loadNews();
    loadEvent();
    loadKeyword();
    pollImage();
    featuredItems();

    //funstuff - screenshots - carousel
    attachScreenshots();
    //funstuff - videos - carousel
    attachVideos();

    $('#m-new').expand({
        oHeight: 164,
        eHeight: 380,
        activeClass: 'active',
        hideThese: '#m-rotban',
        flash: mintroflash,
        flashHere: '#m-introvideo',
        expandThis: '#m-header',
        timeout: 200,
        defaultShow: false //(initialCookie === null ? true : false)
    });
    checkPartnerKey();

    // block teaser for the time being
    // checkTeaser();

    $.cookie("DFOInitial", "false", { expires: 10, path: "/", domain: "nexon.net" });

    //lightbox
    /*var spellPopupCookie = $.cookie("spelltowerPopup");
    if (spellPopupCookie == null || spellPopupCookie.value == false) {
        $().popupinit();
        $().popupYouTubeLb('popups.txt #mfighter-popup', 'mfighter');
    }*/
    $('#spellCk').live({
        click: function () {
            $(this).toggleClass('addcheckmark');
            if ($("#spellCk").hasClass("addcheckmark"))
                $.cookie("spelltowerPopup", "true", { expires: 1, path: "/", domain: "nexon.net" });
            else
                $.cookie("spelltowerPopup", "false", { expires: 1, path: "/", domain: "nexon.net" });
            //$("#popup-close").trigger("click");
        }
    });
}

// show teaser box for users
function checkTeaser() {
    if (initialCookie != null) {
        var teaserCookie = $.cookie("DFOTeaser");
        if (teaserCookie == null || teaserCookie == 'false') {
            //attachTeaserPanel();
            //showHeaderTeaser();
            $('#m-headerteaser-close').click(function (e) {
                hideHeaderTeaser();
            });
            $('#m-femalegunner li a').click(function (e) {
                e.preventDefault();
                $(this).parent().siblings().removeClass('open');
                $(this).parent().addClass('open');
            });
            $('#m-headerteaser-fg').click(function (e) {
                e.preventDefault();
                $('#m-headerteaser').removeClass('pts').addClass('fg');
            });
            $('#m-headerteaser-pts').click(function (e) {
                e.preventDefault();
                $('#m-headerteaser').removeClass('fg').addClass('pts');
            });
            $.cookie("DFOTeaser", "false", { expires: 10, path: "/", domain: "nexon.net" });
        } else if (teaserCookie == 'true') {
            $('#m-headerteaser').hide();
        }
    }
}

// adjust the height of the facebook meter
function fb_meter_height(number_fans) {
    var calc_top = Math.max(0, 100 - (number_fans / 5 / 100));
    $('#m-fb-meter-percent').css('top', calc_top + '%');
}

// read teaser content from html file and attach it to <div>
function attachTeaserPanel() {
    var divEl = $('#m-headerteaser');
    // remove existing content and css class
    divEl.empty();

    var HTML_FILE_URL = '/Teaser/female-gunner-teaser.html';

    $.get(HTML_FILE_URL, function (data) {
        var fileDom = $(data);
        divEl.append(fileDom);
    });
}


// start of funstuff carousel 

var screenshotsReady = false,
	videosReady = false;

function processScreenshots() {
    $('#m-funstuff-screenshots').highlightcarousel({
        slides: '#m-funstuff-screenshots li',
        animtimeout: 1000,
        pausetimeout: 5600,
        nextbtn: '#m-funstuff-right',
        prevbtn: '#m-funstuff-left',
        slider: '#m-funstuff-screenshots',
        imgholder: '#m-funstuff-img a',
        width: 77,
        trigger: 'scr',
        autostart: false
    });
    // if videos are ready, process the tabs
    if (videosReady) {
        processTabs();
    }
}
function processVideos() {
    $('#m-funstuff-videos').highlightcarousel({
        slides: '#m-funstuff-videos li',
        animtimeout: 1000,
        pausetimeout: 5600,
        nextbtn: '#m-funstuff-right',
        prevbtn: '#m-funstuff-left',
        slider: '#m-funstuff-videos',
        imgholder: '#m-funstuff-img a',
        width: 77,
        trigger: 'vid',
        popup: true
    });
    // if screenshots are ready
    if (screenshotsReady) {
        processTabs();
    }
}
function processTabs() {
    $('#m-funstuff-tabs a').tabs({
        tabs: '#m-funstuff-items ul',
        triggerprefix: ['vid', 'scr'],
        triggersuffix: ['pause', 'play']
    });
}

function attachScreenshots() {
    var screenshotsDiv = $('#m-funstuff-screenshots');
    screenshotsDiv.empty();

    $.getJSON('../JS/publisher_screenshots.js', function (d) {
        for (var i = 0; i < d.length; i++) {
            if (d[i].img_url.length > 0 && d[i].thumb_url.length > 0) {
                var li = $('<li>').append(
                	$('<a>').addClass('hzbtn')
					.attr('href', '/FunStuff/Screenshots.aspx')
					.append(
						$('<img>').attr('src', d[i].thumb_url)
						.attr('alt', d[i].img_url)
					)
				);
                screenshotsDiv.append(li);
            }
        }
        screenshotsReady = true;
        processScreenshots();
    });
}

function attachVideos() {
    var videosDiv = $('#m-funstuff-videos');
    videosDiv.empty();

    $.getJSON('../JS/publisher_videos.js', function (d) {
        for (var i = 0; i < d.length; i++) {
            if (d[i].img_url.length > 0 && d[i].thumb_url.length > 0) {  
                var li = $('<li>').append(
					$('<a>').addClass('hzbtn')
					.attr('href', d[i].video_link)
					.append(
						$('<img>').attr('src', d[i].thumb_url)
						.attr('alt', d[i].img_url)
					)
				);
                videosDiv.append(li);
            }
        }
        videosReady = true;
        processVideos();
    });
}

// end of funstuff carousel
