(function(context,$) {

    "use strict";

    context.JK = context.JK || {};
    context.JK.CreateSessionScreen = function(app) {
        var logger = context.JK.logger;
        var rest = context.JK.Rest();
        var realtimeMessaging = context.JK.JamServer;
        var invitationDialog = null;
        var inviteMusiciansUtil = null;
        var MAX_GENRES = 1;
        var sessionSettings = {};
        var friendInput = null;

        function beforeShow(data) {
            inviteMusiciansUtil.clearSelections();
            context.JK.GenreSelectorHelper.render('#create-session-genre');
            resetForm();
        }

        function afterShow(data) {
            inviteMusiciansUtil.loadFriends();

            context.JK.guardAgainstBrowser(app);
        }

        function resetForm() {
            <% if Rails.application.config.autocheck_create_session_agreement %>
            $('#intellectual-property').iCheck('check').attr('checked', true);
            <% else %>
            $('#intellectual-property').iCheck('uncheck').attr('checked', false);
            <% end %>

            var $form = $('#create-session-form');
            var description = sessionSettings.hasOwnProperty('description') ? sessionSettings.description : '';
            $('textarea[name="description"]', $form).val(description);
            var genre = sessionSettings.hasOwnProperty('genres') && sessionSettings.genres.length > 0 ? sessionSettings.genres[0].id : '';
            context.JK.GenreSelectorHelper.reset('#create-session-genre', genre);

            var bandId = sessionSettings.hasOwnProperty('band_id') ? sessionSettings.band_id : '';
            $('#band-list', $form).val(bandId);

            var musician_access = sessionSettings.hasOwnProperty('musician_access') ? sessionSettings.musician_access : true;
            $('#musician-access').val(musician_access.toString());

            toggleMusicianAccess();

            if (musician_access) {
                var approval_required = sessionSettings.hasOwnProperty('approval_required') ? sessionSettings.approval_required : false;
                $('#musician-access-option-' + approval_required).iCheck('check').attr('checked', 'checked');
            }

            var fan_access = sessionSettings.hasOwnProperty('fan_access') ? sessionSettings.fan_access : true;
            $('#fan-access').val(fan_access.toString());
            toggleFanAccess();

            if (fan_access) {
                var fan_chat = sessionSettings.hasOwnProperty('fan_chat') ? sessionSettings.fan_chat : true;
                $('#fan-chat-option-' + fan_chat).iCheck('check').attr('checked', 'checked');
            }

            context.JK.dropdown($('#musician-access', $form));
            context.JK.dropdown($('#fan-access', $form));

            $(friendInput)
                .unbind('blur')
                .attr("placeholder", "Looking up friends...")
                .prop('disabled', true)
        }

        function  validateForm() {
            //var errors = [];
            var isValid = true;
            var $form = $('#create-session-form');

            // Description can't be empty
            var description = $('#description').val();
            if (!description) {
                $('#divDescription .error-text').remove();
                $('#divDescription').addClass("error");
                $('#description').after("<ul class='error-text'><li>Description is required</li></ul>");
                isValid = false;
            }
            else {
                $('#divDescription').removeClass("error");
            }

            var genres = context.JK.GenreSelectorHelper.getSelectedGenres('#create-session-genre');

            if (genres.length === 0) {
                $('#divGenre .error-text').remove();
                $('#divGenre').addClass("error");
                $('#create-session-genre').after("<ul class='error-text'><li>You must select a genre.</li></ul>");
                isValid = false;
            }
            else {
                $('#divGenre').removeClass("error");
            }

            // if (genres.length > MAX_GENRES) {
            //     errors.push(['#genre-list', "No more than " + MAX_GENRES + "genres are allowed."]);
            // }

            var intellectualPropertyChecked = $('#intellectual-property').is(':checked');
            if (!intellectualPropertyChecked) {
                $('#divIntellectualProperty .error-text').remove();
                $('#divIntellectualProperty').addClass("error");
                $('#divTerms').after("<ul class='error-text'><li>You must accept the JamKazam Terms of Service.</li></ul>");
                isValid = false;
            }
            else {
                $('#divIntellectualProperty').removeClass("error");
            }

            return isValid;
        }

        function submitForm(evt) {
            evt.preventDefault();

            if(!gon.isNativeClient) {
              return false;
            }

            if(!context.JK.JamServer.connected) {
              app.notifyAlert("Not Connected", 'To create or join a session, you must be connected to the server.');
              return false;
            }

            // If user hasn't completed FTUE - do so now.
            if (!(context.JK.hasOneConfiguredDevice())) {
                app.afterFtue = function() { submitForm(evt); };
                app.layout.startNewFtue();
                return false;
            }

            // if for some reason there are 0 tracks, show FTUE
            var tracks = context.JK.TrackHelpers.getUserTracks(context.jamClient);
            if(tracks.length == 0) {
              logger.error("we should never have 0 tracks and have gotten this far.  Launch FTUE is the best we can do right now")
              // If user hasn't completed FTUE - do so now.
              app.afterFtue = function() { submitForm(evt); };
              app.layout.startNewFtue();
              return false;
            }

            var isValid = validateForm();
            if (!isValid) {
                // app.notify({
                //     title: "Validation Errors",
                //     text: JSON.stringify(formErrors)
                // });
                return false;
            }

            var data = {};
            data.client_id = app.clientId;
            data.description = $('#description').val();
            data.as_musician = true;
            data.legal_terms = true; // this overrides the default of 'on', which isn't satisfying our concept of boolean
            data.intellectual_property = $('#intellectual-property').is(':checked');

            data.genres = context.JK.GenreSelectorHelper.getSelectedGenres('#create-session-genre');

            data.musician_access = $('#musician-access option:selected').val() === "true" ? true : false;
            data.approval_required = $("input[name='musician-access-option']:checked").val() === "true" ? true : false;

            data.fan_access = $('#fan-access option:selected').val() === "true" ? true : false;
            data.fan_chat = $("input[name='fan-chat-option']:checked").val() === "true" ? true : false;

            if ($('#band-list option:selected').val() !== '') {
                data.band = $('#band-list option:selected').val();
            }
            data.audio_latency = context.jamClient.FTUEGetExpectedLatency().latency;

            // 1. If no previous session data, a single stereo track with the
            //    top instrument in the user's profile.
            // 2. Otherwise, use the tracks from the last created session.
            // Defaulting to 1st instrument in profile always at the moment.
            data.tracks = tracks;

            $('#btn-create-session').addClass('button-disabled');
            $('#btn-create-session').bind('click', false);

            rest.legacyCreateSession(data)
              .done(function(response) {
                var newSessionId = response.id;
                var invitationCount = inviteMusiciansUtil.createInvitations(newSessionId, function() {
                  context.location = '/client#/session/' + newSessionId;
                });
                // Re-loading the session settings will cause the form to reset with the right stuff in it.
                // This is an extra xhr call, but it keeps things to a single codepath
                loadSessionSettings();
                $('#btn-create-session').removeClass('button-disabled');
                $('#btn-create-session').unbind('click', false);

                context.JK.GA.trackSessionCount(data.musician_access, data.fan_access, invitationCount);

                context.JK.GA.trackSessionMusicians(context.JK.GA.SessionCreationTypes.create);
              })
              .fail(function(jqXHR) {
                var handled = false;
                if(jqXHR.status = 422) {
                  var response = JSON.parse(jqXHR.responseText);
                  if(response["errors"] && response["errors"]["tracks"] && response["errors"]["tracks"][0] == "Please select at least one track") {
                    app.notifyAlert("No Inputs Configured", $('<span>You will need to reconfigure your audio device.</span>'));
                    handled = true;
                  }
                }
                if(!handled) {
                  app.notifyServerError(jqXHR, "Unable to Create Session");
                }
                $('#btn-create-session').removeClass('button-disabled');
                $('#btn-create-session').unbind('click', false);

              })

            return false;
        }

        function events() {
            $('#create-session-form').on('submit', submitForm);
            $('#btn-create-session').on("click", submitForm);
            $('#musician-access').change(toggleMusicianAccess);
            $('#fan-access').change(toggleFanAccess);

            $('div[layout-id="createSession"] .btn-email-invitation').click(function() {
                invitationDialog.showEmailDialog();
            });

            $('div[layout-id="createSession"] .btn-gmail-invitation').click(function() {
                invitationDialog.showGoogleDialog();
            });

            $('div[layout-id="createSession"] .btn-facebook-invitation').click(function(e) {
               invitationDialog.showFacebookDialog(e);
            });

            $(friendInput).focus(function() { $(this).val(''); })
        }

        function toggleMusicianAccess() {
            var value = $("#musician-access option:selected").val();
            if (value == "false") {
                $("input[name='musician-access-option']").attr('disabled', 'disabled');
                $("input[name='musician-access-option']").parent().addClass("op10");
            }
            else {
                $("input[name='musician-access-option']").removeAttr('disabled');
                $("input[name='musician-access-option']").parent().removeClass("op10");
            }
        }

        function toggleFanAccess() {
            var value = $("#fan-access option:selected").val();
            if (value == "false") {
                $("input[name='fan-chat-option']").attr('disabled', 'disabled');
                $("input[name='fan-chat-option']").parent().addClass("op10");
            }
            else {
                $("input[name='fan-chat-option']").removeAttr('disabled');
                $("input[name='fan-chat-option']").parent().removeClass("op10");
            }
        }

        function loadBands() {
            var url = "/api/users/" + context.JK.currentUserId + "/bands";
            $.ajax({
                type: "GET",
                url: url,
                success: bandsLoaded
            });
        }

        function bandsLoaded(response) {
            $.each(response, function() {
                var template = $('#template-band-option').html();
                var bandOptionHtml = context.JK.fillTemplate(template, {value: this.id, label: this.name});
                $('#band-list').append(bandOptionHtml);
            });
            context.JK.dropdown($('#band-list'));
        }

        function loadSessionSettings() {
            var url = "/api/users/" + context.JK.currentUserId + "/session_settings";
            $.ajax({
                type: "GET",
                url: url,
                success: sessionSettingsLoaded
            });
        }

        function sessionSettingsLoaded(response) {
            if (response != null) {
               sessionSettings = response;
            }
            resetForm();
        }

        // this exists solely due to a bug in Windows QTWebkit: https://bugreports.qt-project.org/browse/QTBUG-30072
        function initializeButtons() {
           $('div[layout-id="createSession"] .icheckbuttons input').iCheck({
                checkboxClass: 'icheckbox_minimal',
                radioClass: 'iradio_minimal',
                inheritClass: true
            });
        }

        function initialize(invitationDialogInstance, inviteMusiciansUtilInstance) {
            invitationDialog = invitationDialogInstance;
            inviteMusiciansUtil = inviteMusiciansUtilInstance;
            friendInput = inviteMusiciansUtil.inviteSessionCreate('#create-session-invite-musicians', "<div style='margin-right:140px;'>Start typing friends' names or:</div>");  //'
            events();
            loadBands();
            loadSessionSettings();
            initializeButtons();
            var screenBindings = { 'beforeShow': beforeShow, 'afterShow': afterShow };
            app.bindScreen('createSession', screenBindings);
        }

        // Expose publics
        this.initialize = initialize;
        this.resetForm = resetForm;
        this.submitForm = submitForm;
        this.validateForm = validateForm;
        this.loadBands = loadBands;

        return this;
    };

 })(window,jQuery);