﻿/// <reference path="jquery-1.5-vsdoc.js" />
var _currentAnchor = "";
var _currentInteralAnchor = "";
var _previousAnchor = "";
var _previousInteralAnchor = "";
var _currentMediaItem = "";

var _onLoad = true;

var _INDEX = 'index';
var _INDEXASPX = 'index.aspx';
var _INDEXTHUMB = 'index_thumbnail';

var _minFlashHeight = 536; //488;
var _contentOffset = 143;

//Console fix for IE
if (typeof console == "undefined" || typeof console.log == "undefined") {
    var console = { log: function () { } };
}

//On load page, init hash change listener
$().ready(function () {

    AjaxLinks();
    BuildFlash();

    if (_isDebug == true)
        AjaxPro.timeoutPeriod = 120000;

    var hash = stripHash(GetSubChannel()).toLowerCase();
    var loc = GetPageLocation();

    if ((loc == '/' || loc == _INDEXASPX || loc == '') && (hash.length > 0 && hash != loc)) {
        GetPage();
    }
    else {
        InitUIObjects();
    }

    _currentAnchor = GetSubChannel();
    setPreviousAnchor(_currentAnchor);

    _currentInteralAnchor = GetInteralAnchor();

    if (_currentInteralAnchor == "" && defaultArticle != "") {
        _currentInteralAnchor = defaultArticle;
    }

    $(window).hashchange(checkAnchor);

    $(window).hashchange();

    // Added to be able to link to the JackPack
    // overlay from external sites
    var jackPackRegex = new RegExp(/jp=1/);
    if (jackPackRegex.test(window.location.href)) {
        ShowSignUp();
    }



    $(window).resize(function () {
        if (!_isIE6) {
            this.updateFlashAreaSize();
        }
    });

    styleArticleTables();

    initExternalLinkTracking();
});

function setPreviousAnchor(value) {
    _previousAnchor = value;
    if (_previousAnchor == "") {
        _previousAnchor = "#index";
    }
}

function AjaxLinks() {
    $('a').each(function () {
        var href = $(this).attr('href');
        var loc = GetPageLocation();
        var validHref = false;

        //ie and FF behave differently
        if (($.browser.mozilla) || ($.browser.safari) || (($.browser.msie) && parseInt($.browser.version) >= 8)) {
            if (href != undefined)
                validHref = true;
        }
        else {
            if (href != '') {
                validHref = true;
            }
        }

        if (validHref == true) {
            if (href.search('http') == -1
                                    && href != '#'
                                    && href.search('javascript') == -1
                                    && href.search('#') == -1) {
                //if we are in debug, dont do redirects	                                
                if ((loc == '/' || loc == _INDEXASPX) || _isDebug == true) {
                    $(this).attr('href', '#' + href.replace(".aspx", ""));
                }
                else {
                    $(this).attr('href', '/#' + href.replace(".aspx", ""));
                }
            }
        }
    });
}
var _remainingHeight;
function BuildFlash() {
    var flashvars = {};
    flashvars.subchannel = stripHash(GetSubChannel());

    var params = { menu: "false", wmode: "transparent" };
    var attributes = { id: "FlashContent", name: "FlashContent" };

    this.updateFlashAreaSize();

    swfobject.embedSWF("Main.swf", "FlashContent", "100%", "100%", "9.0.0", "resources/images/expressInstall.swf", flashvars, params, attributes);
}

function updateFlashAreaSize() {
    //Compute height that flash can use
    var footerHeight = $("#Footer").height();
    var headerHeight = $("#Header").height();
    var windowHeight = $(window).height();
    _remainingHeight = windowHeight - headerHeight - footerHeight;

    if (_remainingHeight < _minFlashHeight) {
        _remainingHeight = _minFlashHeight;
    }

    var heightPct = (_remainingHeight / windowHeight) * 100 + "%";
    heightPct = _remainingHeight;
    $("#FlashArea").height(heightPct);
}

function stripHash(str) {
    var ary = str.split("#");
    return ary[ary.length - 1];
}

