﻿(function ($) {

    var id = 10; //TODO UBS 11/15/2010: it needs to go away.

    $.widget("ui.tripCalendar", {

        options: {
            timeslotsPerHour: 2,
            beginDate: null,        //trip begin date
            endDate: null,          //trip end date
            currentDate: null,      //the date the user selected.
            scrollToHour: 9,        //UBS 4/20/2011: Scrolls to the hour once the calendar is loaded.
            jsonTrip: null,         //json trip object.
            flgIsMobileView: false,                 //Indicates if the current view is for Mobile phones.
            flgIsMobileListView: false,             //Indicates if the current Mobile view on Mobile phones is List View.
            flgIsEntireCalendarReadyonly: false,    //Indicates if the current calendar is all read-only (facebook, twitter)
            defaultTextLegButtons: "Days in [CITY]", //default text to be shown on Leg buttons.
            tripCalendarElement: this,
            eventEditContainerID: "eventEditContainerID", //ID of the DIV that shows the Event container.
            datePickerElement: null, //the Trip-DatePicker HTML element
            loadingElement: null,    //the div showing the Updating ..status
            eventRender: function (calEvent, $event, self) {
                if (!self._isNewEventAndReadonlyCalendar(calEvent)) {
                    if (calEvent.end.getTime() < new Date().getTime()) {
                        $event.css("backgroundColor", "#aaa");
                        $event.find(".time").css({
                            "backgroundColor": "#999",
                            "border": "1px solid #888"
                        });
                    }

                    if (calEvent.readOnly) {
                        var sContent = "Read only - " + calEvent.description;
                    }
                    else {
                        var sContent = calEvent.description;
                    }
                    $event.attr("title", sContent);
                }
            },

            draggable: function (calEvent, $event, self) {
                //alert('draggable callback works!');
                //return calEvent.readOnly != true;
                var flgReturn = true;
                //flgReturn = (calEvent.readOnly != true) && !self.isMobileDayView();
                flgReturn = (calEvent.readOnly != true) && !self.isMobileDayView() && !self.options.flgIsEntireCalendarReadyonly; //UBS 5/4/2011: readonly calendar for facebook or twitter
                return flgReturn
            },

            resizable: function (calEvent, $event, self) {
                //alert('resizable callback works!');
                //return calEvent.readOnly != true;
                var flgReturn = true;
                //flgReturn = (calEvent.readOnly != true) && !self.isMobileDayView();
                flgReturn = (calEvent.readOnly != true) && !self.isMobileDayView() && !self.options.flgIsEntireCalendarReadyonly; //UBS 5/4/2011: readonly calendar for facebook or twitter
                return flgReturn
            },

            eventNew: function (calEvent, $event, self) {
                //UBS 5/4/2011: readonly calendar for facebook or twitter
                if (!self.options.flgIsEntireCalendarReadyonly) {
                    if (!self.options.flgIsMobileView) {
                        self._renderNewTripEvent(calEvent, $event);
                    }
                    else {
                        //Ticket #34 UBS 10/20/2011: If its mobile-calendar then we need to render-weekcalendar as for some reason (though behavior was not the same before)
                        //                           the cache tripCalendar widget does not have the weekCalendar inside it.
                        self._renderMobileTripCalendar();
                        //END-Ticket #34 UBS 10/20/2011: 
                        self._updateMobileEventEditContainerID(calEvent);
                        var jsonPlan = null;
                        jsonPlan = JSON.parse(calEvent.replace(/&amp;#39;/gi, '\'').replace(/&#39;/gi, '').replace(/&amp;quot;/gi, '"').replace(/&quot;/gi, '"').replace(/\n/gi, "\\n").replace(/\r/gi, "\\r"));
                        self._renderMobileTripEventClick(new self._createCalEvent(jsonPlan), calEvent, null, true);
                        $("#" + self.options.eventEditContainerID).find('ul').listview("refresh");
                        $("#" + self.options.eventEditContainerID).find("select").selectmenu('refresh');
                        $("#" + self.options.eventEditContainerID).find("select").selectmenu('refresh', true);
                    }
                }
            },

            eventDrop: function (calEvent, $event, self) {
                //UBS 5/4/2011: readonly calendar for facebook or twitter
                if (!self.options.flgIsEntireCalendarReadyonly) {
                    //alert('eventDrop callback works!');
                    self._updatePlan(calEvent, $event, self);
                    //self._updateEventsJSONData();
                }
            },

            eventResize: function (calEvent, $event, self) {
                //UBS 5/4/2011: readonly calendar for facebook or twitter
                if (!self.options.flgIsEntireCalendarReadyonly) {
                    //alert('eventResize callback works!');
                    self._updatePlan(calEvent, $event, self);
                    //self._updateEventsJSONData();
                }
            },

            eventClick: function (calEvent, $event, self, flgIsDayViewEventEditClick) {
                //UBS 5/4/2011: readonly calendar for facebook or twitter
                if (!self.options.flgIsEntireCalendarReadyonly) {
                    if (!self.options.flgIsMobileView) {
                        self._renderTripEventClick(calEvent, $event);
                    }
                    else {
                        if (self.options.flgIsMobileView) {
                            //Ticket #34 UBS 10/20/2011: If its mobile-calendar then we need to render-weekcalendar as for some reason (though behavior was not the same before)
                            //                           the cache tripCalendar widget does not have the weekCalendar inside it.
                            self._renderMobileTripCalendar();
                            //END-Ticket #34 UBS 10/20/2011:
                        }
                        if (!self.isMobileDayView() || flgIsDayViewEventEditClick) {
                            self._updateMobileEventEditContainerID(calEvent);
                            var jsonPlan = null;
                            jsonPlan = JSON.parse(calEvent.replace(/&amp;#39;/gi, '\'').replace(/&#39;/gi, '').replace(/&amp;quot;/gi, '"').replace(/&quot;/gi, '"').replace(/\n/gi, "\\n").replace(/\r/gi, "\\r"));
                            self._renderMobileTripEventClick(new self._createCalEvent(jsonPlan), calEvent, null, false);
                            $("#" + self.options.eventEditContainerID).find('ul').listview("refresh");
                            $("#" + self.options.eventEditContainerID).find('ul').listview("refresh");
                            $("#" + self.options.eventEditContainerID).find("select").selectmenu('refresh');
                            $("#" + self.options.eventEditContainerID).find("select").selectmenu('refresh', true);
                        }
                        else {
                            //self.changePageViewEventForMobileDayView(calEvent);
                        }
                    }
                    //self._updateEventsJSONData();
                }
            },

            eventMouseover: function (calEvent, $event, self) {
                //alert(' eventMouseover callback works!');                
            },

            eventMouseout: function (calEvent, $event, self) {
                //alert('eventMouseout callback works!');
            },

            noEvents: function (self) {
                //alert('noEvents callback works!');
            },

            data: function (start, end, callback, self) {
                //callback(self._getEventData());
                callback(self._getTripPlans());
            }
        }, //end of options

        /*
        * Called at the time construction. Just once in Page life, requires a refresh to call this again.
        */
        //_create: function () {
        //    var options = this.options;
        //    var self = this;

        //    //$("#" + options.eventEditContainerID).hide();
        //    self._renderTripCalendar();

        //}, //end of _create()

        /*
        * is called both on construction and for re-initializing the function.
        */
        _init: function () {
            var options = this.options;
            var self = this;

            //$("#" + options.eventEditContainerID).hide();    
            if (!options.flgIsMobileView) {
                self._renderTripCalendar();
            }
            else {
                self._renderMobileTripCalendar();
            }

            options.datePickerElement.data("calEventsNewToInsert", []);
            options.datePickerElement.data("calEventsToUpdate", []);
            options.datePickerElement.data("calEventsToDelete", []);

            if (options.flgIsMobileView && tripCalendar_Cache != undefined) {
                //tripCalendar_Cache.push(this);
                //tripCalendar_Cache.push({ 'iTripId': options.jsonTrip.iTripID, 'item': this })
                var flgCacheFound = false;
                $.each(tripCalendar_Cache, function (i, calendar) {
                    if (calendar.iTripId == options.jsonTrip.iTripID) {
                        calendar.item = self;
                        flgCacheFound = true;
                        return false;
                    }
                });
                if (!flgCacheFound) {
                    tripCalendar_Cache.push({ 'iTripId': options.jsonTrip.iTripID, 'item': self })
                }
            }

        }, //end of _create()

        _isNewEventAndReadonlyCalendar: function (calEvent) {
            var self = this;
            var flgReturn = true;
            if (calEvent != undefined && calEvent != null && calEvent.title == "New Event") {
                flgReturn = self.options.flgIsEntireCalendarReadyonly;
            } else {
                flgReturn = false;
            }
            return flgReturn;
        },

        initializeWeekCalendarForMobile: function () {
            var self = this;
            self._renderMobileTripCalendar();
        },

        changePageViewEventForMobileDayView: function (calEvent) {
            var self = this;
            var formattedDate = self.element.weekCalendar("formatDate", self.options.currentDate, "m/d/Y");
            var eCallbackType = Enums.MobileCallbackTypes.eMobileCalendarCallbackDayView;
            var callbackArgs = {
                "eCallbackType": eCallbackType,
                "iTripID": calEvent.tripId,
                "iPlanID": calEvent.id,
                "currentDate": self.options.currentDate,
                "jsonTrip": self.options.jsonTrip
            };

            var sKey = Math.floor(Math.random() * 100000);
            $.mobile.changePage("/Trip/MobileTripCalendarViewEvent?iTripId=" + calEvent.tripId + "&iPlanId=" + calEvent.id + "&key=" + sKey,
                        'slide',
                        true,
                        false);

            //$.mobile.activePage.data("cancelExistingEventCallbackArgs", callbackArgs);
        },

        refreshTrip: function (newJsonTrip) {
            var self = this;
            if (newJsonTrip != null) {
                self.options.jsonTrip = newJsonTrip;
                self.element.weekCalendar('clearCalendarElement'); //removes the 'wc-container' div i.e. the entire calendar element
                self._init();
            }
        },

        clearCalendarElement: function () {
            var self = this;
            self.element.weekCalendar('clearCalendarElement'); //removes the 'wc-container' div i.e. the entire calendar element
        },

        clear: function () {
            var self = this;
            var dialogElement = this.element;
            this.element.weekCalendar('clear');
            self.options.datePickerElement.data("calEventsNewToInsert", []);
            self.options.datePickerElement.data("calEventsToUpdate", []);
            self.options.datePickerElement.data("calEventsToDelete", []);
        },

        getOptions: function () {
            return this.options;
        },

        isMobileDayView: function () {
            return this.element.weekCalendar('isMobileDayView');
        },

        showLoading: function () {
            var self = this;
            $.each(self.element.find('#loading-calendar'), function (i, element) {
                if ($(this).is(':visible') == false) {
                    $(this).show();
                }
            });
            $.each(self.element.find('.wc-container'), function (i, element) {
                if (!$(this).hasClass('wc-container-hidden')) {
                    $(this).addClass('wc-container-hidden');
                }
            });
        },

        hideLoading: function () {
            var self = this;
            $.each(self.element.find('#loading-calendar'), function (i, element) {
                $(this).hide();
            });
            $.each(self.element.find('.wc-container'), function (i, element) {
                if ($(this).hasClass('wc-container-hidden')) {
                    $(this).removClass('wc-container-hidden');
                }
            });
        },

        saveMobileEvent: function (jsonPlanText) {
            var self = this;
            var options = this.options;

            //New Event form fields.
            var startField = $("#" + options.eventEditContainerID).find("select[name='start']");
            var endField = $("#" + options.eventEditContainerID).find("select[name='end']");
            var titleField = $("#" + options.eventEditContainerID).find("input[name='title']");
            var bodyField = $("#" + options.eventEditContainerID).find("textarea[name='body']");
            var dateField = $("#" + options.eventEditContainerID).find("select[name='date']");
            var typeField = $("#" + options.eventEditContainerID).find("select[name='type']");
            var viewTypeField = $("#" + options.eventEditContainerID).find("select[name='viewType']"); //Mushtaq [Ticket# 14] [18 May 2010]
            var attendeesField = $("#" + options.eventEditContainerID).find("input[name='attendees']");
            //added by mushtaq
            var smsAlertField = $("#" + options.eventEditContainerID).find("input[name='SMSAlert']");
            var phoneNumberField = $("#" + options.eventEditContainerID).find("input[name='phoneNumber']");
            var updatePhoneProfileField = $("#" + options.eventEditContainerID).find("input[name='updatePhoneProfile']");

            var locationField = $("#" + options.eventEditContainerID).find("input[name='location']");
            var attendeesLiField = $("#" + options.eventEditContainerID).find("li[rel='attendees']");
            var locationLiField = $("#" + options.eventEditContainerID).find("li[rel='location']");

            //added by mushtaq
            var smsAlertLiField = $("#" + options.eventEditContainerID).find("li[rel='SMSAlert']");
            var phoneNumberLiField = $("#" + options.eventEditContainerID).find("li[rel='phoneNumber']");

            var calEvent = new self._createCalEvent(null);

            //First double check the containerid is right.
            jsonPlanObj = JSON.parse(jsonPlanText.replace(/&amp;#39;/gi, '\'').replace(/&#39;/gi, '').replace(/&amp;quot;/gi, '"').replace(/&quot;/gi, '"').replace(/\n/gi, "\\n").replace(/\r/gi, "\\r"));
            //UBS 3/15/2011: not sure if this logic is needed any more. Therefore commented it out.
            //if (self.options.eventEditContainerID.split("_").length == 2) {
            //    self.options.eventEditContainerID = self.options.eventEditContainerID + "_" + jsonPlanObj.ID;
            //} else {
            //    var splits = self.options.eventEditContainerID.split("_");
            //    if (splits.length == 3) {
            //        //E.g: eventEditContainer_<%:Model.TRIP_ID %>_<%:Model.ID %>
            //        //[0] = eventEditContainer, [1] = TripID, [2] = Plan ID
            //        self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlanObj.ID;
            //    }
            //}

            calEvent.id = jsonPlanObj.ID;
            calEvent.start = new Date(startField.val());
            calEvent.end = new Date(endField.val());
            //Ticket #34 UBS 10/20/2011: check if value is not undefined otherwise it will cause exceptions below
            if (titleField.val() != undefined) {
                calEvent.title = titleField.val();
            }
            //Ticket #34 UBS 10/20/2011: check if value is not undefined otherwise it will cause exceptions below
            if (bodyField.val() != undefined) {
                calEvent.description = bodyField.val();
            }
            calEvent.readOnly = false;
            calEvent.tripId = options.jsonTrip.iTripID;

            calEvent.type = typeField.val();
            calEvent.viewType = viewTypeField.val(); //Mushtaq [Ticket# 14] [18 May 2010]
            if (attendeesField.val() != "david@trx.com,jones@yahoo.com") {
                //Make sure you dont add watermark text
                calEvent.attendees = attendeesField.val();
            }
            else {
                calEvent.attendees = "";
            }
            if (locationField.val() != "123 Greenville St, Dallas, TX") {
                //Make sure you dont add watermark text
                calEvent.location = locationField.val();
            }
            else {
                calEvent.location = "";
            }

            //added by mushtaq --start
            if ($smsAlertField.length > 0) {
                calEvent.sendSMSAlert = $smsAlertField[0].checked;
            }
            if ($smsAlertField.length > 0 && $smsAlertField[0].checked == true) {
                calEvent.phoneNumber = phoneNumberField[0].value;
            }
            else {
                calEvent.phoneNumber = "";
            }
            // calEvent.updatePhoneProfile = updatePhoneProfileField[0].checked;
            if (updatePhoneProfileField.length > 0 && updatePhoneProfileField[0].checked == true) {
                calEvent.updatePhoneProfile = updatePhoneProfileField[0].checked;
            }
            //end -added by mushtaq

            //Ticket #34 UBS 10/20/2011: Added .title != undefined to the IF below.
            if (calEvent.title != undefined && calEvent.title.length > 0 && calEvent.start != undefined && calEvent.end != undefined &&
                self._isValidMeetingOrRestaurantEvent(calEvent) && self._isValidPhoneNumber(calEvent)) {

                var jsonPlan = JSON.stringify(self._createJsonPlan(calEvent, options.jsonTrip.iTripID));

                $.post("/Trip/MobileTripCalendarEditEvent",
                    {
                        "iTripID": self.options.jsonTrip.iTripID,
                        "sJsonPlan": jsonPlan
                    },
                    function (data) {
                        self._onSuccessMobileSaveEvent(data, self);
                    },
                    "json");

            }
            else {
                //Show the error warnings and hide the required indicators.
                self._displayValidationErrors($("#" + options.eventEditContainerID), calEvent);
                if (self.options.flgIsMobileView) {
                    //$.mobile.pageLoading(true);
                    $.mobile.hidePageLoadingMsg(); //Ticket #34 UBS 10/21/2011: Upgraded to version 1.0 RC2
                }
            }

        },

        deleteMobileEvent: function (jsonPlanText) {
            var self = this;
            var options = this.options;
            var calEvent = new self._createCalEvent(null);

            //First double check the containerid is right.
            jsonPlanObj = JSON.parse(jsonPlanText.replace(/&amp;#39;/gi, '\'').replace(/&#39;/gi, '').replace(/&amp;quot;/gi, '"').replace(/&quot;/gi, '"').replace(/\n/gi, "\\n").replace(/\r/gi, "\\r"));
            if (self.options.eventEditContainerID.split("_").length == 2) {
                self.options.eventEditContainerID = self.options.eventEditContainerID + "_" + jsonPlanObj.ID;
            } else {
                var splits = self.options.eventEditContainerID.split("_");
                if (splits.length == 3) {
                    //E.g: eventEditContainer_<%:Model.TRIP_ID %>_<%:Model.ID %>
                    //[0] = eventEditContainer, [1] = TripID, [2] = Plan ID
                    self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlanObj.ID;
                }
            }

            calEvent.id = jsonPlanObj.ID;

            $.post("/Trip/MobileTripCalendarDeleteEvent",
                {
                    "iTripID": self.options.jsonTrip.iTripID,
                    "iPlanID": jsonPlanObj.ID
                },
                function (data) {
                    self._onSuccessMobileDeleteEvent(data, self);
                },
                "json");

        },

        _updateMobileEventEditContainerID: function (jsonPlanText) {
            var self = this;
            var jsonPlan = null;
            var dayMonth = null;

            if (!self.isMobileDayView()) {
                jsonPlan = JSON.parse(jsonPlanText.replace(/&amp;#39;/gi, '\'').replace(/&#39;/gi, '').replace(/&amp;quot;/gi, '"').replace(/&quot;/gi, '"').replace(/\n/gi, "\\n").replace(/\r/gi, "\\r"));
                dayMonth = self.element.weekCalendar("formatDate", self._dateDeserialize(jsonPlan.StartDateTime), "dM"); //"18Feb"
            } else {
                if (typeof (jsonPlanText) == "object") {
                    jsonPlan = self._createJsonPlan(jsonPlanText, self.options.jsonTrip.iTripID)
                    dayMonth = self.element.weekCalendar("formatDate", jsonPlan.StartDateTime, "dM"); //"18Feb"
                } else if (typeof (jsonPlanText) == "string") {
                    jsonPlan = JSON.parse(jsonPlanText.replace(/&amp;#39;/gi, '\'').replace(/&#39;/gi, '').replace(/&amp;quot;/gi, '"').replace(/&quot;/gi, '"').replace(/\n/gi, "\\n").replace(/\r/gi, "\\r"));
                    dayMonth = self.element.weekCalendar("formatDate", self._dateDeserialize(jsonPlan.StartDateTime), "dM"); //"18Feb"
                }
            }

            //if (!self.isMobileDayView()) {
            //    var dayMonth = self.element.weekCalendar("formatDate", self._dateDeserialize(jsonPlan.StartDateTime), "dM"); //"18Feb"
            //} else {
            //    var dayMonth = self.element.weekCalendar("formatDate", jsonPlan.StartDateTime, "dM"); //"18Feb"
            //}

            if (self.options.eventEditContainerID.split("_").length == 2) {
                //self.options.eventEditContainerID = self.options.eventEditContainerID + "_" + jsonPlan.ID;
                var splits = self.options.eventEditContainerID.split("_");
                if (jsonPlan.ID > 0) {
                    //This means its event-update therefore the id = "eventEditContainer_TRIP_ID_PLAN_ID" 
                    //self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlan.ID;
                    if (jsonPlan.KeyIdentifier != null && jsonPlan.KeyIdentifier != "") {
                        self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlan.ID + "_" + jsonPlan.KeyIdentifier;
                    } else {
                        self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlan.ID;
                    }
                } else {
                    //This means its A NEW event therefore the id = "eventEditContainer_TRIP_ID_018Feb" 
                    //self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlan.ID + dayMonth;
                    if (jsonPlan.KeyIdentifier != null && jsonPlan.KeyIdentifier != "") {
                        self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlan.ID + "_" + dayMonth + "_" + jsonPlan.KeyIdentifier;
                    } else {
                        self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlan.ID + "_" + dayMonth;
                    }
                }
            } else {
                var splits = self.options.eventEditContainerID.split("_");
                if (splits.length == 3) {
                    if (jsonPlan.ID > 0) {
                        //This means its event-update therefore the id = "eventEditContainer_TRIP_ID_PLAN_ID" 
                        //self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlan.ID;
                        if (jsonPlan.KeyIdentifier != null && jsonPlan.KeyIdentifier != "") {
                            self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlan.ID + "_" + jsonPlan.KeyIdentifier;
                        } else {
                            self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlan.ID;
                        }
                    } else {
                        //This means its A NEW event therefore the id = "eventEditContainer_TRIP_ID_018Feb"
                        //self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlan.ID + dayMonth;
                        if (jsonPlan.KeyIdentifier != null && jsonPlan.KeyIdentifier != "") {
                            self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlan.ID + "_" + dayMonth + "_" + jsonPlan.KeyIdentifier;
                        } else {
                            self.options.eventEditContainerID = splits[0] + "_" + splits[1] + "_" + jsonPlan.ID + "_" + dayMonth;
                        }
                    }
                }
            }
        },

        _onSuccessMobileSaveEvent: function (data, self) {
            if (data.flgResult) {
                var sTripCalUrl = "/Trip/MobileTripCalendar?iTripId=" + self.options.jsonTrip.iTripID;
                var calendarPage = null;
                var iCalendarPageIndex = -1;
                var iTotalPagesInHist = $.mobile.urlHistory.length;
                var pagesToRemove = [];
                var eCallbackType = Enums.MobileCallbackTypes.eMobileCalendarCallback;

                if (self.isMobileDayView()) {
                    eCallbackType = Enums.MobileCallbackTypes.eMobileCalendarCallbackDayView;
                }

                $.each($.mobile.urlHistory.stack, function (i, page) {
                    if (page.url == sTripCalUrl) {
                        calendarPage = page;
                        iCalendarPageIndex = i;
                        return false;
                    }
                });

                pagesToRemove.push("/Trip/MobileTripCalendarViewEvent?iTripId=" + data.Trip.iTripID + "&iPlanId=" + data.Plan.ID);
                pagesToRemove.push("/Trip/MobileTripCalendarEditEvent?iTripId=" + data.Trip.iTripID + "&iPlanId=" + data.Plan.ID);

                if (calendarPage != null) {
                    self._myChangePage(calendarPage,
                            iCalendarPageIndex,
                            pagesToRemove,
                            {
                                "eCallbackType": eCallbackType,
                                "jsonTrip": data.Trip,
                                "jsonPlan": data.Plan
                            }
                        );
                }

            } else {
                alert('Could not Modify. Please retry later!');
            }
        },

        _onSuccessMobileDeleteEvent: function (data, self) {
            if (data.flgResult) {
                var sTripCalUrl = "/Trip/MobileTripCalendar?iTripId=" + self.options.jsonTrip.iTripID;
                var calendarPage = null;
                var iCalendarPageIndex = -1;
                var iTotalPagesInHist = $.mobile.urlHistory.length;
                var pagesToRemove = [];
                var eCallbackType = Enums.MobileCallbackTypes.eMobileCalendarCallback;

                if (self.isMobileDayView()) {
                    eCallbackType = Enums.MobileCallbackTypes.eMobileCalendarCallbackDayView;
                }

                $.each($.mobile.urlHistory.stack, function (i, page) {
                    if (page.url == sTripCalUrl) {
                        calendarPage = page;
                        iCalendarPageIndex = i;
                        return false;
                    }
                });

                //pagesToRemove.push("/Trip/MobileTripCalendarViewEvent?iTripId=" + data.Trip.iTripID + "&iPlanId=" + data.Plan.ID);
                //pagesToRemove.push("/Trip/MobileTripCalendarEditEvent?iTripId=" + data.Trip.iTripID + "&iPlanId=" + data.Plan.ID);

                if (calendarPage != null) {
                    self._myChangePage(
                        calendarPage,
                        iCalendarPageIndex,
                        pagesToRemove,
                        {
                            "eCallbackType": eCallbackType,
                            "jsonTrip": data.Trip,
                            "jsonPlan": data.Plan
                        }
                    );
                }

            } else {
                alert('Could not delete. Please retry later!');
            }
        },

        _myChangePage: function (page, iCalendarPageIndex, pagesToRemove, args) {

            if (iCalendarPageIndex > -1) {
                $.mobile.urlHistory.activeIndex = iCalendarPageIndex;
            }

            //$.mobile.changePage(page, 'slide', true, false);
            //$.mobile.activePage.data("callbackArgs", args);

            //Begin-Ticket #34 UBS 10/21/2011: Upgraded from 1.0a3 (alpha) to 1.0 RC2
            $.mobile.changePage(page.url, { transition: "slide", reverse: true, changeHash: false, showLoadMsg: false });
            $.mobile.activePage.jqmData("callbackArgs", args);
            //End-Ticket #34 UBS 10/21/2011:

            if (pagesToRemove.length > 0) {
                $.each(pagesToRemove, function (j, pageToRemove) {
                    $.each($.mobile.urlHistory.stack, function (i, page) {
                        if (page.url == pageToRemove) {
                            $.mobile.urlHistory.stack.splice(i, 1);
                            return false;
                        }
                    });
                });
            }

            //$.mobile.updateHash(page, true);
            //$(page).trigger("callback", args);
        },

        _resetForm: function (flgNewEvent) {
            var options = this.options;
            var $dialogContent = $("#" + options.eventEditContainerID);
            $dialogContent.find('div .wc-container').val("");
            $dialogContent.find('div .wc-container').text("");

            $.each($dialogContent.find("li"), function (i, oLi) {
                $(this).find(".required_data_missing").hide();
                $(this).find(".required_data").show();
            });

            //For new events clear the contents as well.
            if (flgNewEvent || options.flgIsMobileView) {
                $("#" + options.eventEditContainerID).find("input[name='title']").val("");
                $("#" + options.eventEditContainerID).find("textarea[name='body']").val("");
                $("#" + options.eventEditContainerID).find("select[name='type']").text("");
                $("#" + options.eventEditContainerID).find("select[name='viewType']").text(""); //Mushtaq [Ticket# 14] [18 May 2010]
                $("#" + options.eventEditContainerID).find("input[name='attendees']").val("");
                $("#" + options.eventEditContainerID).find("input[name='location']").val("");
                $("#" + options.eventEditContainerID).find("select[name='date']").text("");
                $("#" + options.eventEditContainerID).find("input[name='phoneNumber']").val("");
            }

            if (options.flgIsMobileView) {
                $("#" + options.eventEditContainerID).find("select[name='end']").find("option[value != '']").detach();
                $("#" + options.eventEditContainerID).find("select[name='start']").find("option[value != '']").detach();
            }
        },

        _getEventData: function () {
            var year = new Date().getFullYear();
            var month = new Date().getMonth();
            var day = new Date().getDate();

            return {
                events: [
                   { "id": 1, "start": new Date(year, month, day, 12), "end": new Date(year, month, day, 13, 30), "title": "Lunch with Mike" },
                   { "id": 2, "start": new Date(year, month, day, 14), "end": new Date(year, month, day, 14, 45), "title": "Dev Meeting" },
                   { "id": 3, "start": new Date(year, month, day + 1, 17), "end": new Date(year, month, day + 1, 17, 45), "title": "Hair cut" },
                   { "id": 4, "start": new Date(year, month, day - 1, 8), "end": new Date(year, month, day - 1, 9, 30), "title": "Team breakfast" },
                   { "id": 5, "start": new Date(year, month, day + 1, 14), "end": new Date(year, month, day + 1, 15), "title": "Product showcase" },
                   { "id": 6, "start": new Date(year, month, day, 10), "end": new Date(year, month, day, 11), "title": "I'm read-only", readOnly: true }

                ]
            };
        },

        getLoadingStatusDiv: function () {
            var htmlDiv = '';
            htmlDiv += "<div id=\"loading-calendar\">";
            htmlDiv += "<img src=\"../content/images/spinner.gif\" /><span id=\"loading-calendar-msg\">&nbsp;Updating....</span>";
            htmlDiv += "</div>";
            return htmlDiv;
        },

        _dateDeserialize: function (dateStr, formatStr) {
            var dateReturn = null;

            if (formatStr != undefined && formatStr != null && formatStr != '') {
                //return eval('new' + dateStr.replace(/\//g, ' ')).format(formatStr);
                dateReturn = eval('new' + dateStr.replace(/\//g, ' ')).format(formatStr);
            }
            else {
                //return eval('new' + dateStr.replace(/\//g, ' '));
                dateReturn = eval('new' + dateStr.replace(/\//g, ' '));
            }

            //UBS 4/21/2011: Need to do this massaging because JsonConvert.SerializeObject of .NET MVC framework is converting it 59minutes of 29 minutes.
            if (dateReturn.getMinutes() == 59) {
                dateReturn.setMinutes(0);
                dateReturn.setHours(dateReturn.getHours() + 1);
            } else if (dateReturn.getMinutes() == 29) {
                dateReturn.setMinutes(30);
            }
            //END-UBS 4/21/2011:

            return dateReturn;
        },

        loadMobileEventViewer: function (jsonIOPlanText, eventViewContainerID, sCustomID) {

            var self = this;
            var options = this.options;
            var jsonPlan = null;

            if (typeof jsonIOPlanText == "string") {
                jsonPlan = JSON.parse(jsonIOPlanText.replace(/&amp;#39;/gi, '\'').replace(/&#39;/gi, '').replace(/&amp;quot;/gi, '"').replace(/&quot;/gi, '"').replace(/\n/gi, "\\n").replace(/\r/gi, "\\r")); ;
            }
            else if (typeof jsonIOPlanText == "object") {
                jsonPlan = jsonIOPlanText;
            }

            $("#" + eventViewContainerID + ' li').each(function () {
                if ($(this).attr('id').match(/li_plan_view/)) {
                    $(this).detach();
                }
            });

            var ulHtml = "<ul data-role=\"listview\" data-theme=\"b\" data-inset=\"true\" role=\"listbox\">";
            var liHtml = "";
            var liHtmls = "";

            //Title, Plan Type,  From & To Time.
            var fromTime = self.element.weekCalendar("formatDate", self._dateDeserialize(jsonPlan.StartDateTime), "D g:ia M d, Y ");
            var toTime = self.element.weekCalendar("formatDate", self._dateDeserialize(jsonPlan.EndDateTime), "D g:ia M d, Y ");
            //NOTE : for formats please refer to jquery.weekcalendar.js: line 1532.

            liHtml = "";
            liHtml += "<li data-role=\"option\" id=\"li_plan_view_title\">";
            liHtml += "<h3>" + jsonPlan.Title + "</h3>";
            liHtml += "<p>Type:" + jsonPlan.PlanType + "</p>";
            liHtml += "<p>from " + fromTime + "</p>";
            liHtml += "<p>to " + toTime + "</p>";
            liHtml += "</li>";
            liHtmls += liHtml;

            //Attendees
            liHtml = "";
            liHtml += "<li data-role=\"option\" id=\"li_plan_view_attendees\">";
            liHtml += "<h3>Invitees</h3>";
            liHtml += "<p>" + jsonPlan.Attendees + "</p>";
            liHtml += "</li>";
            liHtmls += liHtml;

            //Location
            liHtml = "";
            liHtml += "<li data-role=\"option\" id=\"li_plan_view_location\">";
            liHtml += "<h3>Location</h3>";
            liHtml += "<p>" + jsonPlan.Location + "</p>";
            liHtml += "</li>";
            liHtmls += liHtml;

            //Description  
            liHtml = "";
            liHtml += "<li data-role=\"option\" id=\"li_plan_view_desc\">";
            liHtml += "<h3>Notes</h3>";
            liHtml += "<p>" + jsonPlan.Description + "</p>";
            liHtml += "</li>";
            liHtmls += liHtml;

            ulHtml += liHtmls + "</ul>";

            $("#ul_plan_" + sCustomID).append(liHtmls);
            $("#ul_plan_" + sCustomID).addClass("mobileLI");
            $("#ul_plan_" + sCustomID).listview("refresh");
        },

        _getTripPlans: function () {
            var options = this.options;
            var self = this;
            var calEvents = [];

            //$.post("/Search/GetTripPlans", { "iTripID": options.jsonTrip.iTripID }, self._getTripPlansOnSuccess, "json");

            if (options.jsonTrip != null && options.jsonTrip.Plans != null && options.jsonTrip.Plans.length > 0) {
                $.each(options.jsonTrip.Plans, function (iPlanCounter, oPlan) {
                    calEvents.push(new self._createCalEvent(oPlan));
                });
            }
            return calEvents;
        },

        _getCurrentDateFirstTripPlan: function () {
            var options = this.options;
            var self = this;
            var calEvents = [];
            var calEventsCurrDate = [];
            var calEventReturn = null;

            calEvents = self._getTripPlans();

            $.each(calEvents, function (iPlanCounter, calEvent) {
                if (calEvent.start.getDate() == options.currentDate.getDate()) {
                    calEventsCurrDate.push(calEvent);
                }
            });

            if (calEventsCurrDate.length > 0)
                calEventReturn = calEventsCurrDate[0];

            return calEventReturn;
        },

        _getTripPlansOnSuccess: function (oPlans) {
            var calEvents = [];
            $.each(oPlans, function (iPlanCounter, oPlan) {
                calEvents.push(new _createCalEvent(oPlan));
            });
            return calEvents;
        },

        _createCalEvent: function (oPlan) {
            if (oPlan != undefined && oPlan != null) {
                this.id = oPlan.ID;
                if (typeof oPlan.StartDateTime == "string") {
                    this.start = _dateDeserialize(oPlan.StartDateTime);
                }
                else {
                    this.start = oPlan.StartDateTime;
                }
                if (typeof oPlan.EndDateTime == "string") {
                    this.end = _dateDeserialize(oPlan.EndDateTime);
                }
                else {
                    this.end = oPlan.EndDateTime;
                }
                this.title = oPlan.Title;
                this.description = oPlan.Description;
                this.readOnly = oPlan.IsReadOnly;
                //UBS 1/13/2011: Added these new Plan fields to Cal-Events in the client-side.
                this.attendees = oPlan.Attendees;

                //added by mushtaq. 
                this.sendSMSAlert = oPlan.SendSMSAlert;
                this.phoneNumber = oPlan.PhoneNumber;
                this.updatePhoneProfile = oPlan.UpdatePhoneProfile;

                this.location = oPlan.Location;
                this.tripId = oPlan.TripID;
                this.type = oPlan.Type;
                this.viewType = oPlan.ViewType; ////Mushtaq [Ticket# 14] [20 May 2010]
                //END-UBS 1/13/2011:
            }
            else {
                this.id = "";
                this.start = "";
                this.end = "";
                this.title = "";
                this.description = "";
                this.readOnly = false;
                this.attendees = "";
                this.sendSMSAlert = false;
                this.phoneNumber = "";
                this.updatePhoneProfile = false;
                this.location = "";
                this.tripId = "";
                this.type = "";
                this.viewType = ""; //Mushtaq [Ticket# 14] [18 May 2010]
            }
        },

        updateEventsJSONData: function () {
            var self = this;
            var options = this.options;

            if (options.datePickerElement.data("calEventsNewToInsert").length > 0) {
                options.datePickerElement.data("calEventsNewToInsertJSON", self._getEventsJson(options.datePickerElement.data("calEventsNewToInsert")));
            }
            if (options.datePickerElement.data("calEventsToUpdate").length > 0) {
                options.datePickerElement.data("calEventsToUpdateJSON", self._getEventsJson(options.datePickerElement.data("calEventsToUpdate")));
            }
            if (options.datePickerElement.data("calEventsToDelete").length > 0) {
                options.datePickerElement.data("calEventsToDeleteJSON", self._getEventsJson(options.datePickerElement.data("calEventsToDelete")));
            }
        },

        _getEventsJson: function (calEvents) {
            var oReturn = [];
            var self = this;

            $.each(calEvents, function (iEventCounter, calEvent) {
                oReturn.push(self._createJsonPlan(calEvent, self.options.jsonTrip.iTripID));
            });

            return oReturn;
        },

        _createJsonPlan: function (calEvent, iTripID) {

            var id = -1;
            var iTripIDTemp = -1;

            if (calEvent.id != 10) {
                id = calEvent.id;
            }

            if (iTripID == undefined || iTripID == null) {
                iTripIDTemp = calEvent.TripID;
            } else {
                iTripIDTemp = iTripID;
            }

            return {
                "ID": id,
                "StartDateTime": calEvent.start,
                "EndDateTime": calEvent.end,
                "Title": calEvent.title,
                "Description": calEvent.body,
                "Attendees": calEvent.attendees,
                "SendSMSAlert": calEvent.sendSMSAlert,
                "PhoneNumber": calEvent.phoneNumber,
                "UpdatePhoneProfile": calEvent.updatePhoneProfile,
                "Type": calEvent.type,
                "ViewType": calEvent.viewType, //Mushtaq [Ticket# 14] [20 May 2010]
                "Location": calEvent.location,
                "TripID": iTripIDTemp,
                "IsReadOnly": false
            };
        },

        _createJsonIOPlan: function (oPlanData, iTripID) {
            var iTripIDTemp = -1;

            if (iTripID == undefined || iTripID == null) {
                iTripIDTemp = oPlanData.TripID;
            } else {
                iTripIDTemp = iTripID;
            }

            this.ID = oPlanData.ID;
            this.StartDateTime = _dateDeserialize(oPlanData.StartDateTime);
            this.EndDateTime = _dateDeserialize(oPlanData.EndDateTime);
            this.Title = oPlanData.Title;
            this.Description = oPlanData.Description;
            this.IsReadOnly = oPlanData.IsReadOnly;
            this.Attendees = oPlanData.Attendees;
            //added by mushtaq
            this.SMSAlert = oPlanData.SendSMSAlert;
            this.PhoneNumber = oPlanData.PhoneNumber;
            this.UpdatePhoneProfile = oPlanData.UpdatePhoneProfile;

            this.BelongsToCity = oPlanData.BelongsToCity;
            this.TripID = iTripIDTemp;
        },

        _updatePlan: function (newCalEvent, oldCalEvent, self) {

            if (newCalEvent.title.length > 0 && newCalEvent.start != undefined && newCalEvent.end != undefined) {
                self.element.data("calEventInProg", newCalEvent);
                var jsonPlan = JSON.stringify(self._createJsonPlan(newCalEvent, self.options.jsonTrip.iTripID));

                //UBS 11/25/2010: Commented the code below as I am now trying to do all updates from TripCalendar.ascx: Save()
                //Save it to the DB.
                //$.post("/Search/InsertOrUpdateTripPlan",
                //                { "iTripID": self.options.jsonTrip.iTripID, "sJsonPlan": jsonPlan },
                //                function (data) {
                //                    self._onSuccessUpdateTripPlan(data, self, newCalEvent);
                //                },
                //                "json");

                //UBS 11/25/2010: Just update in the Calendar we will push it to DB all Changes at once from TripCalendar.ascx:Save()
                //self.element.weekCalendar("updateEvent", newCalEvent);
                var iFoundAtIndex = -1;
                $.each(self.options.datePickerElement.data("calEventsToUpdate"), function (iCounter, event) {
                    if (event.id == newCalEvent.id && newCalEvent.id != -1) {
                        iFoundAtIndex = iCounter;
                        return false;
                    }
                });

                //UBS 12/16/2010: Also check if this update is for the new-cal-event that has not yet been saved to the DB.
                var iFoundAtNewListIndex = -1;
                $.each(self.options.datePickerElement.data("calEventsNewToInsert"), function (iCounter, event) {
                    if (event.id == oldCalEvent.id && oldCalEvent.id == -1) {
                        iFoundAtNewListIndex = iCounter;
                        return false;
                    }
                });

                if (iFoundAtIndex > -1) {
                    //Event already exists in the Pending changes queue therefore just update it.
                    self.options.datePickerElement.data("calEventsToUpdate").splice(iFoundAtIndex, 1, newCalEvent);
                }
                else if (iFoundAtNewListIndex > -1) {
                    //UBS 12/16/2010: Event already exists in the New Plans queue therefore just overwrite it with the new changes.
                    self.options.datePickerElement.data("calEventsNewToInsert").splice(iFoundAtIndex, 1, newCalEvent);
                }
                else {
                    //does not exists in the queue therefore add it to the queue.
                    self.options.datePickerElement.data("calEventsToUpdate").push(newCalEvent);
                }
                //self.options.datePickerElement.data("calEventsToUpdate").push(newCalEvent);
                //iTotalChanges = datePickerElement.tripDatePicker("getTotalEventChangesToDB")
                self.options.datePickerElement.tripDatePicker("updateWCTitleMsg");
            }

        },

        /*
        * UBS 11/25/2010: This is callback function for "/Search/InsertOrUpdateTripPlan". 
        * History : 
        * 1) UBS 11/25/2010 8am - Since I am trying to do all updates from TripCalendar.ascx:Save() this function may
        * have to be moved or decommissioned.
        */
        _onSuccessUpdateTripPlan: function (data, self, calEvent) {
            var options = self.options;
            if (data.flgResult == true) {
                self.element.weekCalendar("updateEvent", calEvent);
                //update the Plan in options.jsonTrip.Plans object.
                var iPlanIndexToUpdate = -1;
                $.each(self.options.jsonTrip.Plans, function (iPlanCounter, oPlan) {
                    if (oPlan.ID == calEvent.id) {
                        iPlanIndexToUpdate = iPlanCounter;
                        return false;
                    }
                });
                if (iPlanIndexToUpdate != -1 && iPlanIndexToUpdate < self.options.jsonTrip.Plans.length) {
                    self.options.jsonTrip.Plans[iPlanIndexToUpdate].Title = data.Plan.Title;
                    self.options.jsonTrip.Plans[iPlanIndexToUpdate].Description = data.Plan.Description;
                    self.options.jsonTrip.Plans[iPlanIndexToUpdate].StartDateTime = data.Plan.StartDateTime;
                    self.options.jsonTrip.Plans[iPlanIndexToUpdate].EndDateTime = data.Plan.EndDateTime;
                    //ID, TripID, BelongsToCity, Attendees, Type, IsReadOnly will not change for now.
                    //added by mushtaq 
                    self.options.jsonTrip.Plans[iPlanIndexToUpdate].SendSMSAlert = data.Plan.sendSMSAlert;
                    self.options.jsonTrip.Plans[iPlanIndexToUpdate].PhoneNumber = data.Plan.PhoneNumber;
                    self.options.jsonTrip.Plans[iPlanIndexToUpdate].UpdatePhoneProfile = data.Plan.UpdatePhoneProfile;
                    self.options.jsonTrip.Plans[iPlanIndexToUpdate].ViewType = data.Plan.ViewType; //Mushtaq [Ticket# 14] [20 May 2010]
                }
                self._init();
            }
            else {
                //Could not save to the DB therefore do not close instead show the error msg.
                //self._displayServerError($("#" + options.eventEditContainerID), calEvent);
            }
        },

        _renderMobileNewTripEvent: function (/*calEvent, $event*/) {
            var options = this.options;
            var self = this;
            self._resetForm(true);

            var startField = $("#" + options.eventEditContainerID).find("select[name='start']")/*.val(calEvent.start)*/;
            var endField = $("#" + options.eventEditContainerID).find("select[name='end']")/*.val(calEvent.end)*/;
            var titleField = $("#" + options.eventEditContainerID).find("input[name='title']");
            var bodyField = $("#" + options.eventEditContainerID).find("textarea[name='body']");
            //UBS 12/17/2010: Enhancing the calendar events, adding 3 new feilds.
            var typeField = $("#" + options.eventEditContainerID).find("select[name='type']");
            var viewTypeField = $("#" + options.eventEditContainerID).find("select[name='viewType']"); //Mushtaq [Ticket# 14] [20 May 2010]
            var attendeesField = $("#" + options.eventEditContainerID).find("input[name='attendees']");
            var smsAlertField = $("#" + options.eventEditContainerID).find("input[name='SMSAlert']");
            var phoneNumberField = $("#" + options.eventEditContainerID).find("input[name='phoneNumber']");
            var updatePhoneProfileField = $("#" + options.eventEditContainerID).find("input[name='updatePhoneProfile']");
            var locationField = $("#" + options.eventEditContainerID).find("input[name='location']");
            var attendeesLiField = $("#" + options.eventEditContainerID).find("li[rel='attendees']");
            var smsAlertLiField = $("#" + options.eventEditContainerID).find("li[rel='SMSAlert']");
            var phoneNumberLiField = $("#" + options.eventEditContainerID).find("li[rel='phoneNumber']");
            var locationLiField = $("#" + options.eventEditContainerID).find("li[rel='location']");
            $(typeField).bind("change", function () {
                self._toggleLocAttendeesFields();
            });
            $(smsAlertField).bind("change", function () {
                if ($smsAlertField.length > 0 && $smsAlertField[0].checked == true) {
                    $phoneNumberLiField.show();
                }
                else {
                    phoneNumberField[0].value = "";
                    updatePhoneProfileField[0].checked = false;
                    $phoneNumberLiField.hide();
                }
            });
            //END-UBS 12/17/2010:

            //initially set the checkbox as unchecked
            smsAlertField[0].checked = false;
            phoneNumberField[0].value = "";
            updatePhoneProfileField[0].checked = false;

            //if the checkbox is checked, then show the phone number textbox, else hide
            $(smsAlertField).click(function (evt) {
                $phoneNumberLiField = $("#" + options.eventEditContainerID).find("li[rel=phoneNumber]");
                if (this.checked == true) {
                    $phoneNumberLiField.show();
                }
                else {
                    phoneNumberField[0].value = "";
                    updatePhoneProfileField[0].checked = false;
                    $phoneNumberLiField.hide();
                }
            });

            var dateField = $("#" + options.eventEditContainerID).find("select[name='date']").val(self.element.weekCalendar("formatDate", calEvent.start));

            //hide the error warnings upon load.
            $("#" + options.eventEditContainerID).find(".required_data_missing").hide();

            $("#" + options.eventEditContainerID).show();

            $("#" + options.eventEditContainerID).find(".date_holder").text(self.element.weekCalendar("formatDate", calEvent.start));
            var timeSlots = self.element.weekCalendar("getTimeslotTimes", calEvent.start);
            self._setupStartAndEndTimeFields(startField, endField, calEvent, timeSlots);
            self._setupTypeDropdowns(typeField, viewTypeField, locationField, attendeesField, null);
        },

        _renderNewTripEvent: function (calEvent, $event) {
            var options = this.options;
            var self = this;
            self._resetForm(true);

            var startField = $("#" + options.eventEditContainerID).find("select[name='start']").val(calEvent.start);
            var endField = $("#" + options.eventEditContainerID).find("select[name='end']").val(calEvent.end);
            var titleField = $("#" + options.eventEditContainerID).find("input[name='title']");
            var bodyField = $("#" + options.eventEditContainerID).find("textarea[name='body']");
            //UBS 12/17/2010: Enhancing the calendar events, adding 3 new feilds.
            var typeField = $("#" + options.eventEditContainerID).find("select[name='type']");
            var viewTypeField = $("#" + options.eventEditContainerID).find("select[name='viewType']"); //Mushtaq [Ticket# 14] [18 May 2010]
            var attendeesField = $("#" + options.eventEditContainerID).find("input[name='attendees']");
            var smsAlertField = $("#" + options.eventEditContainerID).find("input[name='SMSAlert']");
            var phoneNumberField = $("#" + options.eventEditContainerID).find("input[name='phoneNumber']");
            var updatePhoneProfileField = $("#" + options.eventEditContainerID).find("input[name='updatePhoneProfile']");
            var locationField = $("#" + options.eventEditContainerID).find("input[name='location']");
            var attendeesLiField = $("#" + options.eventEditContainerID).find("li[rel='attendees']");
            var smsAlertLiField = $("#" + options.eventEditContainerID).find("li[rel='SMSAlert']");
            var phoneNumberLiField = $("#" + options.eventEditContainerID).find("li[rel='phoneNumber']");
            var locationLiField = $("#" + options.eventEditContainerID).find("li[rel='location']");
            $(typeField).bind("change", function () {
                self._toggleLocAttendeesFields();
            });
            //END-UBS 12/17/2010:

            //initially set the checkbox as unchecked
            smsAlertField[0].checked = false;
            phoneNumberField[0].value = "";
            updatePhoneProfileField[0].checked = false;

            //if the checkbox is checked, then show the phone number textbox, else hide
            $(smsAlertField).click(function (evt) {
                $phoneNumberLiField = $("#" + options.eventEditContainerID).find("li[rel=phoneNumber]");
                if (this.checked == true) {
                    $phoneNumberLiField.show();
                }
                else {
                    phoneNumberField[0].value = "";
                    updatePhoneProfileField[0].checked = false;
                    $phoneNumberLiField.hide();
                }
            });
            //hide the error warnings upon load.
            $("#" + options.eventEditContainerID).find(".required_data_missing").hide();

            $("#" + options.eventEditContainerID).show();

            $("#" + options.eventEditContainerID).dialog({
                modal: true,
                width: 640,
                title: "New Trip Event",
                close: function () {
                    $("#" + options.eventEditContainerID).dialog("destroy");
                    $("#" + options.eventEditContainerID).hide();
                    self.element.weekCalendar("removeUnsavedEvents");
                },
                buttons: {
                    save: function () {
                        calEvent.id = -1; //TODO : UBS 11/15/2010: ID should not be hard-coded.
                        calEvent.start = new Date(startField.val());
                        calEvent.end = new Date(endField.val());
                        calEvent.title = titleField.val();
                        calEvent.body = bodyField.val();
                        calEvent.readOnly = false;
                        calEvent.tripId = options.jsonTrip.iTripID;
                        //calEvent.type = ??, calEvent.Attendees = ??, calEvent.BelongsToCity = ??;

                        //UBS 12/17/2010: Enhancing the calendar events, adding 3 new feilds.
                        calEvent.type = typeField.val();
                        calEvent.viewType = viewTypeField.val(); //Mushtaq [Ticket# 14] [18 May 2010]
                        if (attendeesField.val() != "david@trx.com,jones@yahoo.com") {
                            //Make sure you dont add watermark text
                            calEvent.attendees = attendeesField.val();
                        }
                        else {
                            calEvent.attendees = "";
                        }

                        //added by mushtaq --start
                        if ($smsAlertField.length > 0) {
                            calEvent.sendSMSAlert = $smsAlertField[0].checked;
                        }
                        if ($smsAlertField.length > 0 && $smsAlertField[0].checked == true) {
                            calEvent.phoneNumber = phoneNumberField[0].value;
                        }
                        else {
                            calEvent.phoneNumber = "";
                        }
                        if (updatePhoneProfileField.length > 0 && updatePhoneProfileField[0].checked == true) {
                            calEvent.updatePhoneProfile = updatePhoneProfileField[0].checked;
                        }

                        //end -added by mushtaq

                        if (locationField.val() != "123 Greenville St, Dallas, TX") {
                            //Make sure you dont add watermark text
                            calEvent.location = locationField.val();
                        }
                        else {
                            calEvent.location = "";
                        }
                        //END-UBS 12/17/2010:

                        if (calEvent.title.length > 0 && calEvent.start != undefined && calEvent.end != undefined && self._isValidMeetingOrRestaurantEvent(calEvent)
                        && self._isValidPhoneNumber(calEvent)) {
                            self.element.data("calEventInProg", calEvent);
                            var jsonPlan = JSON.stringify(self._createJsonPlan(calEvent, options.jsonTrip.iTripID));

                            //UBS 11/25/2010: Just update in the Calendar we will push it to DB all Changes at once from TripCalendar.ascx:Save()
                            var iFoundAtIndex = -1;
                            $.each(self.options.datePickerElement.data("calEventsNewToInsert"), function (iCounter, event) {
                                if (event.id == calEvent.id && calEvent.id != -1) {
                                    iFoundAtIndex = iCounter;
                                    return false;
                                }
                            });
                            if (iFoundAtIndex > -1) {
                                //Event already exists in the Pending changes queue therefore just update it.
                                self.options.datePickerElement.data("calEventsNewToInsert").splice(iFoundAtIndex, 1, calEvent);
                            }
                            else {
                                //does not exists in the queue therefore add it to the queue.
                                self.options.datePickerElement.data("calEventsNewToInsert").push(calEvent);
                            }
                            //self.options.datePickerElement.data("calEventsNewToInsert").push(calEvent);
                            self.options.datePickerElement.tripDatePicker("updateWCTitleMsg");
                            self.element.weekCalendar("removeUnsavedEvents");
                            self.element.weekCalendar("updateEvent", calEvent);
                            $("#" + options.eventEditContainerID).dialog("close");

                        }
                        else {
                            //Show the error warnings and hide the required indicators.
                            self._displayValidationErrors($("#" + options.eventEditContainerID), calEvent);
                        }
                    },
                    cancel: function () {
                        $("#" + options.eventEditContainerID).dialog("close");
                    }
                }
            }).show();

            $("#" + options.eventEditContainerID).find(".date_holder").text(self.element.weekCalendar("formatDate", calEvent.start));
            self._setupStartAndEndTimeFields(startField, endField, calEvent, self.element.weekCalendar("getTimeslotTimes", calEvent.start));
            self._setupTypeDropdowns(typeField, viewTypeField, locationField, attendeesField, null);
            $(window).resize().resize(); //fixes a bug in modal overlay size ??
        },

        _displayValidationErrors: function ($eventEditContainer, calEvent) {
            var options = this.options;
            var self = this;

            $.each($eventEditContainer.find("li"), function (i, oLi) {
                $(this).find(".required_data_missing").hide();
                $(this).find(".required_data").show();
            });

            $.each($eventEditContainer.find("li"), function (i, oLi) {
                if (calEvent.start.toString() == "Invalid Date" && $(this).attr("rel") == "start") {
                    $(this).find(".required_data_missing").show();
                    $(this).find(".required_data").hide();
                }
                else if (calEvent.end.toString() == "Invalid Date" && $(this).attr("rel") == "end") {
                    $(this).find(".required_data_missing").show();
                    $(this).find(".required_data").hide();
                }
                else if (calEvent.title.length == 0 && $(this).attr("rel") == "title") {
                    $(this).find(".required_data_missing").show();
                    $(this).find(".required_data").hide();
                }
                else if (!self._isValidMeetingOrRestaurantEvent(calEvent) && $(this).attr("rel") == "location") {
                    $(this).find(".required_data_missing").show();
                    $(this).find(".required_data").hide();
                }
                else if (!self._isValidMeetingOrRestaurantEvent(calEvent) && $(this).attr("rel") == "attendees") {
                    $(this).find(".required_data_missing").show();
                    $(this).find(".required_data").hide();
                }
                else if (calEvent.sendSMSAlert == true && calEvent.phoneNumber.length == 0 && $(this).attr("rel") == "phoneNumber") {
                    $(this).find(".required_data_missing").show();
                    $(this).find(".required_data").hide();
                }
            });
        },

        _displayServerError: function ($eventEditContainer) {
            $.each($eventEditContainer.find("li"), function (i, oLi) {
                if ($(this).attr("rel") == "errMsg") {
                    $(this).show();
                }
            });
        },

        /*
        * UBS 11/25/2010: This is callback function for "/Search/InsertOrUpdateTripPlan". 
        * History : 
        * 1) UBS 11/25/2010 8am - Since I am trying to do all updates from TripCalendar.ascx:Save() this function may
        * have to be moved or decommissioned.
        */
        _onSuccessInsertNewTripPlan: function (data, self) {
            //var self = this;
            var options = self.options;
            //if (data == "SUCCESS") {
            if (data.flgResult == true) {
                self.element.weekCalendar("removeUnsavedEvents");
                self.element.data("calEventInProg").id = data.Plan.ID;
                self.element.weekCalendar("updateEvent", self.element.data("calEventInProg"));
                $("#" + options.eventEditContainerID).dialog("close");
                //Insert the Plan in options.jsonTrip.Plans object.
                self.options.jsonTrip.Plans.push(new self._createJsonIOPlan(data.Plan));
                self._init();
            }
            else {
                //Could not save to the DB therefore do not close instead show the error msg.
                self.element.weekCalendar("removeUnsavedEvents");
                self.element.weekCalendar("updateEvent", self.element.data("calEventInProg"));
                //Show the error warnings and hide the required indicators.
                self._displayServerError($("#" + options.eventEditContainerID), calEvent);
            }
        },


        /*
        * UBS 11/25/2010: This is callback function for "/Search/InsertOrUpdateTripPlan" from _updatePlan(). 
        * History : 
        * 1) UBS 11/25/2010 8am - Since I am trying to do all updates from TripCalendar.ascx:Save() this function may
        * have to be moved or decommissioned.
        */
        _onSuccessUpdateTripPlan: function (data, self, calEvent) {
            //var self = this;
            var options = self.options;
            if (data.flgResult == true) {
                self.element.weekCalendar("updateEvent", calEvent);
                $("#" + options.eventEditContainerID).dialog("close");
                //update the Plan in options.jsonTrip.Plans object.
                var iPlanIndexToUpdate = -1;
                $.each(self.options.jsonTrip.Plans, function (iPlanCounter, oPlan) {
                    if (oPlan.ID == calEvent.id) {
                        iPlanIndexToUpdate = iPlanCounter;
                        return false;
                    }
                });
                if (iPlanIndexToUpdate != -1 && iPlanIndexToUpdate < self.options.jsonTrip.Plans.length) {
                    self.options.jsonTrip.Plans[iPlanIndexToRemove].Title = data.Plan.Title;
                    self.options.jsonTrip.Plans[iPlanIndexToRemove].Description = data.Plan.Description;
                    self.options.jsonTrip.Plans[iPlanIndexToRemove].StartDateTime = data.Plan.StartDateTime;
                    self.options.jsonTrip.Plans[iPlanIndexToRemove].EndDateTime = data.Plan.EndDateTime;
                    self._init();
                    //ID, TripID, BelongsToCity, Attendees, Type, IsReadOnly will not change for now.
                    //added by mushtaq
                    self.options.jsonTrip.Plans[iPlanIndexToRemove].SendSMSAlert = data.Plan.sendSMSAlert;
                    self.options.jsonTrip.Plans[iPlanIndexToRemove].PhoneNumber = data.Plan.PhoneNumber;
                    self.options.jsonTrip.Plans[iPlanIndexToRemove].UpdatePhoneProfile = data.Plan.UpdatePhoneProfile;
                    self.options.jsonTrip.Plans[iPlanIndexToRemove].ViewType = data.Plan.ViewType;
                }
            }
            else {
                //Could not save to the DB therefore do not close instead show the error msg.
                self._displayServerError($("#" + options.eventEditContainerID), calEvent);
            }
        },


        /*
        * UBS 11/25/2010: This is callback function for "/Search/DeleteTripPlan". 
        * History : 
        * 1) UBS 11/25/2010 8am - Since I am trying to do all updates from TripCalendar.ascx:Save() this function may
        * have to be moved or decommissioned.
        */
        _onSuccessDeleteTripPlan: function (data, self, calEvent) {
            if (data.flgResult == true) {
                self.element.weekCalendar("removeEvent", calEvent.id);
                $("#" + self.options.eventEditContainerID).dialog("close");
                //remove the plan in options.jsonTrip.Plans object.
                var iPlanIndexToRemove = -1;
                $.each(self.options.jsonTrip.Plans, function (iPlanCounter, oPlan) {
                    if (oPlan.ID == calEvent.id) {
                        iPlanIndexToRemove = iPlanCounter;
                        return false;
                    }
                });
                if (iPlanIndexToRemove != -1) {
                    self.options.jsonTrip.Plans.splice(iPlanIndexToRemove, 1);
                    self._init();
                }
            }
            else {
                //Could not delete it from DB therefore do not close instead show the error msg.
                self._displayServerError($("#" + self.options.eventEditContainerID));
            }
        },

        /*
        * checks if the calevent is valid meeting or restaurant type
        */
        _isValidMeetingOrRestaurantEvent: function (calEvent) {
            var flgReturn = true;
            if (calEvent != undefined && calEvent != null) {
                if (calEvent.type == Enums.PlanType.eMeeting || calEvent.type == Enums.PlanType.eRestaurant) {
                    if (calEvent.location.length == 0 || calEvent.location == "123 Greenville St, Dallas, TX") {
                        //Watermark text should be accounted as well.
                        flgReturn = false;
                    }
                }
            }
            return flgReturn;
        },

        /*
        * checks if the phone number is provided when sendSMSAlert is checked
        */
        _isValidPhoneNumber: function (calEvent) {
            var flgReturn = true;
            if (calEvent != undefined && calEvent != null) {
                if (calEvent.sendSMSAlert == true && calEvent.phoneNumber == "") {
                    flgReturn = false;
                }
            }
            return flgReturn;
        },

        _getMobileEventEditorID: function (calEvent) {
            var self = this;
            var sReturn = self.options.eventEditContainerID + "_" + calEvent.id;
            return sReturn;
        },

        _renderMobileTripEventClick: function (calEvent, calEventJsonText, $event, flgMobileNewEvent) {
            var options = this.options;
            var self = this;

            if (calEvent.readOnly) {
                return;
            }

            self._resetForm(false);

            if (flgMobileNewEvent) {
                //If adding new events make sure we dont set any value to the dropdown.
                var startField = $("#" + options.eventEditContainerID).find("select[name='start']");
                var endField = $("#" + options.eventEditContainerID).find("select[name='end']");
            } else {
                //If modifying events make sure we set the value to the dropdown.
                var startField = $("#" + options.eventEditContainerID).find("select[name='start']").val(calEvent.start);
                var endField = $("#" + options.eventEditContainerID).find("select[name='end']").val(calEvent.end);
            }
            var titleField = $("#" + options.eventEditContainerID).find("input[name='title']").val(calEvent.title);
            var bodyField = $("#" + options.eventEditContainerID).find("textarea[name='body']").val(calEvent.description);

            //UBS 12/17/2010: Enhancing the calendar events, adding 3 new feilds.
            var typeField = $("#" + options.eventEditContainerID).find("select[name='type']").val(calEvent.type);
            var viewTypeField = $("#" + options.eventEditContainerID).find("select[name='viewType']").val(calEvent.viewType); //Mushtaq [Ticket# 14] [18 May 2010]
            var attendeesField = $("#" + options.eventEditContainerID).find("input[name='attendees']").val(calEvent.attendees);
            var smsAlertField = $("#" + options.eventEditContainerID).find("input[name='SMSAlert']").val(calEvent.sendSMSAlert);
            var phoneNumberField = $("#" + options.eventEditContainerID).find("input[name='phoneNumber']").val(calEvent.phoneNumber);
            var updatePhoneProfileField = $("#" + options.eventEditContainerID).find("input[name='updatePhoneProfile']").val(calEvent.updatePhoneProfile);
            var locationField = $("#" + options.eventEditContainerID).find("input[name='location']").val(calEvent.location);
            var attendeesLiField = $("#" + options.eventEditContainerID).find("li[rel='attendees']");
            var locationLiField = $("#" + options.eventEditContainerID).find("li[rel='location']");
            var smsAlertLiField = $("#" + options.eventEditContainerID).find("li[rel='SMSAlert']");
            var phoneNumberLiField = $("#" + options.eventEditContainerID).find("li[rel='phoneNumber']");
            $(typeField).bind("change", function () {
                self._toggleLocAttendeesFields();
            });
            $(smsAlertField).bind("change", function () {
                if ($smsAlertField.length > 0 && $smsAlertField[0].checked == true) {
                    $phoneNumberLiField.show();
                }
                else {
                    phoneNumberField[0].value = "";
                    updatePhoneProfileField[0].checked = false;
                    $phoneNumberLiField.hide();
                }
            });
            //END-UBS 12/17/2010:

            var dateField = $("#" + options.eventEditContainerID).find("select[name='date']").val(self.element.weekCalendar("formatDate", calEvent.start));
            $(dateField).bind("change", function () {
                self._toggleMobileEventDateField(calEvent, calEventJsonText, flgMobileNewEvent, self);
            });

            //bodyField.val(calEvent.body);

            $("#" + options.eventEditContainerID).show();

            //var startField = $("#" + options.eventEditContainerID).find("select[name='start']").val(calEvent.start);
            //var endField = $("#" + options.eventEditContainerID).find("select[name='end']").val(calEvent.end);

            $("#" + options.eventEditContainerID).find(".date_holder").text(self.element.weekCalendar("formatDate", calEvent.start));

            var timeSlots = self.element.weekCalendar("getTimeslotTimes", calEvent.start);

            self._setupStartAndEndTimeFieldsForUpdate(startField, endField, calEvent, timeSlots);

            //For new mobile-events make sure you dont select any times.
            if (flgMobileNewEvent) {
                startField.find('option[selected="selected"]').removeAttr("selected");
                endField.find('option[selected="selected"]').removeAttr("selected");
            }

            self._setupTypeDropdowns(typeField, viewTypeField, locationField, attendeesField, calEvent);
            self._setupTripDayDropdowns(dateField, calEvent);
        },

        _renderTripEventClick: function (calEvent, $event) {
            var options = this.options;
            var self = this;

            if (calEvent.readOnly) {
                return;
            }

            self._resetForm(false);

            var startField = $("#" + options.eventEditContainerID).find("select[name='start']").val(calEvent.start);
            var endField = $("#" + options.eventEditContainerID).find("select[name='end']").val(calEvent.end);
            var titleField = $("#" + options.eventEditContainerID).find("input[name='title']").val(calEvent.title);
            var bodyField = $("#" + options.eventEditContainerID).find("textarea[name='body']").val(calEvent.description);

            //UBS 12/17/2010: Enhancing the calendar events, adding 3 new feilds.
            var typeField = $("#" + options.eventEditContainerID).find("select[name='type']").val(calEvent.type);
            var viewTypeField = $("#" + options.eventEditContainerID).find("select[name='viewType']").val(calEvent.viewType);
            var attendeesField = $("#" + options.eventEditContainerID).find("input[name='attendees']").val(calEvent.attendees);
            //var smsAlertField = $("#" + options.eventEditContainerID).find("input[name='SMSAlert']").val(calEvent.sendSMSAlert);
            var smsAlertField = $("#" + options.eventEditContainerID).find("input[name='SMSAlert']").attr('checked', calEvent.sendSMSAlert);
            var phoneNumberField = $("#" + options.eventEditContainerID).find("input[name='phoneNumber']").val(calEvent.phoneNumber);
            //var updatePhoneProfileField = $("#" + options.eventEditContainerID).find("input[name='updatePhoneProfile']").val(calEvent.updatePhoneProfile);
            var updatePhoneProfileField = $("#" + options.eventEditContainerID).find("input[name='updatePhoneProfile']").attr('checked', calEvent.updatePhoneProfile);
            var locationField = $("#" + options.eventEditContainerID).find("input[name='location']").val(calEvent.location);
            var attendeesLiField = $("#" + options.eventEditContainerID).find("li[rel='attendees']");
            var locationLiField = $("#" + options.eventEditContainerID).find("li[rel='location']");
            var smsAlertLiField = $("#" + options.eventEditContainerID).find("li[rel='SMSAlert']");
            var phoneNumberLiField = $("#" + options.eventEditContainerID).find("li[rel='phoneNumber']");
            $(typeField).bind("change", function () {
                self._toggleLocAttendeesFields();
            });
            //END-UBS 12/17/2010:

            //bodyField.val(calEvent.body);

            $(smsAlertField).click(function (evt) {
                $phoneNumberLiField = $("#" + options.eventEditContainerID).find("li[rel=phoneNumber]");
                if (this.checked == true) {
                    $phoneNumberLiField.show();
                }
                else {
                    phoneNumberField[0].value = "";
                    updatePhoneProfileField[0].checked = false;
                    $phoneNumberLiField.hide();
                }
            });

            $("#" + options.eventEditContainerID).show();

            $("#" + options.eventEditContainerID).dialog({
                modal: true,
                width: 640,
                title: "Edit - " + calEvent.title,
                close: function () {
                    $("#" + options.eventEditContainerID).dialog("destroy");
                    $("#" + options.eventEditContainerID).hide();
                    self.element.weekCalendar("removeUnsavedEvents");
                },
                buttons: {
                    Update: function () {
                        calEvent.start = new Date(startField.val());
                        calEvent.end = new Date(endField.val());
                        calEvent.title = titleField.val();
                        calEvent.body = bodyField.val();

                        //UBS 12/17/2010: Enhancing the calendar events, adding 3 new feilds.
                        calEvent.type = typeField.val();
                        calEvent.viewType = viewTypeField.val(); //Mushtaq [Ticket# 14] [18 May 2010]
                        if (attendeesField.val() != "david@trx.com,jones@yahoo.com") {
                            //Make sure you dont add watermark text
                            calEvent.attendees = attendeesField.val();
                        }
                        else {
                            calEvent.attendees = "";
                        }

                        //added by mushtaq --start
                        if ($smsAlertField.length > 0) {
                            calEvent.sendSMSAlert = $smsAlertField[0].checked;
                        }
                        else {
                            calEvent.sendSMSAlert = false;
                        }
                        if ($smsAlertField.length > 0 && $smsAlertField[0].checked == true) {
                            calEvent.phoneNumber = phoneNumberField[0].value;
                        }
                        else {
                            calEvent.phoneNumber = "";
                        }
                        if (updatePhoneProfileField.length > 0 && updatePhoneProfileField[0].checked == true) {
                            calEvent.updatePhoneProfile = updatePhoneProfileField[0].checked;
                        }
                        //end -added by mushtaq 

                        if (locationField.val() != "123 Greenville St, Dallas, TX") {
                            //Make sure you dont add watermark text
                            calEvent.location = locationField.val();
                        }
                        else {
                            calEvent.location = "";
                        }
                        //END-UBS 12/17/2010:

                        if (calEvent.title.length > 0 && calEvent.start != undefined && calEvent.end != undefined
                                && self._isValidMeetingOrRestaurantEvent(calEvent) && self._isValidPhoneNumber(calEvent)) {
                            self.element.data("calEventInProg", calEvent);
                            var jsonPlan = JSON.stringify(self._createJsonPlan(calEvent, options.jsonTrip.iTripID));


                            //UBS 11/25/2010: Just update in the Calendar we will push it to DB all Changes at once from TripCalendar.ascx:Save()                            
                            var iFoundAtIndex = -1;
                            $.each(self.options.datePickerElement.data("calEventsToUpdate"), function (iCounter, event) {
                                if (event.id == calEvent.id && calEvent.id != -1) {
                                    iFoundAtIndex = iCounter;
                                    return false;
                                }
                            });
                            if (iFoundAtIndex > -1) {
                                //Event already exists in the Pending changes queue therefore just update it.
                                self.options.datePickerElement.data("calEventsToUpdate").splice(iFoundAtIndex, 1, calEvent);
                            }
                            else {
                                //does not exists in the queue therefore add it to the queue.
                                self.options.datePickerElement.data("calEventsToUpdate").push(calEvent);
                            }
                            self.options.datePickerElement.tripDatePicker("updateWCTitleMsg");
                            self.element.weekCalendar("updateEvent", calEvent);
                            $("#" + options.eventEditContainerID).dialog("close");
                        }
                        else {
                            //Show the error warnings and hide the required indicators.
                            self._displayValidationErrors($("#" + options.eventEditContainerID), calEvent);
                        }
                    },
                    "delete": function () {
                        self.element.data("calEventInProg", calEvent);
                        var jsonPlan = JSON.stringify(self._createJsonPlan(calEvent, options.jsonTrip.iTripID));
                        //UBS 11/25/2010: Just update in the Calendar we will push it to DB all Changes at once from TripCalendar.ascx:Save()                            
                        var iFoundAtIndex = -1;
                        $.each(self.options.datePickerElement.data("calEventsToDelete"), function (iCounter, event) {
                            if (event.id == calEvent.id && calEvent.id != -1) {
                                iFoundAtIndex = iCounter;
                                return false;
                            }
                        });
                        if (iFoundAtIndex > -1) {
                            //Event already exists in the Pending changes queue therefore dont have to do anything.
                        }
                        else {
                            //does not exists in the queue therefore add it to the queue.
                            self.options.datePickerElement.data("calEventsToDelete").push(calEvent);
                        }
                        self.options.datePickerElement.tripDatePicker("updateWCTitleMsg");
                        self.element.weekCalendar("removeEvent", calEvent.id);
                        $("#" + options.eventEditContainerID).dialog("close");
                    },
                    cancel: function () {
                        $("#" + options.eventEditContainerID).dialog("close");
                    }
                }
            }).show();

            var startField = $("#" + options.eventEditContainerID).find("select[name='start']").val(calEvent.start);
            var endField = $("#" + options.eventEditContainerID).find("select[name='end']").val(calEvent.end);
            $("#" + options.eventEditContainerID).find(".date_holder").text(self.element.weekCalendar("formatDate", calEvent.start));
            self._setupStartAndEndTimeFieldsForUpdate(startField, endField, calEvent, self.element.weekCalendar("getTimeslotTimes", calEvent.start));
            self._setupTypeDropdowns(typeField, viewTypeField, locationField, attendeesField, calEvent);
            $(window).resize().resize(); //fixes a bug in modal overlay size ??
        },

        _getNumberOfDaysToShow: function () {
            var self = this;
            var iReturn = 0;

            if (self.options.flgIsMobileView) {
                iReturn = 1;
            }
            else {
                try {
                    //Number of Days:
                    iReturn = (self.options.endDate.getDate() - self.options.beginDate.getDate()) + 1;
                } catch (e) {
                    trace(e.toString());
                }
                if (iReturn < 1 || iReturn > 7) {
                    iReturn = 7;
                }
            }

            return iReturn;
        },

        _getFirstDayOfWeek: function () {
            var self = this;
            var iReturn = 0;

            try {
                //get Day: 0 (sun) - 6(sat)
                iReturn = self.options.beginDate.getDay();
            } catch (e) {
                trace(e.toString());
            }

            return iReturn;
        },

        _appendLoadingDiv: function () {
            var self = this;
            //var $loading1 = $('<img src="loading.gif" alt="loading">');<span id="loading-calendar-msg">&nbsp;Updating....</span>

            //if (self.element.find('#loading-calendar').length == 0) {
            var $loading = $('<img src="/content/images/spinner.gif" alt="loading" /><span id="loading-calendar-msg">&nbsp;Loading....</span>');
            var $dialog = $('<div id=\"loading-calendar\"></div>').append($loading.clone());

            //$dialog.dialog({
            //    width: 150,
            //    height: 100,
            //    autoOpen: false,
            //    modal: true
            //});
            self.element.append($dialog);
            self.element.data("loadingDialog", $dialog);
            //}

        },

        _getDayPlans: function (date) {
            var self = this;
            var plans = [];

            $.each(self.options.jsonTrip.Plans, function (index, plan) {
                if (self._datesHaveSameDay(self._dateDeserialize(plan.StartDateTime), self.options.currentDate)) {
                    plans.push(plan);
                }
            });

            return plans;
        },

        _datesHaveSameDay: function (date1, date2) {
            var flgReturn = false;
            if (date1 != null && date2 != null) {
                if (typeof date1 == "object" && typeof date2 == "object") {
                    if (date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() == date2.getDate()) {
                        flgReturn = true;
                    }
                }
            }
            return flgReturn;
        },

        _renderMobileTripCalendar: function () {
            var self = this;
            var tripCalElement = this.element;
            var plans = self._getDayPlans(self.options.currentDate);
            var firstCalEventOfCurrentDate = null;
            var scrollToHour = null;

            firstCalEventOfCurrentDate = self._getCurrentDateFirstTripPlan();
            if (firstCalEventOfCurrentDate != null)
                scrollToHour = firstCalEventOfCurrentDate.start.getHours();
            else
                scrollToHour = self.options.scrollToHour;

            this.element.weekCalendar({
                date: self.options.currentDate,
                timeslotsPerHour: self.options.timeslotsPerHour,
                jsonTrip: self.options.jsonTrip,
                tripBeginDate: self.options.beginDate,
                tripEndDate: self.options.endDate,
                defaultTextLegButtons: self.options.defaultTextLegButtons,
                flgIsMobileView: self.options.flgIsMobileView,
                flgIsMobileListView: self.options.flgIsMobileListView,
                allowCalEventOverlap: true,
                firstDayOfWeek: self._getFirstDayOfWeek(), //0, //sun
                timeslotHeight: 20,
                scrollToHour: scrollToHour,
                daysToShow: self._getNumberOfDaysToShow(), //7,
                businessHours: { start: 8, end: 18, limitDisplay: false },
                height: function ($calendar) {
                    //return $(window).height() - $("h1").outerHeight();
                    return 495;
                },
                draggable: function (calEvent, $event) {
                    return self.options.draggable(calEvent, $event, self);
                },
                resizable: function (calEvent, $event) {
                    return self.options.resizable(calEvent, $event, self);
                },
                eventRender: function (calEvent, $event) {
                    self.options.eventRender(calEvent, $event, self);
                },
                eventNew: function (calEvent, $event) {
                    self.options.eventNew(calEvent, $event, self);
                },
                eventDrop: function (calEvent, $event) {
                    self.options.eventDrop(calEvent, $event, self);
                },
                eventResize: function (calEvent, $event) {
                    self.options.eventResize(calEvent, $event, self);
                },
                eventClick: function (calEvent, $event) {
                    self.options.eventClick(calEvent, $event, self);
                },
                eventMouseover: function (calEvent, $event) {
                    self.options.eventMouseover(calEvent, $event, self);
                },
                eventMouseout: function (calEvent, $event) {
                    self.options.eventMouseout(calEvent, $event, self);
                },
                noEvents: function () {
                    self.options.noEvents(self);
                },
                data: function (start, end, callback) {
                    self.options.data(start, end, callback, self);
                }
            });

            if (!self.options.flgIsMobileListView) {
                //For Month-view 

                this.element.hide();

                //detach previously loaded li's (plans) for prev day clicks.
                //Ticket #34 UBS 8/22/2011: replaced $ with self.element.find, and .each with .filter
                $('li[id]').filter(function (i) {
                    if ($(this).attr('id') != null) {
                        if ($(this).attr('id').match(/li_plan_/)) {
                            $(this).detach();
                        }
                    }
                });

                var ulHtml = "<ul data-role=\"listview\" data-theme=\"c\" role=\"listbox\">";
                var liHtml = "";
                var liHtmls = "";
                if (plans.length > 0) {
                    $.each(plans, function (i, plan) {
                        liHtml = "";

                        //liHtml += "<li role=\"none\" class=\"ui-li ui-li-static ui-btn-up-d ui-corner-bottom\">";
                        liHtml += "<li role=\"option\" id=\"li_plan_" + plan.ID + "\">";
                        liHtml += "<a href=\"/Trip/MobileTripCalendarViewEvent?iTripId=" + plan.TripID + "&iPlanId=" + plan.ID + "\" >" + plan.Title + "</a>";
                        //liHtml += "<a href=\"/Trip/MobileTripPlanComingSoon?iTripId=" + plan.TripID + "&iPlanId=" + plan.ID + "\" >" + plan.Title + "</a>";
                        liHtml += "</li>";
                        liHtmls += liHtml;
                    });
                    ulHtml += liHtmls + "</ul>";
                    //$(tripCalElement).append(ulHtml);
                    $("#ul_" + self.options.jsonTrip.iTripID).append(liHtmls);
                }
                else {
                    liHtml = "";
                    //liHtml += "<li role=\"option\" class=\"ui-li ui-li-static ui-btn-up-d ui-corner-bottom\">No Events";
                    liHtml += "<li role=\"option\" id=\"li_plan_\">No Events";
                    liHtml += "</li>";
                    ulHtml += liHtml + "</ul>";
                    //$(tripCalElement).append(ulHtml);
                    $("#ul_" + self.options.jsonTrip.iTripID).append(liHtml);
                }

                $("#ul_" + self.options.jsonTrip.iTripID).addClass("mobileLI");
                //$("#ul_" + self.options.jsonTrip.iTripID).listview("refresh");
                //Ticket #34 UBS 8/22/2011: commented the line above as it was causing an exception.
                if ($("#ul_" + self.options.jsonTrip.iTripID + ":visible").length) {
                    $("#ul_" + self.options.jsonTrip.iTripID).listview("refresh");
                }
                self._mobilePlanHrefsModify($("#ul_" + self.options.jsonTrip.iTripID));
            }
            else {
                //For Mobile Day view.

                //detach previously loaded li's (plans) for prev day clicks.
                //$('li').each(function () {
                //    if ($(this).attr('id').match(/li_plan_/)) {
                //        $(this).detach();
                //    }
                //});

                //Ticket #34 UBS 8/22/2011: commented the above section, replaced $ with self.element.find, and .each with .filter
                $('li[id]').filter(function (i) {
                    if ($(this).attr('id') != null) {
                        if ($(this).attr('id').match(/li_plan_/)) {
                            $(this).detach();
                        }
                    }
                });
                this.element.show();
                this.hideLoading();
            }

            //onclick="$(document.getElementById($(this).attr('href'))).remove();"
            //$("#ul_" + self.options.jsonTrip.iTripID).find('a[href]').bind("onclick", self._mobilePlanHrefsRemove(this));
        },

        _mobilePlanHrefsModify: function ($ulElement) {
            $ulElement.find('a[href]').attr('href', function (index, href) {
                if (href.indexOf("/Trip/MobileTripCalendarViewEvent") > -1) {
                    var param = 'key=' + Math.floor(Math.random() * 100000);
                    if (href.charAt(href.length - 1) === '?') //Very unlikely
                        return href + param;
                    else if (href.indexOf('?') > 0)
                        return href + '&' + param;
                    else
                        return href + '?' + param;
                } else {
                    return href;
                }
            });
        },

        //_mobilePlanHrefsRemove: function (href) {
        //    alert('inside _mobilePlanHrefsRemove');
        //    $(document.getElementById($(href).attr('href'))).remove();
        //},

        _renderTripCalendar: function () {
            var self = this;
            var dialogElement = this.element;
            var firstCalEventOfCurrentDate = null;
            var scrollToHour = null;

            firstCalEventOfCurrentDate = self._getCurrentDateFirstTripPlan();
            if (firstCalEventOfCurrentDate != null)
                scrollToHour = firstCalEventOfCurrentDate.start.getHours();
            else
                scrollToHour = self.options.scrollToHour;

            //self._appendLoadingDiv();

            this.element.weekCalendar({
                date: self.options.currentDate,
                timeslotsPerHour: self.options.timeslotsPerHour,
                jsonTrip: self.options.jsonTrip,
                tripBeginDate: self.options.beginDate,
                tripEndDate: self.options.endDate,
                defaultTextLegButtons: self.options.defaultTextLegButtons,
                flgIsMobileView: self.options.flgIsMobileView,
                flgIsMobileListView: self.options.flgIsMobileListView,
                flgIsEntireCalendarReadyonly: self.options.flgIsEntireCalendarReadyonly,
                allowCalEventOverlap: true,
                firstDayOfWeek: self._getFirstDayOfWeek(), //0, //sun
                timeslotHeight: 20,
                scrollToHour: scrollToHour,
                daysToShow: self._getNumberOfDaysToShow(), //7,
                businessHours: { start: 8, end: 18, limitDisplay: false },
                height: function ($calendar) {
                    //return $(window).height() - $("h1").outerHeight();
                    return 495;
                },
                draggable: function (calEvent, $event) {
                    return self.options.draggable(calEvent, $event, self);
                },
                resizable: function (calEvent, $event) {
                    return self.options.resizable(calEvent, $event, self);
                },
                eventRender: function (calEvent, $event) {
                    self.options.eventRender(calEvent, $event, self);
                },
                eventNew: function (calEvent, $event) {
                    self.options.eventNew(calEvent, $event, self);
                },
                eventDrop: function (calEvent, $event) {
                    self.options.eventDrop(calEvent, $event, self);
                },
                eventResize: function (calEvent, $event) {
                    self.options.eventResize(calEvent, $event, self);
                },
                eventClick: function (calEvent, $event) {
                    self.options.eventClick(calEvent, $event, self);
                },
                eventMouseover: function (calEvent, $event) {
                    self.options.eventMouseover(calEvent, $event, self);
                },
                eventMouseout: function (calEvent, $event) {
                    self.options.eventMouseout(calEvent, $event, self);
                },
                noEvents: function () {
                    self.options.noEvents(self);
                },
                data: function (start, end, callback) {
                    self.options.data(start, end, callback, self);
                }
            });
            //$("div.wc-scrollable-grid").scrollTop(350);
        }, //end of _renderTripCalendar()

        _toggleLocAttendeesFields: function () {
            var options = this.options;
            var self = this;

            self._resetValidationIconsOnEventForm();

            $locationLiField = $("#" + options.eventEditContainerID).find("li[rel=location]");
            $attendeesLiField = $("#" + options.eventEditContainerID).find("li[rel=attendees]");
            $SMSalertLiField = $("#" + options.eventEditContainerID).find("li[rel=SMSAlert]");
            $phoneNumberLiField = $("#" + options.eventEditContainerID).find("li[rel=phoneNumber]");
            $typeOptionsField = $("#" + options.eventEditContainerID).find("li[rel=type]");
            $viewTypeOptionsField = $("#" + options.eventEditContainerID).find("li[rel=viewType]");
            $titleField = $("#" + options.eventEditContainerID).find("li[rel=title]");
            $smsAlertField = $("#" + options.eventEditContainerID).find("input[name='SMSAlert']");

            switch (parseInt($typeOptionsField.find('select').val() /*$typeOptionsField.val()*/)) {
                case Enums.PlanType.eMeeting:
                case Enums.PlanType.eRestaurant:
                    $locationLiField.show();
                    $attendeesLiField.show();
                    if ($smsAlertField.length > 0 && $smsAlertField[0].checked == true) {
                        $phoneNumberLiField.show();
                    }
                    else {
                        $phoneNumberLiField.hide();
                    }
                    break;
                default:
                    $locationLiField.hide();
                    $attendeesLiField.hide();
                    if ($smsAlertField.length > 0 && $smsAlertField[0].checked == true) {
                        $phoneNumberLiField.show();
                    }
                    else {
                        $phoneNumberLiField.hide();
                    }
                    break;
            };
        },

        _toggleMobileEventDateField: function (calEvent, calEventJsonText, flgNewEvent, self) {
            var options = self.options;
            //var self = this;

            self._updateMobileEventEditContainerID(calEventJsonText);

            var startField = $("#" + options.eventEditContainerID).find("select[name='start']");
            var endField = $("#" + options.eventEditContainerID).find("select[name='end']");
            var dateFieldVal = $("#" + options.eventEditContainerID).find("select[name='date']").val();
            var dateDateField = (new Date(dateFieldVal));

            if (flgNewEvent) {
                var timeSlots = self.element.weekCalendar("getTimeslotTimes", dateDateField);
            } else {
                //if modifying an existing event.
                var date = null;
                if (dateDateField.getDate() == calEvent.start.getDate()) {
                    date = calEvent.start;
                } else {
                    date = new Date(dateDateField.getFullYear(), dateDateField.getMonth(), dateDateField.getDate(), dateDateField.getHours(), dateDateField.getMinutes(), dateDateField.getSeconds(), dateDateField.getMilliseconds());
                }
                var timeSlots = self.element.weekCalendar("getTimeslotTimes", date);
            }

            if (timeSlots.length > 1) {
                $("#" + options.eventEditContainerID).find("select[name='end']").find("option[value != '']").detach();
                $("#" + options.eventEditContainerID).find("select[name='start']").find("option[value != '']").detach();

                self._setupStartAndEndTimeFieldsForUpdate(startField, endField, calEvent, timeSlots);

                if (flgNewEvent) {
                    startField.find('option[selected="selected"]').removeAttr("selected");
                    endField.find('option[selected="selected"]').removeAttr("selected");
                }

                startField.selectmenu("refresh");
                endField.selectmenu("refresh");
            }
            else {
                alert('error occurred on toggle date: dateDateField = ' + dateDateField);
            }
        },

        _resetValidationIconsOnEventForm: function () {
            var options = this.options;

            $locationLiField = $("#" + options.eventEditContainerID).find("li[rel=location]");
            $attendeesLiField = $("#" + options.eventEditContainerID).find("li[rel=attendees]");
            $typeOptionsField = $("#" + options.eventEditContainerID).find("li[rel=type]");
            $viewTypeOptionsField = $("#" + options.eventEditContainerID).find("li[rel=viewType]");
            $titleField = $("#" + options.eventEditContainerID).find("li[rel=title]");
            $smsAlertField = $("#" + options.eventEditContainerID).find("input[name='SMSAlert']");
            $phoneNumberLiField = $("#" + options.eventEditContainerID).find("li[rel='phoneNumber']");

            //reset the validation icons
            $locationLiField.find(".required_data_missing").hide();
            $locationLiField.find(".required_data").show();
            $attendeesLiField.find(".required_data_missing").hide();
            $attendeesLiField.find(".required_data").show();
            $titleField.find(".required_data_missing").hide();
            $titleField.find(".required_data").show();
            $titleField.find(".required_data_missing").hide();
            $titleField.find(".required_data").show();
            //added by mushtaq
            //UBS 3/11/2011: make sure we have elements.
            if ($smsAlertField.length > 0 && $smsAlertField[0].checked == true) {
                $phoneNumberLiField.find(".required_data_missing").hide();
                $phoneNumberLiField.find(".required_data").show();
            }
        },

        /*
        * Sets up the dropdown for trip days. Used in Mobile Calendar views (for Modifying the plans)
        */
        _setupTripDayDropdowns: function ($dateOptionsField, calEvent) {
            var self = this;
            var flgIsUpdateEvent = false;
            var iTotalTripDays = 1;
            var temp = 0;
            var msecsInADay = 86400000;

            if (calEvent != undefined && calEvent != null) {
                flgIsUpdateEvent = true;
            }

            //calculate total trip days
            temp = Math.floor((self.options.endDate - self.options.beginDate) / (24 * 60 * 60 * 1000));
            iTotalTripDays = temp;
            if (temp < 1) {
                //iTotalTripDays = temp;
                iTotalTripDays = 1;
            }

            for (i = 0; i <= iTotalTripDays; i++) {
                var sOptionVal = '';
                var flgSelected = false;
                var sCalEventStartVal = '';
                var tempDate = null;

                tempDate = new Date(self.options.beginDate.getTime() + i * msecsInADay);
                sOptionVal = self.element.weekCalendar("formatDate", tempDate);
                sCalEventStartVal = self.element.weekCalendar("formatDate", calEvent.start);
                if (sOptionVal == sCalEventStartVal) {
                    flgSelected = true;
                }

                if (!flgSelected) {
                    if ($dateOptionsField.text().indexOf(sOptionVal) < 0) {
                        $dateOptionsField.append("<option value=\"" + tempDate + "\">" + sOptionVal + "</option>");
                    }
                }
                else {
                    if ($dateOptionsField.text().indexOf(sOptionVal) < 0) {
                        $dateOptionsField.append("<option value=\"" + tempDate + "\" selected=\"yes\"" + ">" + sOptionVal + "</option>");
                    }
                }
            }

            if (self.options.flgIsMobileView) {
                $dateOptionsField.selectmenu('refresh');
            }

        },

        /*
        * Sets up the dropdown for plan types.
        * form for editing based on the calendar event being edited
        * UBS 1/13/2011 : Added calEvent param. If Null then its from _renderNewEvent, else its from _renderEventClick.
        */
        _setupTypeDropdowns: function ($typeOptionsField, $viewTypeOptionsField, $locationField, $attendeesField, calEvent) {
            var self = this;
            var flgIsUpdateEvent = false;
            if (calEvent != undefined && calEvent != null) {
                flgIsUpdateEvent = true;
            }

            $.each(Enums.PlanType, function (iCount, enumVal) {
                var sOptionVal = '';
                var flgSelected = false;

                switch (enumVal) {
                    case Enums.PlanType.eOther:
                        sOptionVal = "Other";
                        break;
                    case Enums.PlanType.eAirDepartureOrArrival:
                        sOptionVal = "Air Departure or Arrival";
                        break;
                    case Enums.PlanType.eHotelCheckin:
                        sOptionVal = "Hotel Checkin";
                        break;
                    case Enums.PlanType.eHotelCheckout:
                        sOptionVal = "Hotel Checkout";
                        break;
                    case Enums.PlanType.eCarPickup:
                        sOptionVal = "Car Pickup";
                        break;
                    case Enums.PlanType.eCarDropoff:
                        sOptionVal = "Car Dropoff";
                        break;
                    case Enums.PlanType.eMeeting:
                        sOptionVal = "Meeting";
                        //we should make this default selection only if its a new event.
                        if (!flgIsUpdateEvent) { flgSelected = true; }
                        break;
                    case Enums.PlanType.eRestaurant:
                        sOptionVal = "Restaurant";
                        break;
                    default:
                        sOptionVal = "Other";
                        break;
                }; //end of switch

                if (!flgSelected) {
                    if ($typeOptionsField.text().indexOf(sOptionVal) < 0) {
                        $typeOptionsField.append("<option value=\"" + enumVal + "\">" + sOptionVal + "</option>");
                    }
                }
                else {
                    if ($typeOptionsField.text().indexOf(sOptionVal) < 0) {
                        $typeOptionsField.append("<option value=\"" + enumVal + "\" selected=\"yes\"" + ">" + sOptionVal + "</option>");
                    }
                }

            }); //end of each 
            //Mushtaq [Ticket# 14] [18 May 2010]
            $.each(Enums.AccessLevel, function (iCount, enumVal) {
                var sViewOptionVal = '';
                var flgViewSelected = false;

                switch (enumVal) {
                    case Enums.AccessLevel.ePublic:
                        sViewOptionVal = "Public";
                        //we should make this default selection only if its a new event.
                        if (!flgIsUpdateEvent) { flgViewSelected = true; }
                        break;
                    case Enums.AccessLevel.ePrivate:
                        sViewOptionVal = "Private";
                        break;
                    default:
                        sViewOptionVal = "Public";
                        break;
                }; // end of switch

                if (!flgViewSelected) {
                    if ($viewTypeOptionsField.text().indexOf(sViewOptionVal) < 0) {
                        $viewTypeOptionsField.append("<option value=\"" + enumVal + "\">" + sViewOptionVal + "</option>");
                    }
                }
                else {
                    if ($viewTypeOptionsField.text().indexOf(sViewOptionVal) < 0) {
                        $viewTypeOptionsField.append("<option value=\"" + enumVal + "\" selected=\"yes\"" + ">" + sViewOptionVal + "</option>");
                    }
                }
            }); //end of each

            //if its an Event-Update then make sure we set the right type selected.
            if (flgIsUpdateEvent) {
                $typeOptionsField.find('option[value=' + calEvent.type + ']').attr('selected', 'selected');
                $viewTypeOptionsField.find('option[value=' + calEvent.viewType + ']').attr('selected', 'selected'); //Mushtaq [Ticket# 14] [18 May 2010]
            }

            if (self.options.flgIsMobileView) {
                $typeOptionsField.selectmenu('refresh');
                $viewTypeOptionsField.selectmenu('refresh'); //Mushtaq [Ticket# 14] [18 May 2010]
            }

            self._toggleLocAttendeesFields();
        },

        /*
        * Sets up the start and end time fields in the calendar event 
        * form for editing based on the calendar event being edited
        */
        _setupStartAndEndTimeFields: function ($startTimeField, $endTimeField, calEvent, timeslotTimes) {
            var options = this.options;
            var self = this;
            var flgClearStartTimes = false;
            var flgClearEndTimes = false;

            //first check if the times are for the day that the calEvent is being created.
            for (var i = 0; i < timeslotTimes.length; i++) {
                if ($($startTimeField.find("option[value=" + "\"" + timeslotTimes[i].start + "\"]")).length == 0) {
                    //This means that the start-time is not found in the existing options hence clear the entire options from the start-dropdown
                    flgClearStartTimes = true;
                    //If there is only one option i.e. 'Select Start Time' then we dont have to remove it.
                    $startTimeField.find("option[value != '']").remove();
                }

                if ($($endTimeField.find("option[value=" + "\"" + timeslotTimes[i].end + "\"]")).length == 0) {
                    //This means that the end-time is not found in the existing options hence clear the entire options from the end-dropdown
                    flgClearEndTimes = true;
                    //If there is only one option i.e. 'Select End Time' then we dont have to remove it.
                    $endTimeField.find("option[value != '']").remove();
                }

                if (flgClearEndTimes && flgClearStartTimes) {
                    //once we know that we have cleared both the start and end time dropdowns we dont have to loop any further hence exit
                    break;
                }
            }

            if (!options.flgIsMobileView) {

                //now loop thru each time slot, add the time for start-time/end-time options (if the dropdowns are cleared), set the selected values appropriately.
                for (var i = 0; i < timeslotTimes.length; i++) {
                    var startTime = timeslotTimes[i].start;
                    var endTime = timeslotTimes[i].end;

                    var startSelected = "";
                    if (startTime.getTime() === calEvent.start.getTime()) {
                        startSelected = "selected=\"selected\"";
                    }
                    var endSelected = "";
                    if (endTime.getTime() === calEvent.end.getTime()) {
                        endSelected = "selected=\"selected\"";
                    }

                    //UBS 12/22/2010: Wrapped the appends in the IF's. So that we avoid dupe entries.
                    if (flgClearStartTimes) {
                        //The start-time dropdown lists was cleared. Therefore add a new option to the start-time dropdown list.
                        $startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
                    }
                    else {
                        //The start-time dropdown list was not cleared, which means time options present belonged to the same day as calEvent start-time.
                        //hence check if the time is selected time, if it is then add "selected" attribute to that time-option.
                        if (startSelected.length > 0) {
                            $($startTimeField.find("option[value=" + "\"" + timeslotTimes[i].start + "\"]")).attr("selected", "selected");
                        }
                    }
                    if (flgClearEndTimes) {
                        //The end-time dropdown lists was cleared. Therefore add a new option to the end-time dropdown list.
                        $endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");
                    }
                    else {
                        //The end-time dropdown list was not cleared, which means time options present belonged to the same day as calEvent end-time.
                        //hence check if the time is selected time, if it is then add "selected" attribute to that time-option.
                        if (endSelected.length > 0) {
                            $($endTimeField.find("option[value=" + "\"" + timeslotTimes[i].end + "\"]")).attr("selected", "selected");
                        }
                    }
                    //END-UBS 12/22/2010:

                }
            }
            $endTimeOptions = $endTimeField.find("option");
            $startTimeField.trigger("change");
        },

        /*
        * Sets up the start and end time fields in the calendar event 
        * form for editing based on the calendar event being edited
        */
        _setupStartAndEndTimeFieldsForUpdate: function ($startTimeField, $endTimeField, calEvent, timeslotTimes) {
            var self = this;
            var options = this.options;
            var flgClearStartTimes = false;
            var flgClearEndTimes = false;

            //first check if the times are for the day that the calEvent is being created.
            for (var i = 0; i < timeslotTimes.length; i++) {
                if ($($startTimeField.find("option[value=" + "\"" + timeslotTimes[i].start + "\"]")).length == 0) {
                    //This means that the start-time is not found in the existing options hence clear the entire options from the start-dropdown
                    flgClearStartTimes = true;
                    //If there is only one option i.e. 'Select Start Time' then we dont have to remove it.
                    $startTimeField.find("option[value != '']").remove();
                }

                if ($($endTimeField.find("option[value=" + "\"" + timeslotTimes[i].end + "\"]")).length == 0) {
                    //This means that the end-time is not found in the existing options hence clear the entire options from the end-dropdown
                    flgClearEndTimes = true;
                    //If there is only one option i.e. 'Select End Time' then we dont have to remove it.
                    $endTimeField.find("option[value != '']").remove();
                }

                if (flgClearEndTimes && flgClearStartTimes) {
                    //once we know that we have cleared both the start and end time dropdowns we dont have to loop any further hence exit
                    break;
                }
            }

            for (var i = 0; i < timeslotTimes.length; i++) {
                var startTime = timeslotTimes[i].start;
                var endTime = timeslotTimes[i].end;
                var startSelected = "";
                var endSelected = "";

                if (/*Math.abs(startTime.getDate() - calEvent.start.getDate()) == 0 &&*/
                    Math.abs(startTime.getHours() - calEvent.start.getHours()) == 0 &&
                    Math.abs(startTime.getMinutes() - calEvent.start.getMinutes()) < 60 / options.timeslotsPerHour) {
                    startSelected = "selected=\"selected\"";
                }

                if (/*Math.abs(endTime.getDate() - calEvent.end.getDate()) == 0 &&*/
                    Math.abs(endTime.getHours() - calEvent.end.getHours()) == 0 &&
                    Math.abs(endTime.getMinutes() - calEvent.end.getMinutes()) < 60 / options.timeslotsPerHour) {
                    endSelected = "selected=\"selected\"";
                }

                //$startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
                //$endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");

                //UBS 12/27/2010: Wrapped the appends in the IF's. So that we avoid dupe entries.
                if (flgClearStartTimes || self.options.flgIsMobileView) {
                    //The start-time dropdown lists was cleared. Therefore add a new option to the start-time dropdown list.
                    $startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
                }
                else {
                    //The start-time dropdown list was not cleared, which means time options present belonged to the same day as calEvent start-time.
                    //hence check if the time is selected time, if it is then add "selected" attribute to that time-option.
                    if (startSelected.length > 0) {
                        $($startTimeField.find("option[value=" + "\"" + timeslotTimes[i].start + "\"]")).attr("selected", "selected");
                    }
                }
                if (flgClearEndTimes || self.options.flgIsMobileView) {
                    //The end-time dropdown lists was cleared. Therefore add a new option to the end-time dropdown list.
                    $endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");
                }
                else {
                    //The end-time dropdown list was not cleared, which means time options present belonged to the same day as calEvent end-time.
                    //hence check if the time is selected time, if it is then add "selected" attribute to that time-option.
                    if (endSelected.length > 0) {
                        $($endTimeField.find("option[value=" + "\"" + timeslotTimes[i].end + "\"]")).attr("selected", "selected");
                    }
                }
                //END-UBS 12/27/2010:

            }

            if (self.options.flgIsMobileView) {
                //$endTimeField.selectmenu('refresh');
                //$startTimeField.selectmenu('refresh');
            }

            //$endTimeOptions = $endTimeField.find("option");
            //$startTimeField.trigger("change");
        }

    }) //end of widget - "ui.tripCalendar"

})(jQuery);
