(function(context,$) {

    "use strict";

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

    var downloads = {};

    function listClients() {
        var rest = context.JK.Rest();

        var currentOS = context.JK.detectOS();

        var downloads = $('.downloads');
        rest.getClientDownloads()
            .done(function(data) {
                downloads.removeClass('spinner-large');

                var count = 0;
                for ( var property in data ) count++;


                if(count == 0) {
                    alert("Currently unable to list client software downloads.");
                }
                else {

                    $.each(data, function(key, item) {


                        // if the currentOS we detect from browser is found within the product of an available client
                        // we flag it with this boolean
                        var matchesUserOS = currentOS != null && key.toLowerCase().indexOf(currentOS.toLowerCase()) > -1;

                        var platform = key.substring('JamClient/'.length);

                        var options = {
                            emphasis: matchesUserOS ? "currentOS" : "",
                            uri: item.uri,
                            platform: platform
                        }

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

                        download.find('a').data('platform', platform).click(function() {
                            var clicked = $(this);
                            rest.userDownloadedClient().always(function() {
                                $('body').append('<iframe class="downloading" src="' + clicked.attr('href') + '" style="display:none"/>')
                            })
                            context.JK.GA.trackDownload($(this).data('platform'));
                            return false;
                        });

                        if(matchesUserOS) {
                            // make sure the current user OS is at the top
                            downloads.prepend(download);
                        }
                        else {
                            downloads.append(download)
                        }
                    });
                }
            })
            .fail(function() {
                downloads.removeClass('spinner-large');
                alert("Currently unable to list client software downloads due to error.");
            })
    }

    downloads.listClients = listClients;

    context.JK.Downloads = downloads;

})(window, jQuery)