function GetSubChannel() {
    var page = document.location.hash;
    //rip off everything to the left of "!/"
    var idx = page.indexOf("!/");
    if (idx > 0) {
        page = page.replace(page.slice(idx, page.length), "");
    }

    var mediaItemName = page.indexOf("~");
    if (mediaItemName > 0) {
        page = page.slice(0, mediaItemName);
    }


    if (page.length == 0) {
        var file = window.location.pathname.split("/");
        page = file[file.length - 1];
    }

    var patt1 = new RegExp("^#?MediaItem_[a-zA-Z_0-9]*");
    if (patt1.exec(page)) {
        page = defaultSubChannel;
    }

    var patt3 = new RegExp("^#?Article_[a-zA-Z_0-9]*");
    if (patt3.exec(page)) {
        page = defaultSubChannel;
    }

    var patt2 = new RegExp("^#");
    if (patt2.exec(page)) {
        page = page.slice(1, page.length);
    }

    return page;
}

function GetMediaItemName() {
    var itemName = "";

    var page = document.location.hash;

    var mediaItemName = page.indexOf("~");
    if (mediaItemName > 0) {
        itemName = page.replace(page.slice(0, mediaItemName + 1), "");
    }
    else if (page.length == 0) {
        if (defaultMediaItem) {
            itemName = defaultMediaItem;
        }
    }

    return itemName;
}

function GetInteralAnchor() {
    var retVal = '';
    var page = document.location.hash;
    var idx = page.indexOf("!/");
    if (idx > 0) {
        retVal = page.slice(idx + 2, page.length);
    }
    return retVal;
}

function GetPageLocation() {
    return window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1).toLowerCase();
}

function checkAnchor() {
    if (_currentAnchor.toLowerCase() != GetSubChannel().toLowerCase() || ((_currentAnchor.toLowerCase() == '#searchresults') && (_currentInteralAnchor.toLowerCase() != GetInteralAnchor().toLowerCase()))) {
        var filePattern = new RegExp("([Ii]ndex.aspx){1}|^\/$");
        var file = window.location.pathname;
        if (!filePattern.exec(file)) {
            window.location = _INDEXASPX + "#" + GetSubChannel(); // + "!/" + GetInteralAnchor();
        }
        else {
            setPreviousAnchor(_currentAnchor);
            _previousInteralAnchor = _currentInteralAnchor;
            _currentAnchor = GetSubChannel();
            _currentInteralAnchor = GetInteralAnchor();
            PageChange();
        }
    }
    else if (_currentAnchor.toLowerCase() == GetSubChannel().toLowerCase() && _currentMediaItem != GetMediaItemName()) {
        loadMediaItem();
    }
}


function PageChange() {
    GetFlashContent();
    GetPage();
}

function GetPage() {
    //If getSubChannel is index minimize lower divs, shrink conten area, expand flash area (animateFlashArea)
    var hash = stripHash(GetSubChannel()).toLowerCase();
    var loc = GetPageLocation();

    if ((loc == '/' || loc == _INDEXASPX || loc == '') && (hash == _INDEX || hash == _INDEXTHUMB)) {
        if (_previousAnchor != '')
            NavigateToIndex();
    }
    else {
        //Animate to top of page
        if ($('html, body').scrollTop() != 0) {
            $('html, body').animate({ scrollTop: 0 }, "slow", scrollToTop_callback);
        }
        else {
            scrollToTop_callback();
        }
    }
}

function scrollToTop_callback() {
    //Make sure both the body and html are done with their animations
    if ($("html:animated, body:animated").size() <= 1) {
        var sc = GetSubChannel();
        if (sc.toLowerCase() == "#searchresults" || sc.toLowerCase() == "searchresults") {
            var st = GetInteralAnchor();
            if (st.length > 0) {
                JackLinks.Page.PageSearch(st, GetPage_callback);
            }
        }
        else {
            JackLinks.Page.PageRetrieve(sc, GetPage_callback);
        }
    }
}

function GetPage_callback(res) {
    if (res.error && res.error.Message != 'Unknown') {
        alert($(res.error).attr("Message"));
    }
    else {
        //shrink flash area if moving from index (animateFlashArea).
        if (_previousAnchor == _INDEX || _previousAnchor == _INDEXTHUMB || _previousAnchor == "#" + _INDEX || _previousAnchor == "#" + _INDEXTHUMB) {
            NavigateFromIndex();
        }


        var xContent = $(res.value).find("root");

        //minimize content area
        MinimizeContentArea(function () {
            ContentReplacement(xContent);
            MaximizeContentArea(xContent.find("ColumnLeft").attr("DetailAssetHeight"), InitUIObjects);
        });
    }
}


