function NonClinicTimeScript($, params) {
    //#region Validations
    $.validator.addMethod("timeGreaterThan", function(value, element, parms) {
        if (!/Invalid|NaN/.test(moment(value, 'h:mm a'))) {
            return moment(value, 'h:mm a') > moment($(parms).val(), 'h:mm a');
        }

        return isNaN(value) && isNaN($(parms).val()) || (moment(value, 'h:mm a') > moment($(parms).val(), 'h:mm a'));

    }, params.toTimeMustBeGreaterThanFromTime);

    $.validator.addMethod("dateGreaterThanEndDate", function (value, element, parms) {
        if (!/Invalid|NaN/.test(moment($(parms).val(), 'MM/DD/YYYY'))) {
            return moment(value, 'MM/DD/YYYY') < moment($(parms).val(), 'MM/DD/YYYY');
        }

        return isNaN(value) && isNaN($(parms).val()) || (moment(value, 'MM/DD/YYYY') < moment($(parms).val(), 'MM/DD/YYYY'));

    }, params.endDateMustBeGreaterThanCycleStartDate);

    $.validator.addMethod("dateGreaterThanDate", function (value, element, parms) {
        if (!/Invalid|NaN/.test(moment(value, 'MM/DD/YYYY'))) {
            return moment(value, 'MM/DD/YYYY') > moment($(parms).val(), 'MM/DD/YYYY');
        }

        return isNaN(value) && isNaN($(parms).val()) || (moment(value, 'MM/DD/YYYY') > moment($(parms).val(), 'MM/DD/YYYY'));

    }, params.endDateMustBeGreaterThanStartDate);

    $.validator.addMethod("hasAtleastOneWeekDay", function (value, element, parms) {
        if (!/Invalid|NaN/.test(self.daysSelected())) {
            return self.daysSelected().length > 0;
        }

        return isNaN(value) && isNaN($(parms).val()) || (self.daysSelected().length > 0);

    }, params.selectAtLeast1Day);


    $("#cteForm").validate({
        onfocusout: false,
        rules: {
            description: {
                required: true,
                maxlength: 30
            },
            displayDescription: {
                required: true,
                maxlength: 30
            },
            recurEvery: {
                required: true,
                maxlength: 2
            },
            from: {
                required: true
            },
            to: {
                required: true,
                timeGreaterThan: "#from"
            },
            datepicker: {
                required: true
            },
            startingOn: {
                dateGreaterThanEndDate: "#endingOn"  
            },
            endingOn: {
                required: true,
                dateGreaterThanDate: "#datepicker"
            },
            monday: {
                hasAtleastOneWeekDay: "#dayMultiSelect"
            },
            tuesday: {
                hasAtleastOneWeekDay: "#dayMultiSelect"
            },
            wednesday: {
                hasAtleastOneWeekDay: "#dayMultiSelect"
            },
            thursday: {
                hasAtleastOneWeekDay: "#dayMultiSelect"
            },
            friday: {
                hasAtleastOneWeekDay: "#dayMultiSelect"
            },
            saturday: {
                hasAtleastOneWeekDay: "#dayMultiSelect"
            },
            sunday: {
                hasAtleastOneWeekDay: "#dayMultiSelect"
            }
        },
        groups: {
            checkboxes: 'monday tuesday wednesday thursday friday saturday sunday'
        },
        messages: {
            description: {
                required: params.descCannotBeEmpty,
                maxlength: params.maxLengthCannotExceed30
            },
            displayDescription: {
                required: params.dispDescCannotBeEmpty,
                maxlength: params.maxLengthCannotExceed30
            },            
            recurEvery: {
                required: params.recurEveryCannotBeEmpty,
                maxlength: params.recurEveryLengthCannotExceed2
            },
            from: {
                required: params.fromTimeCannotBeEmpty
            },
            to: {
                required: params.toTimeCannotBeEmpty
            },
            datepicker: {
                required: params.startDateCannotBeEmpty
            }
        },
        errorElement: "div",
        wrapper: "div",
        errorPlacement: function(error, element) {
            error.offset();
            error.addClass("cteError");
            if(element.attr("id") === "description")
                error.insertAfter("#descIcon");              
            if(element.attr("id") === "displayDescription")
                error.insertAfter("#dispDescIcon");             
            if(element.attr("id") === "recurEvery")
                error.insertAfter(".monthOption");   
            if (element.attr("id") === "to" || element.attr("id") === "from")
                error.insertAfter(".daytimeGroup");
            if (element.attr("id") === "endingOn" || element.attr("id") === "startingOn")
                error.appendTo(".dateValidationMsg");
            if (element.attr("id") === "monday" || element.attr("id") === "tuesday" || element.attr("id") === "wednesday" || element.attr("id") === "thursday" || element.attr("id") === "friday" || element.attr("id") === "saturday" || element.attr("id") === "sunday")
                error.appendTo(".weekdayValidationMsg");
            //else {
            //    error.insertAfter(element);   
            //}
        }
    });
    //#endregion

    //#region "checkbox" handler rights belong to KnockStrap (http://faulknercs.github.io/Knockstrap). MIT License.
    ko.bindingHandlers.checkbox = {
        init: function (element, valueAccessor) {
            var $element = $(element),
                handler = function (e) {
                    // we need to handle change event after bootstrap will handle its event
                    // to prevent incorrect changing of checkbox state
                    setTimeout(function () {
                        var $checkbox = $(e.target),
                            value = valueAccessor(),
                            data = $checkbox.val(),
                            isChecked = $checkbox.parent().hasClass('active');

                        if (!$checkbox.prop('disabled')) {
                            if (ko.unwrap(value) instanceof Array) {
                                var index = ko.utils.arrayIndexOf(ko.unwrap(value), (data));

                                if (isChecked && (index === -1)) {
                                    value.push(data);
                                } else if (!isChecked && (index !== -1)) {
                                    value.splice(index, 1);
                                }
                            } else {
                                value(isChecked);
                            }
                        }
                    }, 0);
                };

            if ($element.attr('data-toggle') === 'buttons' && $element.find('input:checkbox').length) {

                if (!(ko.unwrap(valueAccessor()) instanceof Array)) {
                    throw new Error('checkbox binding should be used only with array or observableArray values in this case');
                }

                $element.on('change', 'input:checkbox', handler);
            } else if ($element.attr('type') === 'checkbox') {

                if (!ko.isObservable(valueAccessor())) {
                    throw new Error('checkbox binding should be used only with observable values in this case');
                }

                $element.on('change', handler);
            } else {
                throw new Error('checkbox binding should be used only with bootstrap checkboxes');
            }
        },

        update: function (element, valueAccessor) {
            var $element = $(element),
                value = ko.unwrap(valueAccessor()),
                isChecked;

            if (value instanceof Array) {
                if ($element.attr('data-toggle') === 'buttons') {
                    $element.find('input:checkbox').each(function (index, el) {
                        isChecked = ko.utils.arrayIndexOf(value, el.value) !== -1;
                        $(el).parent().toggleClass('active', isChecked);
                        el.checked = isChecked;
                    });
                } else {
                    isChecked = ko.utils.arrayIndexOf(value, $element.val()) !== -1;
                    $element.toggleClass('active', isChecked);
                    $element.find('input').prop('checked', isChecked);
                }
            } else {
                isChecked = !!value;
                $element.prop('checked', isChecked);
                $element.parent().toggleClass('active', isChecked);
            }
        }
    };
    //#endregion

    //#region Initializations and variable declarations
    $('.cteMenu').dropit();

    // Disable mobile inputs (ie not descendants of #clinic-time-exception-d [desktop]) 
    // ...effectively hiding iOS navigation bar on clicks
    $('#clinic-time-exception').find('.time_element').prop('disabled', 'disabled');
    $('#clinic-time-exception').find('.datepickerInput').prop('disabled', 'disabled');

    // Initialize
    //---------------------------------------------------------------------
    var $desktopRightPanel = $('#clinic-time-exception-d #right-panel');
    var $mobileLeftPanel = $('#clinic-time-exception #left-panel');
    var $mobileRightPanel = $('#clinic-time-exception #right-panel');
    var $descriptionInput = $('#description input');
    var $descriptionSearch = $('#search');
    var $displayDescriptionInput = $('#displayDescription input');
    var $displayDescriptionEdit = $('#edit');
    var $allDayCheckbox = $('#allDay input[type="checkbox"]');
    var $save = $('.save');
    var $edit = $('.edit');
    var $to = $('#to');
    var $from = $('#from');
    var $datepicker = $('#datepicker');
    var $selectedColor = $('#selectedColor');
    var serialized = '';
    var $spinner = $('#spinner-overlay');
    var $overlay = $('#overlay');
    var $startingOn = $('#startingOn');
    var $endingOn = $('#endingOn');
    var $recurCteCheckbox = $('.recurCte input[type="checkbox"]');
    var $cycleStartDate = $("#startingOn");
    var $cycleEndDate = $("#endingOn");
    var $weekdayButton = $(".btn-weekdays");                        // AX-27042

    var DISABLED_OPACITY = '0.60';
    var MAXCHARS = 30;

    $('.mobile-top-nav').hide();
    $('#SchedulerItem').addClass('desktop-nav-selected');

    // Query string params
    //---------------------------------------------------------------------
    var date;
    var allDayReq = params.callerAllDay.length ? params.callerAllDay : 'false';
    var view = params.callerView.length ? params.callerView : 'Day';

    $from.timepicker({
        minuteStep: 15,
        defaultTime: moment().startOf('hour').add(60, 'm').format("h:mm A")
    });
    $to.timepicker({
        minuteStep: 15,
        defaultTime: moment($from.val(), "h:mm A").add(30, "m").format("h:mm A")
    });

    if (params.callerHr.length === 0 && params.callerMin.length === 0) {
        var startWkDt = moment(params.callerDate);
        var endWeekDt = moment(params.callerDate).add(6, 'days');
        var today = moment();
        if (startWkDt <= today && endWeekDt >= today)
            date = moment().format("MM/DD/YYYY");
        else
            date = moment(params.callerDate).format("MM/DD/YYYY");
    } else {
        date = moment(params.callerDate).format("MM/DD/YYYY");

        var d = new Date();
        var h = params.callerHr.length ? params.callerHr : ((12 < d.getHours() + 1) ? (d.getHours() + 1) - 12 : (d.getHours() + 1));
        var m = params.callerMin.length ? params.callerMin : '0';
        var mer = params.callerMer.length ? params.callerMer : (12 <= d.getHours() + 1 && d.getHours() + 1 < 24) ? 'PM' : 'AM';

        var datetimeNow = date + " " + h + ":" + m + " " + mer;
        var timeNow = moment(datetimeNow);
        $from.val(timeNow.format("hh : mm A"));

        // To time
        var timeNowTo = timeNow.add(30, 'minutes');
        $to.val(timeNowTo.format("hh : mm A"));
    }

    $datepicker.datepicker({
        defaultDate: date,
        firstDay: params.startDayOfWeek,
        showOtherMonths: true,
        selectOtherMonths: true
    });

    $startingOn.datepicker({
        defaultDate: date,
        firstDay: params.startDayOfWeek,
        showOtherMonths: true,
        selectOtherMonths: true
    });

    $endingOn.datepicker({
        defaultDate: date,
        firstDay: params.startDayOfWeek,
        showOtherMonths: true,
        selectOtherMonths: true
    });

    $datepicker.val(date);

    $('#ui-datepicker-div').addClass('ui-datepicker-inline');
    $('#ui-datepicker-div').addClass('ui-datepicker');
    
    //#endregion

    //#region Event binding
//    window.onbeforeunload = function (e) {
//        $spinner.show();
//    };

    // Click events
    //---------------------------------------------------------------------
    $('*').on('click', function (e) {
        keepAlive();
        var el = $(e.toElement || e.target);
        if (el[0].id != 'datepicker' && el.closest('.ui-datepicker-header').length == 0) {
            $datepicker.datepicker('hide');
        }
        return true;
    });

    $('.alert-button-ok').on('click', function () {
        hideAlertDialog();
    });

    $('#allDay.inputBorder').on('click', function (evt) {
        if (evt.target.id != 'allDayChk' &&
            evt.target.htmlFor != 'allDayChk') {
            $allDayCheckbox.trigger('click');	// AX-24898.24919.2 $allDayCheckbox.click();
        }
    });

    $('#recurCte.inputBorder').on('click', function (evt) {
        if (evt.target.id != 'recurCteChk' &&
            evt.target.htmlFor != 'recurCteChk') {
            $recurCteCheckbox.trigger('click');	// AX-24898.24919.2 $recurCteCheckbox.click();
        }
    });

    $('#dateText').on('click', function () {
        $('#datepicker').datepicker('show');
    });

    $('a.cancel,\
        a.returnToSched,\
        #SchedulerItem,\
        #MessengerItem,\
        #userSettings,\
        #urgentMsg').on('click', function (evt) {
            evt.preventDefault();
            var _serialized = serialize();

            var url = params.returnUrl + date + '&view=' + view;
            var $urgent = $(evt.target).closest('.urgent-msg-container');
            if ($urgent.length) {
                url = $urgent.attr('href');
            }
            else if (evt.target.href.length) {
                url = evt.target.href;
            }

            if (_serialized !== serialized) {
                $('#alert-no-btn').off();
                $('#alert-yes-btn').off();
                $("#alert-no-btn").on('click', function () {
                    hideAlertDialog();
                    return;
                });
                $('#alert-yes-btn').on("click", function () {
                    hideAlertDialog();
                    window.location = url;
                });
                showAlertDialogYesNo(params.changesLost);
            }
            else {
                window.location = url;
            }
            return false;
        });

    $('.slider-frame').on('click', function (evt) {
        toggleButton($(this));
    });

    $('#eventColor .dropit-submenu li a').on('click', function (evt) {
        var selColor = $(evt.currentTarget).find('span').css('background-color');
        $selectedColor.css('background-color', selColor);
    });

    $displayDescriptionEdit.on('click', function () {
        $(this).hide();
        $displayDescriptionInput.prop('readonly', '');
        $displayDescriptionInput.prop('disabled', '');
        $displayDescriptionInput.trigger('focus');      // AX-24898.24919.2 .focus();
        var len = $displayDescriptionInput.val().length * 2;
        $displayDescriptionInput[0].setSelectionRange(len, len);
        $displayDescriptionInput.css('opacity', DISABLED_OPACITY);
    });

    $('#settingsOptionTitle').on('click', function () {
        $('.toast').remove();
        closePanel();
    });

    $('#search').mousedown(function (evt) {
        evt.stopPropagation();
        evt.preventDefault();
        $descriptionInput.focusout(0, function () {
            $descriptionSearch.show();
        });
        return false;
    });

    // Focus events
    //---------------------------------------------------------------------

    $('*').on('keyup', function (e) {
        keepAlive();
    });

    $('#description input').on('focus', function () {     // AX-24898.24919.2 .focus(function() {
        $descriptionSearch.show();
    });

    $('#description input, #search').focusout(function (evt) {
        $descriptionSearch.hide();
        scrollToTop();
    });

    $displayDescriptionInput.focusout(function () {
        var text = $displayDescriptionInput.val().substr(0, MAXCHARS);
        if (text.length === 0) {
            text = $descriptionInput.val();
            $displayDescriptionInput.val(text);
        }
        if (text.length > 0) {
            $displayDescriptionEdit.show();
            $displayDescriptionInput.prop('readonly', 'readonly');
            $displayDescriptionInput.prop('disabled', 'readonly');
            $displayDescriptionInput.css('opacity', '1');
        }
        scrollToTop();
    });
    
    // Change events
    //---------------------------------------------------------------------
    $allDayCheckbox.on('change', function () {     	// AX-24898.24919.2 .change(function () {
        if (this.checked) {
            $(this).parent().addClass('checked');
            $('.timeGroup').hide();
        } else {
            $(this).parent().removeClass('checked');
            $('.timeGroup').show();

            // Set To Time and From time only if the CTE was allday originally.
            if (self.modeldata.IsAllDay) {
                var thisTimeNow = moment().startOf('hour').add(60, 'm');
                h = thisTimeNow.format("h");
                m = thisTimeNow.format("mm");
                mer = thisTimeNow.format("A");
                $from.val(thisTimeNow.format("hh : mm A"));

                // To time
                var thisTimeNowTo = thisTimeNow.add(30, 'minutes');
                h = thisTimeNowTo.format("h");
                m = thisTimeNowTo.format("mm");
                mer = thisTimeNowTo.format("A");

                $to.val(thisTimeNowTo.format("hh : mm A"));
            }
        }
    });

    $recurCteCheckbox.on('change', function () {     	// AX-24898.24919.2 .change(function () {
        if (this.checked) {
            $(this).closest('.recurCheck').removeClass('no-bottom-padding');
            $(this).parent().addClass('checked');
            self.showIfRecurIsChecked(true);
            self.modeldata.IsRecurring = true;
        } else {
            $(this).closest('.recurCheck').addClass('no-bottom-padding');
            $(this).parent().removeClass('checked');
            self.showIfRecurIsChecked(false);
            self.modeldata.IsRecurring = false;
        }
    });

    $descriptionInput.on('keyup', function (e) {          // AX-24898.24919.2 .keyup(function (e) {
        var desc = $descriptionInput.val();
        var displayDesc = $displayDescriptionInput.val();
        var startswith = desc.indexOf(displayDesc) == 0;
        if (displayDesc.length === 0 || (desc.length <= MAXCHARS && startswith) ||
        (displayDesc.indexOf(desc) >= 0 && displayDesc.length === desc.length + 1)) {
            $displayDescriptionInput.val(desc);
        }
        if (desc.length > 0) {
            $displayDescriptionEdit.show();
        }
        else {
            $displayDescriptionEdit.hide();
        }
    });

    //#endregion
    
    //#region Helper fns
    //---------------------------------------------------------------------
    var scrollToTop = function () {
        $('html,body').animate({ scrollTop: 0 }, 200);
    };

    var serialize = function () {
        var munge = '';
        munge += $allDayCheckbox.is(':checked');
        munge += $datepicker.val() + $from.val();
        munge += $datepicker.val() + $to.val();
        munge += $descriptionInput.val();
        munge += $displayDescriptionInput.val();
        munge += $selectedColor.css('background-color');
        munge += $('#onlyAvailableIn .ui-list-item-link').html();
        munge += $('#qualifyAsBreak .slider-frame').hasClass('on');
        munge += $recurCteCheckbox.is(':checked');
        munge += $cycleStartDate.val();
        munge += $cycleEndDate.val();
        munge += $("#recurEvery").val();
        munge += $("#recurList").val();
        munge += $("#recurMode").val();
        munge += self.daysSelected().toString();

        return munge;
    };

    var slideButtonOff = function($sliderFrame) {
        var $sliderButton = $sliderFrame.find('.slider-button');
        if ($sliderButton.hasClass('disabled')) {
            return true;
        }
        window.setTimeout(function() {
            $sliderFrame.removeClass('on');
            $sliderButton.removeClass('on').html(params.noOpt);
        }, 0);
        return !$sliderButton.hasClass('on');
    };

    var slideButtonOn = function ($sliderFrame) {
        var $sliderButton = $sliderFrame.find('.slider-button');
        if ($sliderButton.hasClass('disabled')) {
            return true;
        }
        window.setTimeout(function () {
            $sliderFrame.addClass('on');
            $sliderButton.addClass('on').html(params.yesOpt);
        }, 0);
        return !$sliderButton.hasClass('on');
    };

    var toggleButton = function ($sliderFrame) {
        var $sliderButton = $sliderFrame.find('.slider-button');
        if (!$sliderButton.hasClass('on')) {
            return slideButtonOn($sliderFrame);
        } else {
            return slideButtonOff($sliderFrame);
        }
    };

    var openPanel = function (isenabled) {
        if (!isenabled)
            return true;

        $overlay.show();
        $descriptionInput.trigger('blur');					// AX-24898.24919.2 .blur();
        $displayDescriptionInput.trigger('blur');					// AX-24898.24919.2 .blur();

        $mobileLeftPanel.css('position', 'absolute');
        $mobileRightPanel.css('display', 'block');
        $mobileLeftPanel.hide('slide', { direction: 'left' }, 500, function () {
            $mobileLeftPanel.css('position', 'absolute');
        });

        $desktopRightPanel.show('slide', { direction: 'right' }, 'fast');
    };

    var closePanel = function () {
        $overlay.hide();

        $mobileLeftPanel.show('slide', { direction: 'left' }, 500, function () {
            $mobileLeftPanel.css('position', 'static');
            $mobileRightPanel.css('display', 'none');
        });

        $desktopRightPanel.hide('slide', { direction: 'right' }, 'fast');
    };
    //#endregion

    //#region Model binding with knockout
    //---------------------------------------------------------------------
    ko.applyBindings(function () {
        var self = this;
        self.startDateTime = "";
        self.endDateTime = "";

        var getSelectedAvailability = function (optionList, id) {
            if (self.OpMode[self.mode] == "Edit") {
                id = self.modeldata.SelectedClinicId;
                var $sliderButton = $('.slider-frame').find('.slider-button');
                if (id > 0) {
                    $sliderButton.addClass('disabled');
                }
            }
            return $.map(optionList ? optionList: [], function (opt) {
                if (opt.Id === id) {
                    return opt.Description;
                } else {
                    return null;
                }
            });
        };

        var updateQualifyAsBreak = function () {
            getSelectedAvailability(self.modeldata.ClinicList, self.modeldata.SelectedClinicId);
        };

        var getSelectedDesc = function (optionList, selected) {
            if (self.OpMode[self.mode] == "Edit") {
                // Show Edit Mode
                self.showEditModeOnLoad();

                // Had to return description since it is bound to the input
                return self.modeldata.SelectedExceptionDesc;
            } else
                return $.map(optionList ? optionList : [], function (opt) {
                    if (opt.Description === selected) {
                        return opt.Description;
                    } else {
                        return null;
                    }
                });
        };

        self.showEditModeOnLoad = function () {
            // Set Display Description
            $displayDescriptionInput.val(self.modeldata.DisplayExceptionDesc);
            // Set Color
            $selectedColor.css('background-color', self.modeldata.CteColor);
            // Set Partial Day checkbox
            //if (parseInt(moment(self.modeldata.StartDateTime).format("HH"), 10) == 0) {
            if (parseInt(self.modeldata.StartDateMinutes / 60, 10) == 0) {
                $edit.addClass('save-active');
                $allDayCheckbox.trigger('click');	// AX-24898.24919.2 $allDayCheckbox.click();
            }

            // Show Edit Button
            self.showForSave = ko.observable(false);
            self.showForEdit = ko.observable(true);

            // Disable all controls
            self.showEnabled(false);
        };

        var getSelectedColor = function (optionList, index) {
            return $.map(optionList ? optionList : [], function (opt) {
                if (opt.Index === index) {
                    return opt.ColorInHex;
                } else {
                    return null;
                }
            });
        };

        // Operation mode enum
        self.OpMode = { 0: "Add", 1: "Edit", 2: "Delete" };
        self.modeldata = params.modelData;
        self.validationResult = {};
        if (self.modeldata.SetException === 1)
            self.modeldata.IsRecurring = false;

        //For disabling the toggle boxes for weekdays
        self.daysSelected = ko.observableArray(self.modeldata.DaysInWeek);
        //$('label.btn-weekdays').addClass('disabled');
        //self.daysSelected = ko.observableArray(["2","3","4","5","6"]);

        self.cycle = ko.observable(self.modeldata.Cycle);
        self.cyclefreq = ko.observable(self.modeldata.CycleFrq);
        self.mode = self.modeldata.CteMode;
        self.startDateTime = "";
        self.endDateTime = "";

        self.showIfRecurIsChecked = ko.observable(false);
        self.showWhenCycleMoreThanOne = ko.observable(false);
        self.showForMonth = ko.observable(false);
        self.cycletype = ko.observable(self.modeldata.CycleType);
        if (self.OpMode[self.mode] === "Edit" && self.modeldata.IsRecurring) {
            if (moment(self.modeldata.CteSetDate).format("MM/DD/YYYY") < moment().format("MM/DD/YYYY")) {
                self.cycleStartDate = ko.observable(moment(self.modeldata.CteSetDate).format("MM/DD/YYYY"));
            } else {
                self.cycleStartDate = ko.observable(moment(self.modeldata.CycleStartDate).format("MM/DD/YYYY"));
            }
        } else {
            self.cycleStartDate = ko.observable(moment(date).format("MM/DD/YYYY"));
        }

        if (self.OpMode[self.mode] === "Add") {
            self.cycleEndDate = date;
        } else {
            self.cycleEndDate = ko.observable(moment(self.modeldata.CycleEndDate).format("MM/DD/YYYY"));
        }

        self.deleteSeries = ko.observable(self.modeldata.DeleteMode > 0);
        self.blockUI2Process = function () {
            $.blockUI.defaults.css = { padding: 0,
                margin: 0,
                width: '30%',
                top: '40%',
                left: '35%',
                textAlign: 'center',
                cursor: 'wait',
                ignoreIfBlocked: true
            };
            $.blockUI({ message: '<span class="ajax-loader-border"><img src="../../../Images/ajax-loader.gif" /></span>',
                overlayCSS: {
                    backgroundColor: 'rgb(27,27,27)',
                    opacity: .25,
                    zIndex: 1501 /*because the header css "desktop-nav" z-index is 1500!*/
                }
            });
        };

        if ($('#clinic-time-exception').length > 0) // mobile
            self.isMobileMode = ko.observable(true);
        else if ($('#clinic-time-exception-d').length > 0) // desktop
            self.isMobileMode = ko.observable(false);

        if (self.OpMode[self.mode] == "Add") {
            $startingOn.val(date);
            $endingOn.val(date);
        }

        if (self.OpMode[self.mode] == "Edit") {
            if (self.modeldata.VacaSet === 0 || self.modeldata.SetException > 0 || moment(self.modeldata.StartDateTime).format("MM/DD/YYYY") < moment().format("MM/DD/YYYY")) {
                self.startDateTime = self.modeldata.StartDateTime;
            }
            else {
                self.startDateTime = self.modeldata.CteSetDate;
            }
            self.endDateTime = self.modeldata.EndDateTime;

            //$from.val(moment(self.modeldata.StartDateTime).format("hh : mm A"));
            //$to.val(moment(self.endDateTime).format("hh : mm A"));

            $from.val(formatTime(self.modeldata.StartDateMinutes));
            $to.val(formatTime(self.modeldata.EndDateMinutes));

            $datepicker.val(moment(self.startDateTime).format("MM/DD/YYYY"));
        }

        self.showForSave = ko.observable(true);
        self.showForEdit = ko.observable(false);

        self.setEnabled = ko.observable(true);
        self.showEnabled = ko.computed({
            read: function () {
                return self.setEnabled();
            },
            write: function (value) {
                self.setEnabled(value);
                if (value) {
                    /* Enabling controls */

                    $('.slider-frame').find('.slider-button')
                        .removeClass('disabled');
                    updateQualifyAsBreak();
                    $('input[name="description"],' +
                        'input[name="displayDescription"],' +
                        'label[for="allDayChk"],' +
                        '.time_element,#eventColor > ul, ' +
                        '#recurEvery, ' +
                        '#recurMode, ' +
                        '#recurList, ' +
                        '#startingOn, ' +
                        '#endingOn').css('opacity', '1');

                    if (self.modeldata.IsRecurring) {
                        $recurCteCheckbox.show();
                        $recurCteCheckbox.trigger('focus');     // AX-24898.24919.2 .focus();         
                        $recurCteCheckbox.trigger('click');	    // AX-24898.24919.2 $recurCteCheckbox.click();

                        // Enable the recurring controls except the Recur checkbox and the CycleType dropdown.
                        // TODO:

                        if ($("#recurEvery").val() > 1) {
                            self.showWhenCycleMoreThanOne(true);
                        }

                        if (self.cycletype() === 1) {
                            self.showForMonth(true);
                            self.showIfRecurIsChecked(true);
                        }

                        $("#recurMode").prop('disabled', true);

                        // Handle date for split case. Check whether the series extend before current date. If so disable.
                        if (moment(self.modeldata.CteSetDate).format("MM/DD/YYYY") >= moment().format("MM/DD/YYYY")) {
                            $('.datepickerInput').css('opacity', '1');
                            $datepicker.datepicker("option", "disabled", false);
                            $datepicker.prop('disabled', '');
                        }

                        $(".btn-weekdays").removeClass("disabled");
                    } else {
                        $("#recurCteChk").prop('checked', false);
                        $('.datepickerInput').css('opacity', '1');
                        $datepicker.datepicker("option", "disabled", false);
                        $datepicker.prop('disabled', '');
                        showIfRecurIsChecked(false);
                    }

                    $('.cteMenu').dropit();
                } else {
                    /* Disabling controls */

                    $('.slider-button').addClass('disabled');
                    $recurCteCheckbox.prop('disabled', true);
                    $('input[name="description"],' +
                        'input[name="displayDescription"],' +
                        'label[for="allDayChk"],' +
                        'label[for="recurCteChk"],' +
                        '.recurChkGroup,' +
                        '.datepickerInput,' +
                        '.time_element,' +
                        '#eventColor > ul, ' +
                        '#recurEvery, ' +
                        '#recurMode, ' +
                        '#recurList, ' +
                        '#startingOn, ' +
                        '#endingOn').css('opacity', DISABLED_OPACITY);

                    if (self.modeldata.IsRecurring) {
                        if (moment(self.modeldata.StartDateTime).format("MM/DD/YYYY") >= moment().format("MM/DD/YYYY")) {
                            showIfRecurIsChecked(true);
                            $("#recurCteChk").prop('checked', true);
                            $recurCteCheckbox.show();
                            $recurCteCheckbox.trigger('focus');     // AX-24898.24919.2 .focus();
                            $recurCteCheckbox.trigger('click');	    // AX-24898.24919.2 $recurCteCheckbox.click();

                            if ($("#recurEvery").val() > 1) {
                                self.showWhenCycleMoreThanOne(true);
                            }

                            if (self.cycletype() === 1) {
                                self.showForMonth(true);
                            }

                            // Disable recurring elements
                            $(".btn-weekdays").addClass("disabled");
                        }
                        else
                            $("#recurCteChk").prop('checked', false);
                    } else {
                        $("#recurCteChk").prop('checked', false);
                    }

                    $datepicker.datepicker('option', 'disabled', 'disabled');
                    $('.cteMenu').off('click');
                }
            },
            ownerDocument: self
        });

        self.currentValue = {
            'AVAILIN': ko.observable(self.modeldata.ClinicList),
            'DESC': ko.observable(self.modeldata.ExceptionList),
            'ASBREAK': ko.observable(self.modeldata.QualifyAsBreak)
        };

        self.callbacks = {
            'AVAILIN': function (i) {
                var $sliderFrame = $('#qualifyAsBreak .slider-frame');
                var $sliderButton = $sliderFrame.find('.slider-button');
                $sliderButton.removeClass('disabled');
                if (i > 0) {
                    $sliderFrame.removeClass('on');
                    $sliderButton.removeClass('on').html(params.noOpt);
                    $sliderButton.addClass('disabled');
                }
                self.modeldata.SelectedClinicId = i;
            },
            'DESC': function (i) {
                self.modeldata.SelectedExceptionId = i;
                var color = getSelectedColor(self.modeldata.ExceptionList, i)[0];
                $selectedColor.css('background-color', color);
                $descriptionInput.trigger('keyup');             // AX-24898.24919.2 .keyup()

                var obj = self.modeldata.ExceptionList[i];
                $displayDescriptionInput.val(obj.DisplayDesc);

                self.modeldata.QualifyAsBreak = (obj.IsBreak === 1);
                var $sliderFrame = $('#qualifyAsBreak .slider-frame');
                if (self.modeldata.QualifyAsBreak === false) {
                    slideButtonOff($sliderFrame);
                } else {
                    slideButtonOn($sliderFrame);
                }

                self.currentValue['AVAILIN'](getSelectedAvailability(self.modeldata.ClinicList, obj.AvailableClinic));
                self.callbacks['AVAILIN'](obj.AvailableClinic);
            }
        };

        self.currentValue['AVAILIN'](getSelectedAvailability(self.modeldata.ClinicList, self.modeldata.SelectedClinicId));
        self.currentValue['DESC'](getSelectedDesc(self.modeldata.ExceptionList, self.modeldata.SelectedExceptionDesc));
        self.currentValue['ASBREAK'](self.modeldata.QualifyAsBreak);
        self.yesNo = self.currentValue['ASBREAK']() ? params.yesOpt : params.noOpt;

        self.options = ko.observableArray([]);

        self.showoption = ko.computed(function () {
            return (self.options() !== null ? true : false);
        });

        self.optionClick = function (setting, evt) {
            ko.utils.arrayForEach(self.options(), function (opt) {
                opt.Selected(false);
            });
            setting.Selected(true);

            self.currentValue[selected](setting.Description());
            var callback = self.callbacks[selected];
            if (callback) {
                var i = setting.Id ? setting.Id() : setting.Index();
                callback(i);
            }
            closePanel();
        };

        self.selected = '';
        self.settingClick = function (selected, data, evt) {
            self.selected = selected;
            switch (selected) {
                case "AVAILIN":
                    openPanel(self.setEnabled());
                    $("#span-settings-title").text(params.onlyAvailableIn);
                    $(".usersettings-details-header").html(params.onlyAvailableInDetails);
                    $.each(self.modeldata.ClinicList, function (i, v) {
                        v.Selected = (v.Id === self.modeldata.SelectedClinicId);
                    });
                    ko.mapping.fromJS(self.modeldata.ClinicList, {}, self.options);
                    break;
                case "DESC":
                    openPanel(self.setEnabled());
                    $descriptionSearch.hide();
                    $("#span-settings-title").html(params.description);
                    $(".usersettings-details-header").html(params.descriptionDetails);
                    $.each(self.modeldata.ExceptionList, function (i, v) {
                        v.Index = i;
                        v.Selected = (v.Index === self.modeldata.SelectedExceptionId);
                    });
                    ko.mapping.fromJS(self.modeldata.ExceptionList, {}, self.options);
                    break;
                case "ASBREAK":
                    self.modeldata.QualifyAsBreak = !self.modeldata.QualifyAsBreak;
                    //self.currentValue['ASBREAK'](self.modeldata.QualifyAsBreak);
                    break;
            }
        };

        self.onclickedit = function (editType) {
            self.modeldata.IsRecurring = false;
            if (moment(self.modeldata.StartDateTime).format("MM/DD/YYYY") >= moment().format("MM/DD/YYYY")) {
                if (self.modeldata.VacaSet === 0 || self.modeldata.SetException === 1) {
                    self.modeldata.IsRecurring = false;
                    self.showEnabled(true);
                    self.showForSave(true);
                    self.showForEdit(false);
                    self.modeldata.EditMode = 0;
                } else {
                    if (editType === 0) {
                        self.showForEdit(true);
                        self.modeldata.IsRecurring = false;
                        self.modeldata.EditMode = 0;
                    } else {
                        self.modeldata.IsRecurring = editType === 1 ? false : true;
                        self.showEnabled(true);
                        self.showForSave(true);
                        self.showForEdit(false);
                        self.modeldata.EditMode = editType === 1 ? 0 : 1;
                    }
                }
            } else {
                self.modeldata.IsRecurring = false;
                self.showEnabled(true);
                self.showForSave(true);
                self.showForEdit(false);
                self.modeldata.EditMode = 0;
            }

            if (self.modeldata.EditMode === 0 && (editType === 1 || editType === 2)) {
                self.startDateTime = self.modeldata.StartDateTime;
                $datepicker.val(moment(self.startDateTime).format("MM/DD/YYYY"));
            } else if (self.modeldata.EditMode === 1) {
                $datepicker.val(moment(self.modeldata.CteSetDate).format("MM/DD/YYYY"));
            }
        };

        self.onclickdelete = function (deleteType) {
            var warnmsg = "";
            self.blockUI2Process();
            self.modeldata.CteMode = 2; // DataOperation enum for Delete
            // Pass the deletion type requested by the client to the server.(0=single,1=series and 2=entire series.)
            self.modeldata.DeleteMode = deleteType;

            //if (msg.length === 0) {
            if (deleteType === 1 || deleteType === 2) {
                // Exception check on recurring vacation delete
                var doExceptionCheckBeforeDelete = $.ajax({
                    url: '/Scheduler/CheckExceptionInRecurringCtes',
                    data: JSON.stringify(self.modeldata),
                    type: "POST",
                    cache: false,
                    contentType: "application/json"
                });

                function recurringCteExceptionCheckSuccess(data) {
                    // Warn the user that the cte has exceptions
                    var doDelete;
                    if (data === "true") {
                        warnmsg = params.cteExceptionDelete;

                        $("#alert-okcancel-btn").off();
                        $("#alert-cancel-btn").off();
                        $("#alert-okcancel-btn").text(params.okText);
                        $("#alert-okcancel-btn").on("click", function () {
                            // Disable users from clicking it more than once.
                            $("#alert-okcancel-btn").prop('disabled', true);   
                            
                            $('.alert-overlay').hide();
                            self.blockUI2Process();
                            executeDelete();
                            return false;
                        });

                        $("#alert-cancel-btn").on("click", function () {
                            $.unblockUI();
                            $('.alert-overlay').hide();
                        });

                        showAlertDialogOkCancel(warnmsg);
                        $.unblockUI();
                        return false;
                    } else {
                        executeDelete();
                    }
                }

                function recurringCteExceptionCheckError(request, status, error) {
                    $.unblockUI();
                    window.location.href = '/Home/Error';
                }

                doExceptionCheckBeforeDelete.done(recurringCteExceptionCheckSuccess);
                doExceptionCheckBeforeDelete.fail(recurringCteExceptionCheckError);
            } else {
                executeDelete();
            }

            function executeDelete() {
                // Update model from controls
                self.UpdateModelFromControls();

                // Call for checking vacation conflicts
                var doDelete = $.ajax({
                    url: '/Scheduler/ProcessCte',
                    data: JSON.stringify(self.modeldata),
                    type: "POST",
                    cache: false,
                    contentType: "application/json"
                });

                // Placed the promise calls after the function definitions to fix a firefox bug.
                doDelete.done(doDeleteSuccess);
                doDelete.fail(doDeleteError);
            }

            function doDeleteSuccess(data) {
                window.location = document.referrer;
                $.unblockUI();
                return true;
            }

            function doDeleteError(request, status, error) {
                $.unblockUI();
                window.location.href = '/Home/Error';
            }
        };

        self.UpdateModelFromControls = function () {
            var isAllDay = $allDayCheckbox.is(':checked');

            // We are sending the from time and to time alongwith the startdate and enddate and that is 
            // what the following two lines are doing.
            var startDateTime = $datepicker.val() + ' ' + $from.val().replace(' : ', ':').trim();
            var endDateTime = $datepicker.val() + ' ' + $to.val().replace(' : ', ':').trim();
            //---------------------------------------------------------

            var desc = $descriptionInput.val();
            var displayDesc = $displayDescriptionInput.val();

            var rgb = $selectedColor.css('background-color').match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);

            function hex(x) {
                return ("0" + parseInt(x, 10).toString(16)).slice(-2);
            }

            var hexColor = "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
            var avail = getSelectedAvailability(self.modeldata.ClinicList, self.modeldata.SelectedClinicId)[0];

            //---------------------------------------------------------
            self.modeldata.IsAllDay = isAllDay;
            //self.modeldata.QualifyAsBreak = self.modeldata.QualifyAsBreak;
            self.modeldata.SelectedExceptionDesc = desc;
            self.modeldata.DisplayExceptionDesc = displayDesc;
            self.modeldata.CteColor = hexColor;
            self.modeldata.StartDateTime = moment(startDateTime).format("YYYY/MM/DD HH:mm:ss");
            self.modeldata.EndDateTime = moment(endDateTime).format("YYYY/MM/DD HH:mm:ss");

            self.modeldata.StartDateMinutes = setTotalMin($from.val().replace(' : ', ':').trim());
            self.modeldata.EndDateMinutes = setTotalMin($to.val().replace(' : ', ':').trim());

            self.modeldata.Cycle = self.cycle();

            // If cycle is 1 or less than 1 then put the cte date as the date else get the date from user input.
            if (self.cycle() < 2)
                self.modeldata.CycleStartDate = moment(startDateTime).format("YYYY/MM/DD");
            else
                self.modeldata.CycleStartDate = moment($cycleStartDate.val()).format("YYYY/MM/DD");


            self.modeldata.CycleType = self.cycletype();

            if (self.OpMode[self.mode] === "Edit") {
                if (moment(self.modeldata.CteSetDate).format("YYYY/MM/DD") < moment().format("YYYY/MM/DD")) {
                    self.modeldata.CteSetDate = moment(self.modeldata.CteSetDate).format("YYYY/MM/DD");
                }
                else {
                    self.modeldata.CteSetDate = moment(self.modeldata.StartDateTime).format("YYYY/MM/DD");
                }
                self.modeldata.CycleEndDate = moment($cycleEndDate.val()).format("YYYY/MM/DD");
            }
            else if (self.OpMode[self.mode] === "Add") {
                self.modeldata.CteSetDate = moment($datepicker.val()).format("YYYY/MM/DD");
                self.modeldata.CycleEndDate = moment($endingOn.val()).format("YYYY/MM/DD");
            }

            self.modeldata.CycleFrq = self.cyclefreq();

            var $sliderButton = $('#qualifyAsBreak .slider-frame').find('.slider-button').get(0);
            self.modeldata.QualifyAsBreak = $sliderButton.textContent.toUpperCase() === params.yesOpt.toUpperCase() ? true : false;
            //---------------------------------------------------------
        };

        self.saveModel = function (evt) {
            if ($("#cteForm").valid()) {
                // Prevent users from clicking the save button more than once
                $save.prop('disabled', true);

                // Update model from controls
                self.UpdateModelFromControls();
                $('.alert-overlay').hide();
                self.blockUI2Process();

                // Call for getting the conflicts with existing CTEs if any
                var validateCte = $.ajax({
                    url: '/Scheduler/ValidateCte',
                    data: JSON.stringify({ cteModel: self.modeldata }),
                    type: "POST",
                    cache: false,
                    contentType: "application/json"
                });

                function validateCteSuccess(data) {
                    if (data.length === 0) {
                        processNonClinicTime();
                        return false;
                    }

                    // Get the validated Data in proper format for processing
                    var validatedData = JSON.parse(data);
                    var valdnMsg;

                    // Handle if there are any validation warnings. First check is to see if the series needs to be split.
                    if (validatedData.Warnings.length > 0) {
                        splitRecurringCte();
                    } else if (validatedData.Errors.length > 0) {
                        // Check for blocking validations
                        checkBlockingValidations();
                    } else {
                        // If there are no errors or warning go ahead to process the cte.
                        processNonClinicTime();
                        return false;
                    }

                    function splitRecurringCte() {
                        // Check if the series spans past and future.
                        if (!_.some(validatedData.Warnings, function (item) { return item.Text === "SplitPastRecurringCte"; })) {
                            checkBlockingValidations();
                            return false;
                        }
                        valdnMsg = params.splitRecurringCTEs + '\n' + params.splitRecurringCTEQuestion;

                        $("#alert-yes-btn").off();
                        $("#alert-no-btn").off();
                        $("#alert-yes-btn").on("click", function () {
                            // Disable users from clicking it more than once.
                            $("#alert-yes-btn").prop('disabled', true);                             

                            $('.alert-overlay').hide();
                            self.blockUI2Process();
                            // User wants to split the past CTEs. Fire the callback to split it.
                            var processForSplitting = $.ajax({
                                url: '/Scheduler/ProcessSplittingRecurringCtes',
                                data: JSON.stringify({ cteModel: self.modeldata, validationResult: self.validationResult }),
                                type: "POST",
                                cache: false,
                                contentType: "application/json"
                            });

                            function processForSplittingSuccess(newdata) {
                                // The split is done successfully. 
                                self.modeldata = JSON.parse(newdata);
                                // Guard for spanish.
                                //self.modeldata.StartDateTime = moment(self.modeldata.StartDateTime).format("YYYY/MM/DD HH:mm:ss");
                                //self.modeldata.EndDateTime = moment(self.modeldata.EndDateTime).format("YYYY/MM/DD HH:mm:ss");
                                self.modeldata.StartDateTime = moment(self.modeldata.StartDateTime).format("YYYY/MM/DD ");  //.format("YYYY/MM/DD HH:mm:ss");
                                self.modeldata.StartDateTime += formatTimeHourMin(self.modeldata.StartDateMinutes);
                                self.modeldata.EndDateTime = moment(self.modeldata.EndDateTime).format("YYYY/MM/DD ");  //.format("YYYY/MM/DD HH:mm:ss");
                                self.modeldata.EndDateTime += formatTimeHourMin(self.modeldata.EndDateMinutes);

                                self.modeldata.CycleStartDate = moment(self.modeldata.CycleStartDate).format("YYYY/MM/DD");
                                self.modeldata.CycleEndDate = moment(self.modeldata.CycleEndDate).format("YYYY/MM/DD");
                                self.modeldata.CteSetDate = moment(self.modeldata.CteSetDate).format("YYYY/MM/DD");

                                // Call the validator again with the newly created cte after the split to get the validation results.
                                var postSplitValidateCte = $.ajax({
                                    url: '/Scheduler/ValidateCte',
                                    data: JSON.stringify({ cteModel: self.modeldata }),
                                    type: "POST",
                                    cache: false,
                                    contentType: "application/json"
                                });

                                postSplitValidateCte.done(postSplitValidateCteSuccess);
                                postSplitValidateCte.fail(postSplitValidateCteError);
                            }

                            function processForSplittingFail(request, status, error) {
                                $.unblockUI();
                                window.location.href = '/Home/Error';
                            }

                            processForSplitting.done(processForSplittingSuccess);
                            processForSplitting.fail(processForSplittingFail);
                        });

                        $("#alert-no-btn").on("click", function () {
                            $.unblockUI();
                            $('.alert-overlay').hide();

                            // Enable users to click save button
                            $save.prop('disabled', false);
                        });
                        showAlertDialogYesNo(valdnMsg);
                        $.unblockUI();
                        return false;
                    }

                    function postSplitValidateCteSuccess(psdata) {
                        // Validation post splitting of ctes.
                        validatedData = JSON.parse(psdata);

                        // Start the validations beginning with blocking validations if any.
                        checkBlockingValidations();
                    }

                    function postSplitValidateCteError() {
                        $.unblockUI();
                        window.location.href = '/Home/Error';
                    }

                    function checkBlockingValidations() {
                        // Handle if there is any validation error.
                        if (validatedData.Errors.length > 0) {
                            // Take the json object, get the unique key values then join them.
                            var cteList = $.map(_.uniq(validatedData.Errors[0].ListConflicts, function (item) {
                                return item.ExceptionType;
                            }), function (value, key) { return value.ExceptionType; }).join('\n');

                            // Need to get the first error only.
                            var apptList = $.map(validatedData.Errors[0].ListConflicts, function (value, key) { return value.PatientName + " (" + value.Chart + ")"; }).join('\n');

                            var isBlocking = false;
                            if (self.modeldata.IsRecurring) {
                                if (validatedData.Errors[0].FieldName === "OverlappingCte") {
                                    valdnMsg = params.cannotSaveCteConflictsCTEs + '\n\n' + cteList;
                                    showAlertDialogOk(valdnMsg);
                                    $.unblockUI();
                                    isBlocking = true;
                                } else if (validatedData.Errors[0].FieldName === "AppointmentConflict") {
                                    valdnMsg = params.cannotSaveCteConflictsAppts + '\n\n' + params.pleaseSaveCteAxium;
                                    showAlertDialogOk(valdnMsg);
                                    $.unblockUI();
                                    isBlocking = true;
                                }
                            } else {
                                if (validatedData.Errors[0].FieldName === "OverlappingCte") {
                                    valdnMsg = params.cannotSaveCteConflictsCTEs + '\n\n' + cteList;
                                    showAlertDialogOk(valdnMsg);
                                    $.unblockUI();
                                    isBlocking = true;
                                } else if (validatedData.Errors[0].FieldName === "AppointmentConflict") {
                                    valdnMsg = params.cannotSaveCteConflictsAppts + '\n\n' + apptList + '\n\n' + params.pleaseSaveCteAxium;
                                    showAlertDialogOk(valdnMsg);
                                    $.unblockUI();
                                    isBlocking = true;
                                }
                            }

                            if (isBlocking) {
                                // Enable users to click save button
                                $save.prop('disabled', false);                                

                                return false;
                            }

                            $('.alert-overlay').hide();

                            var url = params.returnUrl + date + '&view=' + view;
                            window.location = url;
                            return true;
                        }
                        else
                            overLapWarnings();
                    }

                    function overLapWarnings() {
                        // Check if there is overlapWarning
                        if (!_.some(validatedData.Warnings, function (item) { return item.Text === "OverlappingCte"; })) {
                            breakTimes();
                            return false;
                        }

                        // Process Overlapped cte warning.
                        var wrnList = _.uniq(_.find(validatedData.Warnings, function (item) { return item.Text === "OverlappingCte"; }).ListConflicts, function (e) { return e.ExceptionType; });
                        var cteListItems = _.map(wrnList, function (wItem) {
                            return wItem.ExceptionType;
                        }).join('\n');

                        valdnMsg = params.confirmSaveCteConflictsCTEs + '\n\n' + cteListItems;

                        $("#alert-yes-btn").off();
                        $("#alert-no-btn").off();
                        $("#alert-yes-btn").on("click", function () {
                            // Disable users from clicking it more than once.
                            $("#alert-yes-btn").prop('disabled', true); 
                            
                            $('.alert-overlay').hide();
                            self.blockUI2Process();
                            breakTimes();
                        });

                        $("#alert-no-btn").on("click", function () {
                            $.unblockUI();
                            $('.alert-overlay').hide();

                            // Enable users to click save button
                            $save.prop('disabled', false);   
                        });
                        showAlertDialogYesNo(valdnMsg);
                        $.unblockUI();
                        return false;
                    }

                    function breakTimes() {
                        // Check if there is break time warning
                        if (!_.some(validatedData.Warnings, function (item) { return item.Text === "BreakTime"; })) {
                            exceptionForRecurringCte();
                            return false;
                        }

                        valdnMsg = params.breakTimes;

                        $("#alert-yes-btn").off();
                        $("#alert-no-btn").off();
                        $("#alert-yes-btn").on("click", function () {
                            // Disable users from clicking it more than once.
                            $("#alert-yes-btn").prop('disabled', true);                             

                            // Disable users from clicking it more than once.
                            $("#alert-yes-btn").prop('disabled', true);   
                            
                            $('.alert-overlay').hide();
                            self.blockUI2Process();
                            exceptionForRecurringCte();
                        });

                        $("#alert-no-btn").on("click", function () {
                            $.unblockUI();
                            $('.alert-overlay').hide();

                            // Enable users to click save button
                            $save.prop('disabled', false);   
                        });
                        showAlertDialogYesNo(valdnMsg);
                        $.unblockUI();
                        return false;
                    }

                    function exceptionForRecurringCte() {
                        // Check if there is break time warning
                        if (!_.some(validatedData.Warnings, function (item) { return item.Text === "ExceptionForRecurringCte"; })) {
                            processNonClinicTime();
                            return false;
                        }

                        valdnMsg = params.cteExceptionDelete;

                        $("#alert-yes-btn").off();
                        $("#alert-no-btn").off();
                        $("#alert-yes-btn").on("click", function () {
                            // Disable users from clicking it more than once.
                            $("#alert-yes-btn").prop('disabled', true); 
                            
                            $('.alert-overlay').hide();
                            self.blockUI2Process();
                            processNonClinicTime();
                            return false;
                        });

                        $("#alert-no-btn").on("click", function () {
                            $.unblockUI();
                            $('.alert-overlay').hide();

                            // Enable users to click save button
                            $save.prop('disabled', false);   
                        });
                        showAlertDialogYesNo(valdnMsg);
                        $.unblockUI();
                        return false;
                    }

                    return false;
                }

                function processNonClinicTime() {
                    self.modeldata.CycleEndDate = moment(self.modeldata.CycleEndDate).format("YYYY/MM/DD");
                    self.modeldata.CteSetDate = moment(self.modeldata.CteSetDate).format("YYYY/MM/DD");
                    //Validation done so go ahead and process that CTE.
                    var processCte = $.ajax({
                        url: '/Scheduler/ProcessCte',
                        data: JSON.stringify({ cteModel: self.modeldata, validationResult: self.validationResult }),
                        type: "POST",
                        cache: false,
                        contentType: "application/json"
                    });

                    processCte.done(processCteSucess);
                    processCte.fail(processCteError);
                }

                function validateCteError(request, status, error) {
                    $.unblockUI();
                    window.location.href = '/Home/Error';
                }

                validateCte.done(validateCteSuccess);
                validateCte.fail(validateCteError);

                function processCteSucess(data) {
                    // CTE Process has completed. Show the saved message.
                    $('.toast').remove();
                    toastr.options.positionClass = 'toast-bottom-left';
                    toastr.success(params.saved);

                    $('.alert-overlay').hide();
                    var url = params.returnUrl + date + '&view=' + view;
                    window.location = url;
                    $.unblockUI();
                    return false;
                }

                function processCteError(request, status, error) {
                    $.unblockUI();
                    window.location.href = '/Home/Error';
                }
            }
        };
    });
    //#endregion

    //#region Other event bindings
    // Bind Cycle Type dropdown
    $("#recurMode").on("change", function () {
        if ($(this).val() === "1") {
            self.showForMonth(true);
        } else {
            self.showForMonth(false);
        }
    });

    // Bind Cycle
    $("#recurEvery").on("keyup", function () {
        if (Math.floor($(this).val()) > 1) {
            self.showWhenCycleMoreThanOne(true);
        } else {
            self.showWhenCycleMoreThanOne(false);
        }
        
        /*if (isNaN($(this).val())) {
            self.cycle(0);
        }*/
    });

    // Suppress alphabets and decimal for recurEvery input box.
    $("#recurEvery").on('keypress', function (e) {		// AX-24898.24919.2 .keypress(function (e) {
        var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
        var ewhich = [];
        var ekeyCode = [8,37,38,39,40,46]; // backspace, leftarrow, toparrow, rightarrow, bottomarrow, delete
        
        var ew = e.which;
        var ek = e.keyCode;

        for (var i = 48; i < 58; i++)
            ewhich.push(i);
        
        if (!(ewhich.indexOf(ew) >= 0)) {
            if (isFirefox && (ekeyCode.indexOf(ek) >= 0)) {
                return true;
            }

            e.preventDefault();
        }
    });
    //#endregion

    serialized = serialize();
    if (allDayReq === 'true') {
        $allDayCheckbox.trigger('click');	// AX-24898.24919.2 $allDayCheckbox.click();
    }

    function pad(str, max) {
        str = str.toString();
        return str.length < max ? pad("0" + str, max) : str;
    }
    // Format time in hh : mm PM
    function formatTime(totalMinutes) {
        var hours = parseInt(totalMinutes / 60, 10);
        var min = totalMinutes - (hours * 60);
        var valResult = (hours > 12 ? pad(hours - 12, 2) : pad(hours, 2)) + " : " + pad(min, 2) + (hours >= 12 ? " PM" : " AM");
        return (valResult);
    }
    // Format time in HH:mm
    function formatTimeHourMin(totalMinutes) {
        var hours = parseInt(totalMinutes / 60, 10);
        var min = totalMinutes - (hours * 60);
        var valResult = pad(hours, 2) + ":" + pad(min, 2) + ":00";
        return (valResult);
    }
    // From time as string (9:10 AM) to number from midnight
    function setTotalMin(strTime) {
        var timeSplit = strTime.split(':');
        var minStr = timeSplit[1].substr(0, 2);
        var ampm = timeSplit[1].substr(3, 2);

        var hour = parseInt(timeSplit[0], 10);
        var min = parseInt(minStr, 10);
        if (ampm.toUpperCase() == "PM" && hour < 12)
            hour += 12;     // Add 12 hours; except when is 12
        if (ampm.toUpperCase() == "AM" && hour == 12)
            hour = 0;       // For 12 AM needs to be cero
        return (hour * 60) + min;
    }    

    $weekdayButton.on('click', function () {     	// AX-27042
        $(this).toggleClass('active');
    });
}

