(function(context,$) {

    "use strict";

    context.JK = context.JK || {};
    context.JK.AddTrackDialog = function(app, myTracks, sessionId, sessionModel) {
        var logger = context.JK.logger;

        var ASSIGNMENT = {
            CHAT: -2,
            OUTPUT: -1,
            UNASSIGNED: 0,
            TRACK1: 1,
            TRACK2: 2
        };

        var instrument_array = [];

        // dialog variables
        // dialog variables
        var inputUnassignedList = [];
        var track2AudioInputChannels = [];

        function events() {

            // Track 2 Add
            $('#img-add-track2-input-add').unbind("click");
            $('#img-add-track2-input-add').click(function() {
                $('#add-track2-unused > option:selected').remove().appendTo('#add-track2-input');
            });

            // Track 2 Remove
            $('#img-add-track2-input-remove').unbind("click");
            $('#img-add-track2-input-remove').click(function() {
                $('#add-track2-input > option:selected').remove().appendTo('#add-track2-unused'); 
            });

            $('#btn-cancel-new-audio').click(context.JK.showOverlay);
            $('#btn-error-ok').click(context.JK.showOverlay);

            // $('#btn-cancel-new-audio').click(function() {
            //      app.layout.closeDialog('add-new-audio-gear');
            // });
            // $('#btn-error-ok').click(function() {
            //      app.layout.closeDialog('error-dialog');
            // });
            
            $('#btn-add-track').unbind("click");
            $('#btn-add-track').click(saveSettings);
        }

        function showDialog() {

            $('#add-track2-unused').empty();
            $('#add-track2-input').empty();
            $('#add-track2-instrument').empty();

            initDialogData();

            // load Unused Inputs
            context.JK.loadOptions($('#template-option').html(), $('#add-track2-unused'), inputUnassignedList, "id", "name", -1);

            // load Track 2 Input(s)
            context.JK.loadOptions($('#template-option').html(), $('#add-track2-input'), track2AudioInputChannels, "id", "name", -1);

            // load Track 2 Instrument
            context.JK.loadOptions($('#template-option').html(), $('#add-track2-instrument'), instrument_array, "id", "description", -1);
        }

        function initDialogData() {

            // set arrays
            inputUnassignedList = _loadList(ASSIGNMENT.UNASSIGNED, true, false);
            console.log("inputUnassignedList: " + JSON.stringify(inputUnassignedList));
            track2AudioInputChannels = _loadList(ASSIGNMENT.TRACK2, true, false);
        }

        function _loadList(assignment, input, chat) {
            var list = [];

            // get data needed for listboxes
            var channels = context.jamClient.TrackGetChannels();

            var musicDevices = context.jamClient.TrackGetMusicDeviceNames(input);

            // SEE loadList function in TrackAssignGui.cpp of client code
            $.each(channels, function(index, val) {

                if (input !== val.input) {
                    return;
                }

                var currAssignment = context.jamClient.TrackGetAssignment(val.id, val.input);
                if (assignment !== currAssignment) {
                    return;
                }

                logger.debug("channel id=" + val.id + ", channel input=" + val.input + ", channel assignment=" + currAssignment + 
                    ", channel name=" + val.name + ", channel type=" + val.device_type + ", chat=" + val.chat);

                var os = context.jamClient.GetOSAsString();
                if (os === context.JK.OS.WIN32) {
                    if (chat && ($.inArray(val.device_id, musicDevices) > -1 || context.jamClient.TrackIsMusicDeviceType(val.device_type))) {
                        return;
                    }
                }
                else {
                    if (chat && ($.inArray(val.device_id, musicDevices) > -1 || !context.jamClient.TrackIsMusicDeviceType(val.device_type))) {
                        return;
                    }
                }

                if (!chat && $.inArray(val.device_id, musicDevices) === -1) {
                    return;
                }

                if ((chat && !val.chat) || (!chat && val.chat)) {
                    return;
                }

                list.push(val);
            });

            return list;
        }

        function saveSettings() {
            if (!validateSettings()) {
                return;
            }

            saveTrack();
            app.layout.closeDialog('add-track');
        }

        function saveTrack() {
            // TRACK 2 INPUTS
            $("#add-track2-input > option").each(function() {
                logger.debug("Saving track 2 input = " + this.value);
                context.jamClient.TrackSetAssignment(this.value, true, ASSIGNMENT.TRACK2);
            });

            // TRACK 2 INSTRUMENT
            var instrumentVal = $('#add-track2-instrument').val();
            var instrumentText = $('#add-track2-instrument > option:selected').text().toLowerCase();

            logger.debug("Saving track 2 instrument = " + instrumentVal);
            context.jamClient.TrackSetInstrument(ASSIGNMENT.TRACK2, instrumentVal);

            // UPDATE SERVER
            logger.debug("Adding track with instrument " + instrumentText);
            var data = {};
            // use the first track's connection_id (not sure why we need this on the track data model)
            logger.debug("myTracks[0].connection_id=" + myTracks[0].connection_id);
            data.connection_id = myTracks[0].connection_id;
            data.instrument_id = instrumentText;
            data.sound = "stereo";
            sessionModel.addTrack(sessionId, data);
        }

        function validateSettings() {
            var isValid = true;
            var noTrackErrMsg = 'You must assign at least one input port to each of your tracks. Please update your settings to correct this. If you want to delete a track, please return to the session screen and delete the track by clicking the "x" box in the upper right-hand corner of the track.';
            var noInstrumentErrMsg = 'You must specify what instrument is being played for this new track. Please update your settings to correct this.';

            var errMsg;

            // verify Input and Instrument exist
            if ($('#add-track2-input > option').size() === 0 || $('#add-track2-input > option').size() > 2) {
                errMsg = noTrackErrMsg;
                isValid = false;
            }

            if (isValid && $('#add-track2-instrument > option:selected').length === 0) {
                errMsg = noInstrumentErrMsg;
                isValid = false;
            }

            if (!isValid) {
                context.JK.showErrorDialog(app, errMsg, "invalid settings");
            }
            return isValid;
        }

        // TODO: repeated in configureTrack.js
        function _init() {
            // load instrument array for populating listboxes, using client_id in instrument_map as ID
            context.JK.listInstruments(app, function(instruments) {
                $.each(instruments, function(index, val) {
                    instrument_array.push({"id": context.JK.server_to_client_instrument_map[val.description].client_id, "description": val.description});
                });
            });
        }

        this.initialize = function() {
            events();
            _init();
        };

        this.showDialog = showDialog;

        return this;
    };

 })(window,jQuery);