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

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

(function ($) {
    $.widget("ui.playeraskpanel", {
        options: {
            onSendQuestion: null,
            dismissFunction: null,
            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-message-dialog'
            },
            classes: {
                panel: 'ui-playeraskpanel',
                form: 'ui-playeraskpanel-form',
                inputStretch: 'input-stretch',
                header: 'panel-header',
                modalMask: 'panel-modal-mask'
            },
            subject: {
                maxLength: 512
            },
            message: {
                cols: 20,
                rows: 10
            },
            labelMargin: 115,
            currentPosition: 0,
            presentation: null,
            scrollbarColor: 'rgba(255,255,255,0.5)',
            window: window,
            javascriptResize: true,
            msgDialogWidth: undefined
        },

        _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;
            this._msgDialogInterval = 0;
            self.element.addClass(o.classes.panel);
            var markup =
                '<p id="' + o.ids.header + '" class="' + o.classes.header + '">' + Mediasite.Player.Localization.Buttons.Ask + '</p>' +
				'<div id="' + o.ids.scrollWrapper + '">' +
					'<div id="' + o.ids.scroll + '">' +
						'<form class="' + o.classes.form + '">' +
							'<p><label for="' + o.ids.nameField + '"> * ' + Mediasite.Player.Localization.AskQuestion.Name + '</label><input type="text" name="name" id="' + o.ids.nameField + '" class="' + o.classes.inputStretch + '" /></p>' +
							'<p><label for="' + o.ids.emailField + '">' + Mediasite.Player.Localization.AskQuestion.Email + '</label><input type="text" name="email" id="' + o.ids.emailField + '"  class="' + o.classes.inputStretch + '" /></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="' + o.classes.inputStretch + '" /></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="' + o.classes.inputStretch + '"></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>' +
                            '<p><span class="requiredField">* ' + Mediasite.Player.Localization.Common.RequiredField + '</span></p>' +
						'</form>' +
					'</div>' +
				'</div>' +
				'<div id="' + o.ids.modalMask + '" class="' + o.classes.modalMask + '"></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();
            self._overlayState(false);
            $('#' + o.ids.dismissDialog, self.element).click(function () { $('#' + o.ids.modalMask, self.element).hide(); });

            if (o.javascriptResize) {
                $(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
            $('.' + o.classes.inputStretch, 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 () {
            var o = this.options;
            this.element.removeClass(o.classes.panel);
            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();
            }

            if (o.javascriptResize) {
                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
                };

                if (jQuery.isFunction(o.onSendQuestion)) {
                    o.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) {
                    self._displayMessage(Mediasite.Player.Localization.Buttons.Ask, '<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;
            var title = Mediasite.Player.Localization.AskQuestion.SendSuccessTitle;
            
            var dismissHandler;

            if (success) {
                message = Mediasite.Player.Localization.AskQuestion.SendSuccessDetail;
                 $('#' + o.ids.subjectField, self.element).val("");
                 $('#' + o.ids.messageField, self.element).val("");
                
                dismissHandler = function() {
                    $(self).unbind();

                    if (jQuery.isFunction(o.dismissFunction)) {
                        o.dismissFunction();
                    }
                };
            } else {
                title = Mediasite.Player.Localization.AskQuestion.SendFailureTitle;
                
                if (message.length == 0) {
                    message = Mediasite.Player.Localization.AskQuestion.SendFailureDetail;
                }
            }

            self._displayMessage(title, message, dismissHandler);
        },

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

            $('#' + o.ids.emailField, self.element).val(emailData["EmailAddress"]);
        },

        _displayMessage: function (title, message, callback) {

            var self = this,
                o = self.options;

            self._overlayState(true);

            self._killDisplayMessage();
            var messageElement = $('<div id="' + o.ids.msgDialog + '"></div>');
            messageElement.appendTo(self.element);
            
            var messageOptions =
            {
                title: title,
                message: message,
                allowClose: false,
                dialogClass: 'panelMessage',
                width: o.msgDialogWidth ? o.msgDialogWidth : self.element.innerWidth() - 4,
                modal: false,
                close: function () {
                    self._overlayState(false);
                    if ($.isFunction(callback)) {
                        callback();
                    }
                },
                position:
                {
                    my: "center top",
                    at: "center top+100",
                    of: self.element
                },
                appendTo: self.element[0]
            };
            messageElement.messagedisplay(messageOptions);
            
            self._msgDialogInterval = setInterval(function() {
                if (!self.element.is(':visible')) {
                    self._overlayState(false);
                    clearInterval(self._msgDialogInterval);
                }
            }, 500);
        },

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

            show ? $('#' + o.ids.modalMask, self.element).show() : $('#' + o.ids.modalMask, self.element).hide();
        },
        
        _killDisplayMessage: function() {
            
            var self = this,
                o = self.options;

            var messageElement = $('#' + o.ids.msgDialog, self.element);
            
            if (messageElement.length > 0) {
                if (messageElement.hasClass('messagedisplayinit')) {
                    messageElement.messagedisplay('destroy');
                }
                messageElement.remove();
            }

        }

    });
})(jQuery);
