/// <reference path="../ScriptReference/jquery-1.5.2.js"/>

/*
 * jQuery UI PlayerAskPanel
 *
 * Depends:
 *   jquery.ui.core.js
 *   jquery.ui.widget.js
 *   Mediasite.Player.Localization.js
 *
 */

(function ($) {
    $.widget("ui.playeraskpanel", {
        options: {
            ids: {
                header: 'ui-playeraskpanel-header',
                scroll: 'ui-playeraskpanel-scroll',
                scrollWrapper: 'ui-playeraskpanel-scroll-wrapper',
                nameField: 'ui-playeraskpanel-name',
                emailField: 'ui-playeraskpanel-email',
                subjectField: 'ui-playeraskpanel-subject',
                messageField: 'ui-playeraskpanel-message',
                timeCheckBox: 'ui-playeraskpanel-time-checkbox',
                timeField: 'ui-playeraskpanel-time',
                timeFormat: 'ui-playeraskpanel-time-format',
                timeLabel: 'ui-playeraskpanel-timeLabel',
                submitArea: 'ui-playeraskpanel-submit',
                sendButton: 'ui-playeraskpanel-sendBtn',
                modalMask: 'ui-playeraskpanel-modalmask',
                msgDialog: 'ui-playeraskpanel-dialog',
                dialogText: 'ui-playeraskpanel-dialog-text',
                dismissDialog: 'ui-playeraskpanel-dismiss-dialog',
                dialogTitle: 'ui-playeraskpanel-dialog-title'
            },
            subject: {
                maxLength: 512
            },
            message: {
                cols: 20,
                rows: 10
            },
            labelMargin: 115,
            currentPosition: 0,
            presentation: null,
            scrollbarColor: 'rgba(255,255,255,0.5)',
            window: window
        },

        _setOption: function (key, value) {
            var self = this,
                o = self.options;

            o[key] = value;

            //hide time checkbox if live
            if (key === 'presentation' && o.presentation.PlayStatus != "OnDemand") {
                self.hideTimeData();
            }
            //

            // update time field
            if (key === 'currentPosition') {
                $('#' + o.ids.timeField, self.element).val(Mediasite.Player.TimeHelper.getDisplayFromDuration(o.currentPosition, true));
            }
        },

        _create: function () {
            var self = this,
                o = self.options;
            self.element.addClass("ui-playeraskpanel");
            var markup =
                '<p id="' + o.ids.header + '">' + Mediasite.Player.Localization.Buttons.Ask + '</p>' +
				'<div id="' + o.ids.scrollWrapper + '">' +
					'<div id="' + o.ids.scroll + '">' +
						'<form class="ui-playeraskpanel-form">' +
							'<p><label for="' + o.ids.nameField + '">' + Mediasite.Player.Localization.AskQuestion.Name + '</label><input type="text" name="name" id="' + o.ids.nameField + '" class="input-stretch" /></p>' +
							'<p><label for="' + o.ids.emailField + '">' + Mediasite.Player.Localization.AskQuestion.Email + '</label><input type="text" name="email" id="' + o.ids.emailField + '"  class="input-stretch" /></p>' +
							'<p><label for="' + o.ids.subjectField + '">' + Mediasite.Player.Localization.AskQuestion.Subject + '</label><input type="text" name="subject" id="' + o.ids.subjectField + '" maxlength="' + o.subject.maxLength + '" class="input-stretch" /></p>' +
							'<p><label for="' + o.ids.messageField + '">' + Mediasite.Player.Localization.Email.Message + '</label><textarea name="message" id="' + o.ids.messageField + '" rows="' + o.message.rows + '" cols="' + o.message.cols + '" class="input-stretch"></textarea></p>' +
							'<p><label id="' + o.ids.timeLabel + '" for="' + o.ids.timeCheckBox + '">' + Mediasite.Player.Localization.AskQuestion.Time + '</label><input type="checkbox" name="timeCheckbox" id="' + o.ids.timeCheckBox + '"/><input type="text" name="time" id="' + o.ids.timeField + '" /><span id="' + o.ids.timeFormat + '">' + Mediasite.Player.Localization.AskQuestion.TimeFormat + '</span></p>' +
							'<p id="' + o.ids.submitArea + '"><input id="' + o.ids.sendButton + '" type="submit" value="' + Mediasite.Player.Localization.AskQuestion.AskButton + '" /></p>' +
						'</form>' +
					'</div>' +
				'</div>' +
				'<div id="' + o.ids.modalMask + '">' +
					'<div id="' + o.ids.msgDialog + '">' +
						'<div id="' + o.ids.dialogTitle + '"/>' +
						'<div id="' + o.ids.dialogText + '"/>' +
						'<button id="' + o.ids.dismissDialog + '">' + Mediasite.Player.Localization.Common.OK + '</button>' +
					'</div>' +
				'</div>';
            self.divMarkup = $(markup).appendTo(self.element);

            var submitForm = function (e) { e.preventDefault(); self._sendQuestion(); };
            $('form', self.element).bind('submit', submitForm);
            $('#' + o.ids.sendButton, self.element).click(submitForm);

            $('#' + o.ids.modalMask, self.element).hide();
            $('#' + o.ids.dismissDialog, self.element).click(function () { $('#' + o.ids.modalMask, self.element).hide(); });

            $(o.window).resize(function () {
                self.updateLayout();
            });
        },

        hideTimeData: function () {
            var o = this.options;
            $('#' + o.ids.timeCheckBox, self.element).hide();
            $('#' + o.ids.timeField, self.element).hide();
            $('#' + o.ids.timeFormat, self.element).hide();
            $('#' + o.ids.timeLabel, self.element).hide();
        },

        updateLayout: function () {
            var self = this,
                o = self.options;

            // stretch out input fields
            $('.input-stretch', self.element).width(self.element.innerWidth() - o.labelMargin);
            $('#' + o.ids.messageField, self.element).width(self.element.innerWidth() - o.labelMargin - 2); // <TEXTAREA> is weird


            var $scrollWrapper = $('#' + o.ids.scrollWrapper, self.element);
            var availableHeight = self.element.height();   // Start with panel's inner height
            // Subtract height of pertinent siblings
            availableHeight -= $('#' + o.ids.header, self.element).outerHeight(true);
            // availableHeight is now space alloted for the scroll wrapper
            // Allow for scroll wrapper's padding and margin
            availableHeight -= parseInt($scrollWrapper.css('margin-top'), 10) || 0;
            availableHeight -= parseInt($scrollWrapper.css('margin-bottom'), 10) || 0;
            availableHeight -= parseInt($scrollWrapper.css('padding-top'), 10) || 0;
            availableHeight -= parseInt($scrollWrapper.css('padding-bottom'), 10) || 0;

            availableHeight = availableHeight > 0 ? availableHeight : 20; // just in case

            $scrollWrapper.height(availableHeight);

            // refresh iscroll
            $('#' + o.ids.scroll, self.element).iscroll({ scrollbarColor: o.scrollbarColor });
        },

        destroy: function () {
            this.element.removeClass("ui-playeraskpanel");
            this.divMarkup.remove();
        },

        _init: function () {
            var self = this,
                o = self.options;

            // update current position value
            $('#' + o.ids.timeField, self.element).val(Mediasite.Player.TimeHelper.getDisplayFromDuration(o.currentPosition, true));

            //show time oncheck, default to hide.
            $('#' + o.ids.timeCheckBox, self.element)
             .change(function () {
                 if ($('#' + o.ids.timeCheckBox, self.element).is(':checked')) {
                     $('#' + o.ids.timeField, self.element).attr('disabled', false);
                 } else {
                     $('#' + o.ids.timeField, self.element).attr('disabled', true);
                 }
             })
             .trigger('change');

            //hide time controls and labels alltogether if live
            if (o.presentation != null && o.presentation.PlayStatus != "OnDemand") {
                self.hideTimeData();
            }


            this.updateLayout();
        },

        _sendQuestion: function () {
            var self = this,
                   o = self.options;

            if (validateQuestion()) {
                var timeInPreso = 0;
                if ($('#' + o.ids.timeCheckBox, self.element).is(":checked")) {
                    timeInPreso = Mediasite.Player.TimeHelper.getDurationFromDisplay($('#' + o.ids.timeField, self.element).val());
                }

                var question = {
                    Submitter: $("#" + o.ids.nameField, self.element).val(),
                    SubmitterEmail: $("#" + o.ids.emailField, self.element).val(),
                    Subject: $("#" + o.ids.subjectField, self.element).val(),
                    QuestionText: $("#" + o.ids.messageField, self.element).val(),
                    TimeInPresentation: timeInPreso
                };

                var notifier = o.notifier || new Mediasite.Player.ViewEventNotifier();
                notifier.OnSendQuestion(question);
            }

            function validateQuestion() {
                var errors = "";
                var nameValue = $('#' + o.ids.nameField, self.element).val();
                if (!nameValue || nameValue.length < 1) {
                    errors += "<br/> - " + Mediasite.Player.Localization.AskQuestion.NameRequired;
                }
                var emailValue = $.trim($('#' + o.ids.emailField, self.element).val());
                if (emailValue.length > 0 && !validateEmailAddress(emailValue)) {   // Email is optional, so only validate if it's not empty or whitespace
                    errors += "<br/> - " + Mediasite.Player.Localization.AskQuestion.EmailInvalid;
                }
                var subjectValue = $('#' + o.ids.subjectField, self.element).val();
                if (!subjectValue || subjectValue.length < 1) {
                    errors += "<br/> - " + Mediasite.Player.Localization.AskQuestion.SubjectRequired;
                }
                var messageValue = $('#' + o.ids.messageField, self.element).val();
                if (!messageValue || messageValue.length < 1) {
                    errors += "<br/> - " + Mediasite.Player.Localization.AskQuestion.QuestionRequired;
                }

                if ($('#' + o.ids.timeCheckBox, self.element).is(":checked")) {
                    var timeValue = $('#' + o.ids.timeField, self.element).val();
                    if (!timeValue || (o.presentation && (Mediasite.Player.TimeHelper.getDurationFromDisplay(timeValue) > o.presentation.Duration))
                        || Mediasite.Player.TimeHelper.getDurationFromDisplay(timeValue) == -1) {
                        errors += "<br/> - " + Mediasite.Player.Localization.AskQuestion.QuestionTimeError;
                    }
                }

                if (errors.length > 0) {
                    $('#' + o.ids.modalMask, self.element).show();
                    $('#' + o.ids.dialogTitle, self.element).text(Mediasite.Player.Localization.Buttons.Ask);
                    $('#' + o.ids.dialogText, self.element).html('<strong>' + Mediasite.Player.Localization.AskQuestion.ValidationError + '</strong><br/>' + errors);
                    return false;
                }

                return true;
            }

            function validateEmailAddress(address) {
                var emailRegEx = /^[A-Z0-9.'_%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
                return emailRegEx.test(address);
            }

        },

        sendQuestionComplete: function (success, message) {
            var self = this,
                   o = self.options;
            $('#' + o.ids.modalMask, self.element).show();

            if (success) {
                $('#' + o.ids.dialogTitle, self.element).text(Mediasite.Player.Localization.AskQuestion.SendSuccessTitle);
                $('#' + o.ids.dialogText, self.element).text(Mediasite.Player.Localization.AskQuestion.SendSuccessDetail);
                $('#' + o.ids.subjectField, self.element).val("");
                $('#' + o.ids.messageField, self.element).val("");

                var dismissHandler = function (evt) {
                    $(this).unbind(evt);

                    if (o.dismissFunction) {
                        o.dismissFunction();
                    }
                };

                $('#' + o.ids.dismissDialog, self.element).bind('click', dismissHandler);
            }
            else {
                $('#' + o.ids.dialogTitle, self.element).text(Mediasite.Player.Localization.AskQuestion.SendFailureTitle);
                if (message.length > 0) {
                    $('#' + o.ids.dialogText, self.element).text(message);
                }
                else {
                    $('#' + o.ids.dialogText, self.element).text(Mediasite.Player.Localization.AskQuestion.SendFailureDetail);
                }
            }
        }
    });
})(jQuery);