function ContentReplacement(xContent) {
    xContent.children().each(function () {
        var div = $(this).attr("ID");
        var content = $(this).text();
        if ($(this)[0].tagName.toLowerCase() == 'overlays') {
            $(this).children().each(function () {
                //if the div isnt on the page add it
                var divID = $(this).attr("ID");
                if ($('#' + divID).length == 0) {
                    $('body').append($(this).text());
                }
            });
        }
        else {
            $("#" + div).html(content);
        }
    });
}

function MinimizeContentArea(callback) {
    var height = $(window).height();
    $("#ContentArea").animate({ top: height }, 500, null, function () { $("#ContentArea").hide('fast', callback); });
}

function MaximizeContentArea(flashAssetHeight, callback) {
    $("#ContentArea").show('fast',
   	                            function () {
   	                                ContentAreaAnimateTop(parseInt(flashAssetHeight), callback);
   	                            });
}

function ContentAreaAnimateTop(flashAssetHeight, callback) {
    $("#ContentArea").animate({ top: (parseInt(flashAssetHeight) + _contentOffset) }, 500, callback);
}

function InitUIObjects() {
    InitScroller();
    RefreshDragDrop();
    StyleScrollBar();
    FixPng();
    ProductNavigation();

    if (_currentAnchor.toLowerCase() == GetSubChannel().toLowerCase() && _currentMediaItem != GetMediaItemName()) {
        loadMediaItem();
    }

    if (defaultArticle != "") {
        console.log("jumping to article: " + defaultArticle);
        window.location.hash = defaultArticle;
        defaultArticle = "";
    }

    styleArticleTables();
}

function styleArticleTables() {
    $(".ArticleCopy table").attr("cellspacing", 0)
    $(".ArticleCopy table").attr("cellpadding", 0)
    $(".ArticleCopy table").attr("border", 0)
    $(".ArticleCopy table tr:even").addClass("even");
}

function loadMediaItem() {
    console.log("loadMediaItem");
    var subChannel = GetSubChannel();
    if (_currentAnchor.toLowerCase() == subChannel.toLowerCase() && _currentMediaItem != GetMediaItemName()) {
        var mediaItemName = GetMediaItemName();
        console.log("mediaItemName: " + mediaItemName);

        if (mediaItemName != "") {
            var ele = $("#" + GetMediaItemName());
            if (ele.size() > 0) {
                _currentMediaItem = GetMediaItemName();
                var assetID = ele.attr("assetItemID");
                var arrName = ele.attr("assetArray");

                var arr = [];
                if ($("#" + arrName).val() != null) {
                    arr = $("#" + arrName).val().split(",");
                }
                console.log("Loading asset: " + assetID);
                loadAsset(arr, assetID);
                JumpToTop();
            }
        }
    }
}

function FixPng() {
    correctPNG();
}

function RefreshDragDrop() {
    $(".dragdrop").draggable({ appendTo: 'body', containment: 'document', revert: true, helper: 'clone', opacity: 0.7, zIndex: 7000,
        start: function (event, ui) {
            showModal('share');
        },
        stop: function (event, ui) {
            showModal('share');
        }
    });
    $(".droppable").droppable({
        drop: function (event, ui) {

            var st = $('#' + event.target.id).attr("sharetype");
            var l = "";
            var wl = window.location.toString();

            var draggable = ui.draggable;
            if (draggable) {
                var draggableItemName = draggable.attr("id");
                var page = window.location.href.toString();
                var pathname = window.location.pathname.toString();
                var i = page.indexOf(pathname);
                if (i > 0) {
                    page = page.replace(page.slice(i, page.length), "");
                }

                var shareChannel = draggable.attr("channel");
                var shareSubChannel = draggable.attr("subChannel");
                if (draggable.attr("multiMediaItemName")) {
                    wl = locationOrigin + "MediaItem_" + shareChannel + shareSubChannel + draggable.attr("multiMediaItemName") + ".aspx";
                }
                else if (draggable.attr("article")) {
                    wl = locationOrigin + "Article_" + shareChannel + shareSubChannel + draggable.attr("article") + ".aspx";
                }
            }

            if (st.toLowerCase() == 'other') {
                l = "http://api.addthis.com/oexchange/0.8/offer?url={url}";
            }
            else {
                if (st.toLowerCase() == 'facebook') {
                    wl = wl.replace("#", "");
                    wl = wl.replace(/index.aspx/i, "");
                    wl = wl.replace(/.aspx/i, "");
                    wl = wl + ".aspx";
                }
                l = "http://api.addthis.com/oexchange/0.8/forward/{st}/offer?url={url}";
            }
            l = l.replace("{st}", st);
            l = l.replace("{url}", wl);
            l = l.replace("#", "%23");
            recordOutboundLinkLabeled('Share Link', wl, st);
            window.open(l);
        }
    });
}

