(function(context,$) {

    "use strict";

    context.JK = context.JK || {};

    var downloads = {};
    var isCongratulations;
    var downloadUris = {}; // map of platform > uri
    var rest = context.JK.Rest();

    function selectPlatform(selectedPlatform) {
        var platformName; // mac, windows, linux
        var platformDisplay; // Mac, Windows, Linux
        var platform = selectedPlatform; //MacOSX, Win32, Unix
        var platformName1, platformName2, platform1, platform2, platformDisplay1, platformDisplay2;
        var uri = downloadUris[selectedPlatform];

        // prepare template varaibles
        if (selectedPlatform == "Unix") {
            platformName = "linux";
            platformDisplay = "Linux"
            platformName1 = "mac";
            platformDisplay1 = "Mac";
            platformName2 = "windows";
            platformDisplay2 = "Windows";
            platform1 = "MacOSX";
            platform2 = "Win32"
        } else if(selectedPlatform == "Win32") {
            platformName = "windows";
            platformDisplay = "Windows";
            platformName1 = "mac";
            platformDisplay1 = "Mac";
            platformName2 = "linux"
            platformDisplay2 = "Linux";
            platform1 = "MacOSX";
            platform2 = "Unix";
        } else if(selectedPlatform == "MacOSX") {
            platformName = "mac";
            platformDisplay = "Mac";
            platformName1 = "windows";
            platformDisplay1 = "Windows";
            platformName2 = "linux";
            platformDisplay2 = "Linux";
            platform1 = "Win32";
            platform2 = "Unix";
        }
        else {
            alert("unknown platform: " + selectedPlatform);
        }

        var options = {
            platform : platform,
            platformName : platformName,
            platformDisplay : platformDisplay,
            platformName1 : platformName1,
            platformDisplay1 : platformDisplay1,
            platformName2 : platformName2,
            platformDisplay2 : platformDisplay2,
            platform1: platform1,
            platform2: platform2,
            uri : uri ? uri : '#',
            isCongratulations : isCongratulations
        };

        var blurb = $(context._.template($('#client-download-blurb-contents').html(), options, { variable: 'data' }));

        // isolate active image for blurb
        $('div.hidden-images img[data-purpose=' + platformName + ']', blurb).remove().appendTo($('a.current-os-download', blurb));

        var selectOthers = $(context._.template($('#client-download-select-others').html(), options, { variable: 'data' }));

        // isolate active images for selectOthers
        $('div.hidden-images img[data-purpose=' + platformName1 + ']', selectOthers).remove().appendTo($('a[data-order=1]', selectOthers));
        $('div.hidden-images img[data-purpose=' + platformName2 + ']', selectOthers).remove().appendTo($('a[data-order=2]', selectOthers));


        // install click handler for change selection
        $('a', selectOthers).click(function() {
            var platform = $(this).attr('data-platform');
            selectPlatform(platform);
            return false;
        });

        $('a', blurb).click(function() {
            var clicked = $(this);
            var href = clicked.attr('href');
            if(href != "#") {
                context.JK.GA.trackDownload(clicked.attr('data-platform'));
                rest.userDownloadedClient().always(function() {
                  $('body').append('<iframe class="downloading" src="' + clicked.attr('href') + '" style="display:none"/>')
                });
            }
            else {
                // if there is no download available, apologize to the user
                alert("Sorry, this download is not currently available.");
                return false;
            }

            return false;
        });

        // update blurb
        $('body.web .downloads-blurb').empty().append(blurb);
        // update the 'download other platforms' buttons
        $('body.web .downloads-container').empty().append(selectOthers);
        // update system requirements
        $('body.web .system-requirements ul').hide();
        $('body.web .system-requirements ul.' + platformName + '-requirements').show();
        $('body.web .system-requirements').show();
    }

    function removeSpinner() {
        $('body.web .spinner-large').remove();
    }

    function flashCongratulations(friend) {
        if(friend) {
            context.JK.flash('Congratulations!<br>Soon you can play with ' + friend + '!', {hide:20})
        }
        else {
            context.JK.flash('Congratulations!<br>Your account is ready.', {hide:20})
        }

    }
    function listClients(congratulations, friend) {
        isCongratulations = congratulations;

        if(isCongratulations) {
          flashCongratulations(friend);
        }
        else {
          //flashCongratulations();
        }

        var rest = context.JK.Rest();
        var currentOS = context.JK.detectOS();
        var downloads = $('.downloads');

        rest.getClientDownloads()
            .done(function(data) {
                removeSpinner();

                $.each(data, function(key, item) {
                    var platform = key.substring('JamClient/'.length);

                    downloadUris[platform] = item.uri;
                });
            })
            .fail(function(jqXHR) {
                removeSpinner();
                context.JK.app.notify({text: "Currently unable to list client software downloads due to error."});
            })
            .always(function() {
                selectPlatform(currentOS == null ? 'Win32' : currentOS);
            });
    }

    downloads.listClients = listClients;

    context.JK.Downloads = downloads;

})(window, jQuery)