function StyleScrollBar() {

    if ($('.FeedModuleScroll').length > 0) {
        try {
            $('.FeedModuleScroll').jScrollPane({ scrollbarWidth: 7, scrollbarMargin: 15, dragMinHeight: 30, dragMaxHeight: 30 });
        }
        catch (err) {
            //alert(err.description);
        }
    }
}

function InitScroller() {
    $(".mediaHolder").each(function (index) {
        var lessBtnId = '#' + $(this).find(".mediaContainerScrollLeft").attr('id');
        var moreBtnId = '#' + $(this).find(".mediaContainerScrollRight").attr('id');

        $(this).find(".mediaSection").clickScroll({
            speed: 500,
            easing: 'easeInOutExpo',
            lessBtn: lessBtnId,
            moreBtn: moreBtnId,
            horizontal: true,
            autoHideNav: true
        });
    });
}

function GetFlashContent() {
    changeSubChannel(GetSubChannel());
}

function GetFeedItems(feedID, col) {
    JackLinks.Page.FeedItemsRetrieve(feedID, col, GetFeedItems_callback);
}

function GetFeedItems_callback(res) {
    if (res.error && res.error.Message != 'Unknown') {
        alert($(res.error).attr("Message"));
    }
    else {
        var xContent = $(res.value).find("root").find("Feed");
        $("#divFeed" + xContent.attr("ID")).html(xContent.text());

        StyleScrollBar();
    }
}

function AssetClick(id, arrName) {
    var page = GetSubChannel();
    var ele = $("#" + id);
    var channel = ele.attr("channel");
    var subchannel = ele.attr("subchannel");
    var multiMediaItemName = ele.attr("multiMediaItemName");
    var mediaType = ele.attr("mediaType");
    var trackingAction = channel + "->" + subchannel + "->" + multiMediaItemName;
    //var trackingPage = ele.attr("trackingPage");

    //Recording as an even so we can tell how many people navigate directly to a multimedie item page.
    recordOutboundLinkLabeled("Multimedia View", trackingAction, mediaType);
    //_gaq.push(['_trackPageview', "/" + trackingPage]);

    window.location.hash = page.replace(".aspx", "") + "~" + multiMediaItemName;
}

function NavigateToIndex() {
    _minFlashHeight = 488;
    updateFlashAreaSize();

    MinimizeContentArea(function () { });
    animateFlashArea(_remainingHeight);

    if (_currentAnchor == _INDEX) {
        showCarousel();
    }
    else {
        showThumbnails();
    }
}

function NavigateFromIndex() {
    _minFlashHeight = 536;
    updateFlashAreaSize();
    animateFlashArea(565);
}

function JumpToTop() {
    $('html, body').animate({ scrollTop: 90 }, "slow", function () { });
}

function MediaAssetRollover(id) {
    $('#' + id).show();
}

function MediaAssetRollout(id) {
    $('#' + id).hide();
}

function Search() {
    document.location.hash = "#SearchResults!/" + $('#search').val();
}

function ProductNavigation() {
    $(".productNavigation img").hover(
		function () {
		    $(this).attr("defaultImg", $(this).attr("src"));
		    $(this).attr("src", $(this).attr("overImg"));
		}, function () {
		    $(this).attr("src", $(this).attr("defaultImg"));
		});
}
