var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var portal;
(function (portal) {
    var general;
    (function (general) {
        var accounts;
        (function (accounts) {
            "use strict";
            function InitAccountsPage($container) {
                new AccountsManager($container);
            }
            accounts.InitAccountsPage = InitAccountsPage;
            function InitDisputesPage($container) {
                new ChargeGroupsManager($container);
            }
            accounts.InitDisputesPage = InitDisputesPage;
            function InitStatementDateRange($container) {
                var chargeGroupID = $container.data("chargegroupid");
                if (starrez.library.utils.IsNotNullUndefined(chargeGroupID)) {
                    chargeGroupID = Number(chargeGroupID);
                }
                portal.PageElements.$actions.find(".ui-btn-showreport").SRClick(function (e) {
                    var call = new starrez.service.accounts.GetStatementReport({
                        pageID: portal.page.CurrentPage.PageID,
                        dateStart: $container.GetControl("StatementDateStart").SRVal(),
                        dateEnd: $container.GetControl("StatementDateEnd").SRVal(),
                        chargeGroupID: chargeGroupID
                    });
                    starrez.library.service.OpenInNewTab(call.GetURLWithParameters());
                });
            }
            accounts.InitStatementDateRange = InitStatementDateRange;
            function InitAccountsSettings($container) {
                var $statementType = $container.GetControl("StatementReportType");
                var $statementLayout = $container.GetControl("StatementReportLayout");
                var $invoiceType = $container.GetControl("InvoiceReportType");
                var $invoiceLayout = $container.GetControl("InvoiceReportLayout");
                $statementType.change(function (e) {
                    ReportTypeChanged(true, $statementType.SRVal(), $statementLayout);
                });
                $invoiceType.change(function (e) {
                    ReportTypeChanged(false, $invoiceType.SRVal(), $invoiceLayout);
                });
            }
            accounts.InitAccountsSettings = InitAccountsSettings;
            function ReportTypeChanged(isStatement, reportType, $ctrl) {
                var call = new starrez.service.accounts.GetReportLayouts({
                    isStatement: isStatement,
                    reportType: reportType
                });
                call.Request(function (data) {
                    starrez.library.controls.dropdown.FillDropDown(data, $ctrl, "Value", "Text", $ctrl.SRVal(), true);
                });
            }
            var ChargeGroupsManager = (function () {
                function ChargeGroupsManager($container) {
                    var _this = this;
                    this.$container = $container;
                    this.model = starrez.model.EntryTransactionsBaseModel($container);
                    var $tableContainer = $container.find(".ui-account-summary-container");
                    var tables = starrez.tablesetup.CreateTableManager($tableContainer.find("table"), $tableContainer, {
                        AttachRowClickEvent: true,
                        OnRowClick: function ($tr, data, e, manager) { _this.LoadDetailsTable($tr); }
                    });
                    this.chargeGroupsTable = tables[0];
                    this.AttachFocusEvents($tableContainer);
                    this.$detailsContainer = $container.find(".ui-account-details-container");
                }
                ChargeGroupsManager.prototype.LoadDetailsTable = function ($tr) {
                    var _this = this;
                    // The row is (de-)selected when it's clicked before this function is called.
                    // So isSelected here means it was clicked for the first time.
                    // If the raw was selected, the calling function will deselect it, so isSelected here will be false.
                    if ($tr.isSelected()) {
                        var call;
                        var rawTermSessionID = $tr.data("termsession");
                        if (starrez.library.utils.IsNotNullUndefined(rawTermSessionID)) {
                            call = new starrez.service.accounts.GetAccountDetailsForTermSession({
                                pageID: portal.page.CurrentPage.PageID,
                                chargeGroupID: Number($tr.data("chargegroup")),
                                termSessionID: Number(rawTermSessionID)
                            }).Request({ ActionVerb: starrez.library.service.RequestType.Post, UseStandardError: false });
                        }
                        else {
                            call = new starrez.service.accounts.GetAccountDetails({
                                pageID: portal.page.CurrentPage.PageID,
                                chargeGroupID: Number($tr.data("chargegroup"))
                            }).Request({ ActionVerb: starrez.library.service.RequestType.Post, UseStandardError: false });
                        }
                        call.done(function (html) {
                            _this.$detailsContainer.html(html);
                            _this.$container.data("TransactionsManager", new TransactionsManager(_this.$detailsContainer, _this.model));
                        }).fail(function () {
                            portal.page.CurrentPage.SetErrorMessage(_this.model.LoadTransactionsErrorMessage);
                        });
                    }
                };
                ChargeGroupsManager.prototype.AttachFocusEvents = function ($tableContainer) {
                    var _this = this;
                    $tableContainer.on("focusin", function (e) {
                        if ($(e.target).hasClass("ui-account-summary-container")) {
                            _this.chargeGroupsTable.DisplayFocus(true);
                        }
                        else {
                            _this.chargeGroupsTable.DisplayFocus(false);
                        }
                    });
                    $tableContainer.on("focusout", function (e) {
                        _this.chargeGroupsTable.DisplayFocus(false);
                    });
                };
                return ChargeGroupsManager;
            })();
            var AccountsManager = (function (_super) {
                __extends(AccountsManager, _super);
                function AccountsManager($container) {
                    _super.call(this, $container);
                    this.$container = $container;
                    this.accountsModel = starrez.model.AccountSummaryModel($container);
                    if (!this.accountsModel.SplitChargeGroupByTermSession) {
                        this.$manualBreakup = $container.GetControl("ManualBreakup");
                        this.AttachManualBreakupClick();
                    }
                    this.$totalToPay = $container.GetControl("TotalToPay");
                    this.$breakupAmounts = $container.GetControl("AmountToPay");
                    this.AttachPayButton();
                    this.AttachStatementButton();
                    this.AttachBreakupAmountsChange();
                    this.DisableRowSelectionOnInputClick();
                    this.ToggleAmountInputs();
                }
                AccountsManager.prototype.AttachStatementButton = function () {
                    var _this = this;
                    this.$container.find(".ui-btn-view-statement").SRClick(function (e) {
                        var $chargeGroup = _this.chargeGroupsTable.SelectedRows().first();
                        var call = new starrez.service.accounts.GetStatementDateInput({
                            pageID: portal.page.CurrentPage.PageID,
                            chargeGroupID: $chargeGroup.isFound() ? $chargeGroup.data("chargegroup") : null
                        });
                        call.Request().done(function (url) {
                            window.location.href = url;
                        });
                    });
                };
                AccountsManager.prototype.DisableRowSelectionOnInputClick = function () {
                    this.$breakupAmounts.SRClick(function (e) {
                        e.stopPropagation();
                    });
                };
                AccountsManager.prototype.PaySelectedAccounts = function () {
                    var amounts = [];
                    var areAmountsValid = true;
                    this.chargeGroupsTable.Rows().each(function (index, row) {
                        var $row = $(row);
                        var $ctrl = $row.GetControl("AmountToPay");
                        var validationResult = starrez.library.validation.ValidateField($ctrl);
                        if (!validationResult.IsValid) {
                            areAmountsValid = false;
                            return;
                        }
                        var amt = Number($ctrl.SRVal());
                        if (amt > 0) {
                            var chargeGroupID = $row.data("chargegroup");
                            var termSessionID = $row.data("termsession");
                            amounts.push({ ChargeGroupID: chargeGroupID, TermSessionID: termSessionID, Amount: amt });
                        }
                    });
                    if (!areAmountsValid) {
                        portal.page.CurrentPage.SetErrorMessage(this.accountsModel.EnterAmountsToPayMessage);
                    }
                    else {
                        new starrez.service.accounts.AddPaymentsToCart({
                            pageID: portal.page.CurrentPage.PageID,
                            payments: amounts
                        }).Post().done(function () {
                            portal.page.CurrentPage.SubmitPage();
                        });
                    }
                };
                AccountsManager.prototype.PayAllAccounts = function () {
                    var validationResult = starrez.library.validation.ValidateField(this.$totalToPay);
                    var amount = Number(this.$totalToPay.SRVal());
                    if (!validationResult.IsValid) {
                        portal.page.CurrentPage.SetErrorMessage(this.accountsModel.EnterAmountsToPayMessage);
                    }
                    else {
                        new starrez.service.accounts.PayAll({
                            pageID: portal.page.CurrentPage.PageID,
                            amount: amount
                        }).Post().done(function (response) {
                            portal.page.CurrentPage.SubmitPage();
                        });
                    }
                };
                AccountsManager.prototype.AttachPayButton = function () {
                    var _this = this;
                    this.$container.find(".ui-btn-pay-selected").SRClick(function (e) {
                        if (_this.UseManualBreakup()) {
                            _this.PaySelectedAccounts();
                        }
                        else {
                            _this.PayAllAccounts();
                        }
                    });
                };
                AccountsManager.prototype.UseManualBreakup = function () {
                    if (this.accountsModel.SplitChargeGroupByTermSession) {
                        return true;
                    }
                    else {
                        return this.$manualBreakup.SRVal();
                    }
                };
                AccountsManager.prototype.AttachManualBreakupClick = function () {
                    var _this = this;
                    this.$manualBreakup.change(function (e) {
                        _this.ToggleAmountInputs();
                    });
                };
                AccountsManager.prototype.ToggleAmountInputs = function () {
                    if (this.UseManualBreakup()) {
                        this.$totalToPay.Disable();
                        this.$breakupAmounts.Enable();
                        this.UpdateTotalAmountByPaymentBreakup();
                    }
                    else {
                        this.$totalToPay.Enable();
                        this.$breakupAmounts.Disable();
                        this.UpdateTotalAmountToOustandingBalance();
                    }
                };
                AccountsManager.prototype.AttachBreakupAmountsChange = function () {
                    var _this = this;
                    this.$breakupAmounts.focusout(function (e) {
                        _this.CleanCurrencyTextbox($(e.target));
                        _this.UpdateTotalAmountByPaymentBreakup();
                    });
                };
                AccountsManager.prototype.CleanCurrencyTextbox = function ($control) {
                    var amountString = $control.SRVal();
                    if (starrez.library.stringhelper.IsUndefinedOrEmpty(amountString)) {
                        $control.SRVal(this.FormatCurrency(0));
                        return;
                    }
                    var amount = Number($control.SRVal());
                    $control.SRVal(this.FormatCurrency(amount));
                };
                ;
                AccountsManager.prototype.UpdateTotalAmountByPaymentBreakup = function () {
                    this.$totalToPay.SRVal(this.FormatCurrency(this.GetBreakupAmountsTotal()));
                };
                ;
                AccountsManager.prototype.UpdateTotalAmountToOustandingBalance = function () {
                    this.$totalToPay.SRVal(this.FormatCurrency(this.accountsModel.TotalToPay));
                };
                AccountsManager.prototype.GetBreakupAmountsTotal = function () {
                    var lineAmount;
                    var total = 0;
                    this.$breakupAmounts.each(function (index, element) {
                        lineAmount = Number($(element).SRVal());
                        if (!isNaN(lineAmount)) {
                            total += lineAmount;
                        }
                    });
                    return total;
                };
                ;
                AccountsManager.prototype.FormatCurrency = function (amount) {
                    return amount.toFixed(this.accountsModel.MoneyInputDecimalPlaces);
                };
                return AccountsManager;
            })(ChargeGroupsManager);
            var TransactionsManager = (function () {
                function TransactionsManager($container, model) {
                    this.$container = $container;
                    this.model = model;
                    var tables = starrez.tablesetup.CreateTableManager($container.find("table"), $container, {
                        AttachRowClickEvent: true
                    });
                    // If there are no transactions, there will be no table
                    if (tables.length > 0) {
                        this.transactionsTable = tables[0];
                        this.AttachInvoiceButton();
                        this.AttachDisputeButton();
                        this.transactionsTable.Rows().each(function (i, e) {
                            var $row = $(e);
                            if (!starrez.library.convert.ToBoolean($row.data("isdisputable"))) {
                                $row.GetControl("Select").Disable();
                                $row.prop("title", model.CannotDisputeTransactionMessage);
                            }
                        });
                    }
                }
                TransactionsManager.prototype.AttachInvoiceButton = function () {
                    this.$container.find(".ui-btn-view-invoice").SRClick(function (e) {
                        var call = new starrez.service.accounts.GetInvoiceReport({
                            pageID: portal.page.CurrentPage.PageID,
                            invoiceID: $(e.currentTarget).closest("tr").data("invoice")
                        });
                        starrez.library.service.OpenInNewTab(call.GetURLWithParameters());
                    });
                };
                TransactionsManager.prototype.AttachDisputeButton = function () {
                    var _this = this;
                    this.$container.find(".ui-btn-dispute").SRClick(function (e) {
                        var selectedTransactions = _this.GetSelectedIDs();
                        if (selectedTransactions.length < 1) {
                            portal.page.CurrentPage.SetErrorMessage(_this.model.TransactionsNotSelectedErrorMessage);
                        }
                        else {
                            new starrez.service.accounts.GetDisputeUrl({
                                pageID: portal.page.CurrentPage.PageID,
                                transactionIDs: selectedTransactions
                            }).Request().done(function (url) {
                                window.location.href = url;
                            });
                        }
                    });
                };
                TransactionsManager.prototype.GetSelectedIDs = function () {
                    return this.transactionsTable
                        .SelectedRows()
                        .map(function (i, e) { return Number($(e).data("transaction")); })
                        .toArray();
                };
                return TransactionsManager;
            })();
        })(accounts = general.accounts || (general.accounts = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function AccountSummaryModel($sys) {
            return {
                EnterAmountsToPayMessage: $sys.data('enteramountstopaymessage'),
                MoneyInputDecimalPlaces: Number($sys.data('moneyinputdecimalplaces')),
                SplitChargeGroupByTermSession: starrez.library.convert.ToBoolean($sys.data('splitchargegroupbytermsession')),
                TotalToPay: Number($sys.data('totaltopay'))
            };
        }
        model.AccountSummaryModel = AccountSummaryModel;
        function EntryTransactionsBaseModel($sys) {
            return {
                CannotDisputeTransactionMessage: $sys.data('cannotdisputetransactionmessage'),
                ChargeGroupID: $sys.data('chargegroupid'),
                LoadTransactionsErrorMessage: $sys.data('loadtransactionserrormessage'),
                Transaction_TermSessionID: $sys.data('transaction_termsessionid'),
                TransactionsNotSelectedErrorMessage: $sys.data('transactionsnotselectederrormessage')
            };
        }
        model.EntryTransactionsBaseModel = EntryTransactionsBaseModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var accounts;
        (function (accounts) {
            "use strict";
            var AddPaymentsToCart = (function (_super) {
                __extends(AddPaymentsToCart, _super);
                function AddPaymentsToCart(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Accounts";
                    this.Controller = "accounts";
                    this.Action = "AddPaymentsToCart";
                }
                AddPaymentsToCart.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID,
                        payments: this.o.payments
                    };
                    return obj;
                };
                return AddPaymentsToCart;
            })(starrez.library.service.AddInActionCallBase);
            accounts.AddPaymentsToCart = AddPaymentsToCart;
            var GetAccountDetails = (function (_super) {
                __extends(GetAccountDetails, _super);
                function GetAccountDetails(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Accounts";
                    this.Controller = "accounts";
                    this.Action = "GetAccountDetails";
                }
                GetAccountDetails.prototype.CallData = function () {
                    var obj = {
                        chargeGroupID: this.o.chargeGroupID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return GetAccountDetails;
            })(starrez.library.service.AddInActionCallBase);
            accounts.GetAccountDetails = GetAccountDetails;
            var GetAccountDetailsForTermSession = (function (_super) {
                __extends(GetAccountDetailsForTermSession, _super);
                function GetAccountDetailsForTermSession(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Accounts";
                    this.Controller = "accounts";
                    this.Action = "GetAccountDetailsForTermSession";
                }
                GetAccountDetailsForTermSession.prototype.CallData = function () {
                    var obj = {
                        chargeGroupID: this.o.chargeGroupID,
                        pageID: this.o.pageID,
                        termSessionID: this.o.termSessionID
                    };
                    return obj;
                };
                return GetAccountDetailsForTermSession;
            })(starrez.library.service.AddInActionCallBase);
            accounts.GetAccountDetailsForTermSession = GetAccountDetailsForTermSession;
            var GetDisputeUrl = (function (_super) {
                __extends(GetDisputeUrl, _super);
                function GetDisputeUrl(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Accounts";
                    this.Controller = "accounts";
                    this.Action = "GetDisputeUrl";
                }
                GetDisputeUrl.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID,
                        transactionIDs: this.o.transactionIDs
                    };
                    return obj;
                };
                return GetDisputeUrl;
            })(starrez.library.service.AddInActionCallBase);
            accounts.GetDisputeUrl = GetDisputeUrl;
            var GetInvoiceReport = (function (_super) {
                __extends(GetInvoiceReport, _super);
                function GetInvoiceReport(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Accounts";
                    this.Controller = "accounts";
                    this.Action = "GetInvoiceReport";
                }
                GetInvoiceReport.prototype.CallData = function () {
                    var obj = {
                        invoiceID: this.o.invoiceID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return GetInvoiceReport;
            })(starrez.library.service.AddInActionCallBase);
            accounts.GetInvoiceReport = GetInvoiceReport;
            var GetReportLayouts = (function (_super) {
                __extends(GetReportLayouts, _super);
                function GetReportLayouts(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Accounts";
                    this.Controller = "accounts";
                    this.Action = "GetReportLayouts";
                }
                GetReportLayouts.prototype.CallData = function () {
                    var obj = {
                        isStatement: this.o.isStatement,
                        reportType: this.o.reportType
                    };
                    return obj;
                };
                return GetReportLayouts;
            })(starrez.library.service.AddInActionCallBase);
            accounts.GetReportLayouts = GetReportLayouts;
            var GetStatementDateInput = (function (_super) {
                __extends(GetStatementDateInput, _super);
                function GetStatementDateInput(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Accounts";
                    this.Controller = "accounts";
                    this.Action = "GetStatementDateInput";
                }
                GetStatementDateInput.prototype.CallData = function () {
                    var obj = {
                        chargeGroupID: this.o.chargeGroupID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return GetStatementDateInput;
            })(starrez.library.service.AddInActionCallBase);
            accounts.GetStatementDateInput = GetStatementDateInput;
            var GetStatementReport = (function (_super) {
                __extends(GetStatementReport, _super);
                function GetStatementReport(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Accounts";
                    this.Controller = "accounts";
                    this.Action = "GetStatementReport";
                }
                GetStatementReport.prototype.CallData = function () {
                    var obj = {
                        chargeGroupID: this.o.chargeGroupID,
                        dateEnd: this.o.dateEnd,
                        dateStart: this.o.dateStart,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return GetStatementReport;
            })(starrez.library.service.AddInActionCallBase);
            accounts.GetStatementReport = GetStatementReport;
            var PayAll = (function (_super) {
                __extends(PayAll, _super);
                function PayAll(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Accounts";
                    this.Controller = "accounts";
                    this.Action = "PayAll";
                }
                PayAll.prototype.CallData = function () {
                    var obj = {
                        amount: this.o.amount,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return PayAll;
            })(starrez.library.service.AddInActionCallBase);
            accounts.PayAll = PayAll;
        })(accounts = service.accounts || (service.accounts = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var additionaloccupant;
        (function (additionaloccupant) {
            var management;
            (function (management) {
                "use strict";
                function InitialiseAdditionalOccupantList($container) {
                    new AdditionalOccupantListManager($container);
                }
                management.InitialiseAdditionalOccupantList = InitialiseAdditionalOccupantList;
                var AdditionalOccupantListManager = (function () {
                    function AdditionalOccupantListManager($container) {
                        var _this = this;
                        this.$container = $container;
                        this.model = starrez.model.AdditionalOccupantManagementModel($container);
                        this.$container.find(".ui-delete-occupant").SRClick(function (e) { return _this.DeleteOccupant(e); });
                        this.$container.find(".ui-view-occupant").SRClick(function (e) { return _this.ViewOccupant(e); });
                    }
                    AdditionalOccupantListManager.prototype.DeleteOccupant = function (e) {
                        var _this = this;
                        var $button = $(e.currentTarget);
                        var $actionPanel = $button.closest(".ui-action-panel");
                        var message = $button.data("deleteconfirmationtext").toString();
                        portal.ConfirmAction(message, this.model.DeleteOccupantConfirmationHeaderText).done(function () {
                            var hash = $button.data("hash").toString();
                            var bookingOccupantID = _this.GetBookingOccupantID($actionPanel);
                            new starrez.service.additionaloccupant.DeleteOccupant({
                                hash: hash,
                                pageID: portal.page.CurrentPage.PageID,
                                bookingOccupantID: bookingOccupantID
                            }).Post().done(function () {
                                location.reload();
                            });
                        });
                    };
                    AdditionalOccupantListManager.prototype.ViewOccupant = function (e) {
                        var $button = $(e.currentTarget);
                        var $actionPanel = $button.closest(".ui-action-panel");
                        var hash = $button.data("hash").toString();
                        var bookingOccupantID = this.GetBookingOccupantID($actionPanel);
                        new starrez.service.additionaloccupant.RedirectToDetailsPage({
                            hash: hash,
                            pageID: portal.page.CurrentPage.PageID,
                            bookingOccupantID: bookingOccupantID,
                            readOnly: !this.model.AllowEdit
                        }).Post().done(function (url) {
                            location.href = url;
                        });
                    };
                    AdditionalOccupantListManager.prototype.GetBookingOccupantID = function ($actionPanel) {
                        return Number($actionPanel.data("bookingoccupantid"));
                    };
                    return AdditionalOccupantListManager;
                })();
            })(management = additionaloccupant.management || (additionaloccupant.management = {}));
        })(additionaloccupant = general.additionaloccupant || (general.additionaloccupant = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function AdditionalOccupantManagementModel($sys) {
            return {
                AdditionalOccupantOption: $sys.data('additionaloccupantoption'),
                AllowEdit: starrez.library.convert.ToBoolean($sys.data('allowedit')),
                DeleteOccupantConfirmationHeaderText: $sys.data('deleteoccupantconfirmationheadertext')
            };
        }
        model.AdditionalOccupantManagementModel = AdditionalOccupantManagementModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var additionaloccupant;
        (function (additionaloccupant) {
            "use strict";
            var DeleteOccupant = (function (_super) {
                __extends(DeleteOccupant, _super);
                function DeleteOccupant(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "AdditionalOccupant";
                    this.Controller = "additionaloccupant";
                    this.Action = "DeleteOccupant";
                }
                DeleteOccupant.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                DeleteOccupant.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        bookingOccupantID: this.o.bookingOccupantID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return DeleteOccupant;
            })(starrez.library.service.AddInActionCallBase);
            additionaloccupant.DeleteOccupant = DeleteOccupant;
            var RedirectToDetailsPage = (function (_super) {
                __extends(RedirectToDetailsPage, _super);
                function RedirectToDetailsPage(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "AdditionalOccupant";
                    this.Controller = "additionaloccupant";
                    this.Action = "RedirectToDetailsPage";
                }
                RedirectToDetailsPage.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                RedirectToDetailsPage.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        bookingOccupantID: this.o.bookingOccupantID,
                        pageID: this.o.pageID,
                        readOnly: this.o.readOnly
                    };
                    return obj;
                };
                return RedirectToDetailsPage;
            })(starrez.library.service.AddInActionCallBase);
            additionaloccupant.RedirectToDetailsPage = RedirectToDetailsPage;
        })(additionaloccupant = service.additionaloccupant || (service.additionaloccupant = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var application;
        (function (application) {
            var termselector;
            (function (termselector) {
                "use strict";
                function Initialise($container) {
                    new TermSelector($container);
                }
                termselector.Initialise = Initialise;
                var TermSelector = (function () {
                    function TermSelector($container) {
                        this.$term = $container.GetControl('TermID');
                        this.$classification = $container.GetControl('ClassificationID');
                        this.$applyButton = $container.find('.ui-select-action');
                        this.AttachClickEvents($container);
                    }
                    TermSelector.prototype.AttachClickEvents = function ($container) {
                        var _this = this;
                        this.$applyButton.SRClick(function (e) {
                            var $self = $(e.currentTarget);
                            var termID = $self.closest('.ui-action-panel').data('termid');
                            var classificationID = $self.closest('.ui-action-panel').data('classificationid');
                            _this.ApplyForTerm(termID, classificationID);
                            starrez.library.utils.SafeStopPropagation(e);
                        });
                    };
                    TermSelector.prototype.ApplyForTerm = function (termID, classificationID) {
                        if (starrez.library.utils.IsNotNullUndefined(termID)) {
                            this.$term.SRVal(termID);
                        }
                        if (starrez.library.utils.IsNotNullUndefined(classificationID) && starrez.library.utils.IsNotNullUndefined(termID)) {
                            this.$classification.SRVal(classificationID);
                        }
                        portal.page.CurrentPage.SubmitPage();
                    };
                    return TermSelector;
                })();
            })(termselector = application.termselector || (application.termselector = {}));
        })(application = general.application || (general.application = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var applicationpreferences;
    (function (applicationpreferences) {
        "use strict";
        function InitApplicationPreferencesPage($container) {
            new ApplicationPreferencesModel($container);
        }
        applicationpreferences.InitApplicationPreferencesPage = InitApplicationPreferencesPage;
        var ApplicationPreferencesModel = (function () {
            function ApplicationPreferencesModel($container) {
                var _this = this;
                this.$container = $container;
                this.preferencesTable = starrez.tablesetup.CreateTableManager(this.$container.find(".ui-application-preferences-table table"), $('body'))[0];
                this.applicationPreferencesModel = starrez.model.ApplicationPreferencesModel($container);
                this.loadPreferencesErrorMessage = this.applicationPreferencesModel.LoadPreferencesErrorMessage;
                this.addButtonErrorMessage = this.applicationPreferencesModel.AddButtonErrorMessage;
                this.saveButtonErrorMessage = this.applicationPreferencesModel.SaveButtonErrorMessage;
                this.preferenceNotSelectedErrorMessage = this.applicationPreferencesModel.PreferenceNotSelectedErrorMessage;
                this.maximumNumberOfPreferences = this.applicationPreferencesModel.MaximumNumberOfPreferences;
                this.$tbody = this.preferencesTable.$table.find('tbody');
                this.$addButton = this.$container.find('.ui-add-application-preference');
                this.$saveButton = $('body').find('.ui-submit-page-content');
                this.$preferenceMessage = this.$container.find('.ui-preference-message');
                this.maximumNumberOfPreferencesOverallErrorMessage = this.applicationPreferencesModel.MaximumNumberOfPreferencesOverallErrorMessage;
                this.pageID = portal.page.CurrentPage.PageID;
                this.AttachDeleteEvents();
                this.AttachAddEvents();
                this.AttachRowEvents();
                this.isValid = true;
                portal.page.CurrentPage.FetchAdditionalData = function () { return _this.GetData(); };
                portal.page.CurrentPage.AddCustomValidation(this);
            }
            ApplicationPreferencesModel.prototype.AttachAddEvents = function () {
                var _this = this;
                this.$addButton.SRClick(function () {
                    _this.AddPreferenceRow();
                });
                if (this.maximumNumberOfPreferences <= this.preferencesTable.Rows().length) {
                    this.$addButton.Disable();
                }
            };
            ApplicationPreferencesModel.prototype.AttachDeleteEvents = function () {
                var _this = this;
                this.preferencesTable.$table.SRClickDelegate('delete', '.ui-btn-delete', function (e) {
                    var $deleteButton = $(e.currentTarget);
                    $deleteButton.closest('tr').remove();
                    _this.EnableAddandSave();
                    _this.UpdatePreferenceMessage();
                    _this.UpdateRowOrder();
                });
            };
            ApplicationPreferencesModel.prototype.AttachRowEvents = function () {
                var _this = this;
                this.preferencesTable.$table.SRClickDelegate('ok', '.ui-btn-ok', function (e) {
                    var $okButton = $(e.currentTarget);
                    var $preferenceDropDown = $okButton.closest('tr').GetControl('PreferenceDropdown');
                    var preferenceValue = $preferenceDropDown.SRVal();
                    if (preferenceValue === "0") {
                        alert(_this.preferenceNotSelectedErrorMessage);
                        return false;
                    }
                    var hash = _this.preferencesTable.$table.attr('displaypreferencehash').toString();
                    new starrez.service.applicationpreferences.DisplayPreferenceRow({
                        index: _this.preferencesTable.Rows().length,
                        pageID: _this.pageID,
                        preferenceID: Number(preferenceValue),
                        hash: hash
                    }).Post().done(function (results) {
                        if (starrez.library.utils.IsNotNullUndefined(results)) {
                            _this.preferencesTable.$table.find('tbody').append(results);
                            $okButton.closest('tr').remove();
                        }
                        else {
                            portal.page.CurrentPage.SetErrorMessage(_this.loadPreferencesErrorMessage);
                        }
                    });
                    _this.EnableAddandSave();
                });
                this.preferencesTable.$table.SRClickDelegate('cancel', '.ui-btn-cancel', function (e) {
                    var $cancelButton = $(e.currentTarget);
                    $cancelButton.closest('tr').remove();
                    _this.UpdatePreferenceMessage();
                    _this.EnableAddandSave();
                });
            };
            ApplicationPreferencesModel.prototype.EnableAddandSave = function () {
                this.$addButton.prop("title", "");
                this.$saveButton.prop("title", "");
                if (this.maximumNumberOfPreferences > this.preferencesTable.Rows().length) {
                    this.$addButton.Enable();
                }
                this.$saveButton.Enable();
                this.isValid = true;
            };
            ApplicationPreferencesModel.prototype.AddPreferenceRow = function () {
                var _this = this;
                var preferenceIDs = this.GetPreferenceIDs();
                var hash = this.preferencesTable.$table.attr('editpreferencehash').toString();
                new starrez.service.applicationpreferences.EditPreferenceOnlyRow({
                    index: this.preferencesTable.Rows().length,
                    preferenceIDs: preferenceIDs,
                    pageID: this.pageID,
                    hash: hash
                }).Post().done(function (results) {
                    if (starrez.library.utils.IsNotNullUndefined(results)) {
                        _this.AddPreferenceRowTable(results);
                    }
                    else {
                        portal.page.CurrentPage.SetErrorMessage(_this.loadPreferencesErrorMessage);
                    }
                });
                this.$addButton.prop("title", this.addButtonErrorMessage);
                this.$saveButton.prop("title", this.saveButtonErrorMessage);
                this.$addButton.Disable();
                this.$saveButton.Disable();
                this.isValid = false;
            };
            ApplicationPreferencesModel.prototype.AddPreferenceRowTable = function (results) {
                if (!results.IsPreferenceLimitReached) {
                    if (this.$tbody.isFound()) {
                        this.$tbody.append(results.PreferenceRow);
                    }
                    else {
                        this.preferencesTable.$table.append('<tbody></tbody>');
                        this.$tbody = this.preferencesTable.$table.find('tbody');
                        this.$tbody.append(results.PreferenceRow);
                    }
                    this.UpdateRowOrder();
                }
                if (this.maximumNumberOfPreferences <= this.preferencesTable.Rows().length) {
                    this.$preferenceMessage.find('div').text(this.maximumNumberOfPreferencesOverallErrorMessage);
                }
                else {
                    this.$preferenceMessage.html(results.DisplayNotificationMessage);
                }
            };
            ApplicationPreferencesModel.prototype.GetPreferenceIDs = function () {
                var $tableRows = this.$tbody.find('tr');
                var preferenceIDs = [];
                $tableRows.each(function (index, element) {
                    preferenceIDs.push(Number($(element).data('id')));
                });
                return preferenceIDs;
            };
            ApplicationPreferencesModel.prototype.UpdateRowOrder = function () {
                var $rowOrders = this.$tbody.find('.ui-order-column');
                var preferenceNumber = 1;
                $rowOrders.each(function (index, element) {
                    $(element).text(preferenceNumber);
                    preferenceNumber++;
                });
            };
            ApplicationPreferencesModel.prototype.UpdatePreferenceMessage = function () {
                var _this = this;
                new starrez.service.applicationpreferences.DeleteRowMessage({
                    numberOfPreferences: this.GetPreferenceIDs().length,
                    pageID: this.pageID
                }).Post().done(function (results) {
                    _this.$preferenceMessage.html(results);
                });
            };
            ApplicationPreferencesModel.prototype.Validate = function () {
                var deferred = $.Deferred();
                if (this.isValid) {
                    deferred.resolve();
                }
                else {
                    deferred.reject();
                }
                return deferred.promise();
            };
            ApplicationPreferencesModel.prototype.GetData = function () {
                var data = this.GetPreferenceIDs();
                return {
                    SelectedPreferences: data
                };
            };
            return ApplicationPreferencesModel;
        })();
    })(applicationpreferences = portal.applicationpreferences || (portal.applicationpreferences = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function ApplicationPreferencesModel($sys) {
            return {
                AddButtonErrorMessage: $sys.data('addbuttonerrormessage'),
                LoadPreferencesErrorMessage: $sys.data('loadpreferenceserrormessage'),
                MaximumNumberOfPreferences: Number($sys.data('maximumnumberofpreferences')),
                MaximumNumberOfPreferencesOverallErrorMessage: $sys.data('maximumnumberofpreferencesoverallerrormessage'),
                PreferenceItems: $sys.data('preferenceitems'),
                PreferenceNotSelectedErrorMessage: $sys.data('preferencenotselectederrormessage'),
                SaveButtonErrorMessage: $sys.data('savebuttonerrormessage')
            };
        }
        model.ApplicationPreferencesModel = ApplicationPreferencesModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var applicationpreferences;
        (function (applicationpreferences) {
            "use strict";
            var DeleteRowMessage = (function (_super) {
                __extends(DeleteRowMessage, _super);
                function DeleteRowMessage(o) {
                    _super.call(this);
                    this.o = o;
                    this.Area = "ApplicationPreferences";
                    this.Controller = "applicationpreferences";
                    this.Action = "DeleteRowMessage";
                }
                DeleteRowMessage.prototype.CallData = function () {
                    var obj = {
                        numberOfPreferences: this.o.numberOfPreferences,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return DeleteRowMessage;
            })(starrez.library.service.ActionCallBase);
            applicationpreferences.DeleteRowMessage = DeleteRowMessage;
            var DisplayPreferenceRow = (function (_super) {
                __extends(DisplayPreferenceRow, _super);
                function DisplayPreferenceRow(o) {
                    _super.call(this);
                    this.o = o;
                    this.Area = "ApplicationPreferences";
                    this.Controller = "applicationpreferences";
                    this.Action = "DisplayPreferenceRow";
                }
                DisplayPreferenceRow.prototype.CallData = function () {
                    var obj = {
                        index: this.o.index,
                        preferenceID: this.o.preferenceID
                    };
                    return obj;
                };
                DisplayPreferenceRow.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return DisplayPreferenceRow;
            })(starrez.library.service.ActionCallBase);
            applicationpreferences.DisplayPreferenceRow = DisplayPreferenceRow;
            var EditPreferenceOnlyRow = (function (_super) {
                __extends(EditPreferenceOnlyRow, _super);
                function EditPreferenceOnlyRow(o) {
                    _super.call(this);
                    this.o = o;
                    this.Area = "ApplicationPreferences";
                    this.Controller = "applicationpreferences";
                    this.Action = "EditPreferenceOnlyRow";
                }
                EditPreferenceOnlyRow.prototype.CallData = function () {
                    var obj = {
                        index: this.o.index,
                        preferenceIDs: this.o.preferenceIDs
                    };
                    return obj;
                };
                EditPreferenceOnlyRow.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return EditPreferenceOnlyRow;
            })(starrez.library.service.ActionCallBase);
            applicationpreferences.EditPreferenceOnlyRow = EditPreferenceOnlyRow;
        })(applicationpreferences = service.applicationpreferences || (service.applicationpreferences = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var appointments;
    (function (appointments) {
        "use strict";
        var hours = "hours";
        function Initialise($container) {
            new Appointments($container);
        }
        appointments.Initialise = Initialise;
        var Appointments = (function () {
            function Appointments($container) {
                this.$container = $container;
                this.model = starrez.model.AppointmentsModel($container);
                this.$calendar = $container.find(".ui-fullcalendar");
                this.$suggestions = $container.find(".ui-suggestions");
                this.$appointmentsList = $container.find(".ui-booked-appointments-list");
                this.$processDescription = $container.find(".ui-process-description");
                this.$currentProcessContainer = $container.find(".ui-current-process-container");
                this.$noAppointmentsNotification = $container.find(".ui-no-appointments-notification");
                this.$jumpToDate = this.$container.GetControl("appointments-jumptodate");
                this.$calendarViewDropdown = this.$container.GetControl("DefaultView");
                this.$processList = $container.GetControl("appointment-process-id");
                if (this.$processList.isFound()) {
                    this.selectedProcessID = this.$processList.SRVal();
                }
                else {
                    this.selectedProcessID = $container.GetControl("appointment-process-id").SRVal();
                }
                this.InitialiseButtonEvents();
                this.InitialiseTableEvents();
                this.InitialiseProcessChangeEvent(this.$processList);
                this.InitialiseFullCalendar(this.$calendar);
            }
            Appointments.prototype.InitialiseFullCalendar = function ($calendar) {
                var _this = this;
                var initial = moment(this.model.InitialDate);
                var baseUrl = portal.StartupOptions.BaseUrl;
                if (baseUrl === "/") {
                    //The browser can handle it perfectly well if the baseUrl is empty. Adding slash here will actually cause problems.
                    //The change is done here instead of in StartupOptions.cs to avoid any unknown implications
                    baseUrl = "";
                }
                $calendar.fullCalendar({
                    header: {
                        left: "",
                        center: "",
                        right: ""
                    },
                    buttonText: {
                        today: this.model.TodayButtonText,
                        month: this.model.MonthButtonText,
                        week: this.model.WeekButtonText,
                        day: this.model.DayButtonText
                    },
                    timeFormat: "h(:mm)a",
                    columnFormat: {
                        week: this.model.WeekViewDateFormat,
                        day: this.model.DayViewDateFormat
                    },
                    events: {
                        url: baseUrl +
                            new starrez.service.appointments.GetTimeslots({
                                start: new Date(),
                                end: new Date(),
                                portalPageID: portal.page.CurrentPage.PageID,
                                appointmentProcessID: this.selectedProcessID
                            }).GetURL(),
                        type: "POST",
                        data: function () {
                            return {
                                portalPageID: portal.page.CurrentPage.PageID,
                                appointmentProcessID: _this.selectedProcessID
                            };
                        }
                    },
                    firstDay: this.model.FirstDayOfWeek,
                    defaultDate: initial,
                    minTime: moment.duration(this.model.MinHour, hours),
                    maxTime: moment.duration(this.model.MaxHour, hours),
                    defaultView: this.model.DefaultView,
                    timezone: false,
                    theme: false,
                    allDayDefault: false,
                    allDaySlot: false,
                    views: {
                        agenda: {
                            timeFormat: "h:mma" // Agenda view - 5:00 pm - 6:30 pm
                        }
                    },
                    viewRender: function (view) {
                        // when we update the calendar, keep the date picker synced up
                        if (starrez.library.utils.IsNotNullUndefined(_this.$jumpToDate) && _this.$jumpToDate.isFound()) {
                            _this.updatingCalendar = true;
                            var momentDate = _this.$calendar.fullCalendar("getDate").toDate();
                            var dateWithoutTimezone = new Date(momentDate.getUTCFullYear(), momentDate.getUTCMonth(), momentDate.getUTCDate());
                            _this.$jumpToDate.SRVal(dateWithoutTimezone);
                        }
                    },
                    eventClick: function (slot, e) {
                        starrez.library.utils.SafeStopPropagation(e);
                        var start = moment(new Date(slot.start.year(), slot.start.month(), slot.start.date(), slot.start.hours(), slot.start.minutes()));
                        var end = moment(new Date(slot.end.year(), slot.end.month(), slot.end.date(), slot.end.hours(), slot.end.minutes()));
                        if (starrez.library.convert.ToBoolean(slot["booked"]) || start <= moment()) {
                            return;
                        }
                        portal.ConfirmAction(slot["description"] + _this.model.BookConfirmationMessage, "Book Appointment")
                            .done(function () {
                            var call = new starrez.service.appointments.BookTimeslot({
                                startDate: start.toDate(),
                                endDate: end.toDate(),
                                portalPageID: portal.page.CurrentPage.PageID,
                                appointmentProcessID: _this.selectedProcessID,
                                hash: slot["bookurlhash"]
                            });
                            call.Request({
                                ActionVerb: starrez.library.service.RequestType.Post,
                                RejectOnFail: true
                            }).done(function (data) {
                                portal.page.CurrentPage.SetSuccessMessage(data);
                                _this.RefetchBookedAppointments();
                                if (_this.model.ShowSuggestions) {
                                    _this.ShowSuggestions();
                                }
                            }).always(function () {
                                $calendar.fullCalendar("refetchEvents");
                            });
                        }).fail(function () {
                            $(e.target).focus();
                        });
                    }
                });
            };
            Appointments.prototype.InitialiseButtonEvents = function () {
                var _this = this;
                // when the date picker is updated
                this.$jumpToDate.on("change", function (e) {
                    if (_this.updatingCalendar) {
                        _this.updatingCalendar = false;
                    }
                    else {
                        var date = $(e.currentTarget).SRVal();
                        var gotoDate = moment(date);
                        _this.$calendar.fullCalendar("gotoDate", gotoDate);
                    }
                });
                // when the calendar view dropdown is changed
                this.$calendarViewDropdown.on("change", function () {
                    _this.$calendar.fullCalendar("changeView", _this.$calendarViewDropdown.SRVal());
                });
                // when one of the calendar nav buttons is clicked
                this.$container.find(".ui-calendar-action").SRClick(function (e) {
                    var $button = $(e.currentTarget);
                    var action = $button.data("action").toString();
                    _this.$calendar.fullCalendar(action);
                });
            };
            Appointments.prototype.InitialiseTableEvents = function () {
                var _this = this;
                this.$appointmentsList.on("click", ".ui-cancel-appointment", function (e) {
                    var timeslotID = Number($(e.target).closest("tr").data("timeslot"));
                    portal.ConfirmAction(_this.model.CancelConfirmationMessage, "Cancel Appointment").done(function () {
                        var call = new starrez.service.appointments.CancelTimeslot({
                            timeSlotID: timeslotID,
                            portalPageID: portal.page.CurrentPage.PageID
                        });
                        call.Post().done(function (data) {
                            portal.page.CurrentPage.SetSuccessMessage(data);
                            _this.RefetchBookedAppointments();
                            _this.$calendar.fullCalendar("refetchEvents");
                        });
                    });
                });
            };
            Appointments.prototype.InitialiseProcessChangeEvent = function ($processList) {
                var _this = this;
                $processList.change(function (e) {
                    _this.selectedProcessID = $processList.SRVal();
                    _this.RefetchProcessDescription();
                    new starrez.service.appointments.GetProcessInitialDate({
                        appointmentProcessID: _this.selectedProcessID
                    }).Post().done(function (date) {
                        if (!starrez.library.stringhelper.IsUndefinedOrEmpty(date)) {
                            _this.$currentProcessContainer.show();
                            _this.$noAppointmentsNotification.hide();
                            var gotoDate = moment(date);
                            _this.$calendar.fullCalendar("gotoDate", gotoDate);
                            _this.$calendar.fullCalendar("refetchEvents");
                        }
                        else {
                            _this.$currentProcessContainer.hide();
                            _this.$noAppointmentsNotification.show();
                        }
                    });
                });
            };
            Appointments.prototype.RefetchProcessDescription = function () {
                var _this = this;
                new starrez.service.appointments.GetProcessDescription({
                    portalPageID: portal.page.CurrentPage.PageID,
                    appointmentProcessID: this.selectedProcessID
                }).Post().done(function (data) {
                    _this.$processDescription.html(data);
                });
            };
            Appointments.prototype.RefetchBookedAppointments = function () {
                var _this = this;
                new starrez.service.appointments.GetBookedAppointments({
                    portalPageID: portal.page.CurrentPage.PageID,
                    appointmentProcessIDs: starrez.library.convert.ToNumberArray(this.model.AppointmentProcessIDs)
                }).Post().done(function (data) {
                    _this.$appointmentsList.html(data);
                });
            };
            Appointments.prototype.ShowSuggestions = function () {
                var _this = this;
                new starrez.service.appointments.GetSuggestions({
                    pageID: portal.page.CurrentPage.PageID,
                    roomLocationIDs: this.model.RoomLocationIDs
                }).Post().done(function (html) {
                    _this.$suggestions.html(html);
                });
            };
            return Appointments;
        })();
    })(appointments = portal.appointments || (portal.appointments = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function AppointmentsModel($sys) {
            return {
                AppointmentProcessIDs: $sys.data('appointmentprocessids'),
                AvailableViews: ($sys.data('availableviews') === '') ? [] : ($sys.data('availableviews')).toString().split(','),
                BookConfirmationMessage: $sys.data('bookconfirmationmessage'),
                CancelConfirmationMessage: $sys.data('cancelconfirmationmessage'),
                DayButtonText: $sys.data('daybuttontext'),
                DayViewDateFormat: $sys.data('dayviewdateformat'),
                DefaultView: $sys.data('defaultview'),
                FirstDayOfWeek: Number($sys.data('firstdayofweek')),
                InitialDate: moment($sys.data('initialdate')).toDate(),
                MaxHour: Number($sys.data('maxhour')),
                MinHour: Number($sys.data('minhour')),
                MonthButtonText: $sys.data('monthbuttontext'),
                RoomLocationIDs: ($sys.data('roomlocationids') === '') ? [] : ($sys.data('roomlocationids')).toString().split(',').map(function (e) { return Number(e); }),
                ShowSuggestions: starrez.library.convert.ToBoolean($sys.data('showsuggestions')),
                TodayButtonText: $sys.data('todaybuttontext'),
                WeekButtonText: $sys.data('weekbuttontext'),
                WeekViewDateFormat: $sys.data('weekviewdateformat')
            };
        }
        model.AppointmentsModel = AppointmentsModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var appointments;
        (function (appointments) {
            "use strict";
            var BookTimeslot = (function (_super) {
                __extends(BookTimeslot, _super);
                function BookTimeslot(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Appointments";
                    this.Controller = "appointments";
                    this.Action = "BookTimeslot";
                }
                BookTimeslot.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                BookTimeslot.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        appointmentProcessID: this.o.appointmentProcessID,
                        endDate: this.o.endDate,
                        portalPageID: this.o.portalPageID,
                        startDate: this.o.startDate
                    };
                    return obj;
                };
                return BookTimeslot;
            })(starrez.library.service.AddInActionCallBase);
            appointments.BookTimeslot = BookTimeslot;
            var CancelTimeslot = (function (_super) {
                __extends(CancelTimeslot, _super);
                function CancelTimeslot(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Appointments";
                    this.Controller = "appointments";
                    this.Action = "CancelTimeslot";
                }
                CancelTimeslot.prototype.CallData = function () {
                    var obj = {
                        portalPageID: this.o.portalPageID,
                        timeSlotID: this.o.timeSlotID
                    };
                    return obj;
                };
                return CancelTimeslot;
            })(starrez.library.service.AddInActionCallBase);
            appointments.CancelTimeslot = CancelTimeslot;
            var GetBookedAppointments = (function (_super) {
                __extends(GetBookedAppointments, _super);
                function GetBookedAppointments(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Appointments";
                    this.Controller = "appointments";
                    this.Action = "GetBookedAppointments";
                }
                GetBookedAppointments.prototype.CallData = function () {
                    var obj = {
                        appointmentProcessIDs: this.o.appointmentProcessIDs,
                        portalPageID: this.o.portalPageID
                    };
                    return obj;
                };
                return GetBookedAppointments;
            })(starrez.library.service.AddInActionCallBase);
            appointments.GetBookedAppointments = GetBookedAppointments;
            var GetProcessDescription = (function (_super) {
                __extends(GetProcessDescription, _super);
                function GetProcessDescription(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Appointments";
                    this.Controller = "appointments";
                    this.Action = "GetProcessDescription";
                }
                GetProcessDescription.prototype.CallData = function () {
                    var obj = {
                        appointmentProcessID: this.o.appointmentProcessID,
                        portalPageID: this.o.portalPageID
                    };
                    return obj;
                };
                return GetProcessDescription;
            })(starrez.library.service.AddInActionCallBase);
            appointments.GetProcessDescription = GetProcessDescription;
            var GetProcessInitialDate = (function (_super) {
                __extends(GetProcessInitialDate, _super);
                function GetProcessInitialDate(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Appointments";
                    this.Controller = "appointments";
                    this.Action = "GetProcessInitialDate";
                }
                GetProcessInitialDate.prototype.CallData = function () {
                    var obj = {
                        appointmentProcessID: this.o.appointmentProcessID
                    };
                    return obj;
                };
                return GetProcessInitialDate;
            })(starrez.library.service.AddInActionCallBase);
            appointments.GetProcessInitialDate = GetProcessInitialDate;
            var GetSuggestions = (function (_super) {
                __extends(GetSuggestions, _super);
                function GetSuggestions(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Appointments";
                    this.Controller = "appointments";
                    this.Action = "GetSuggestions";
                }
                GetSuggestions.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID,
                        roomLocationIDs: this.o.roomLocationIDs
                    };
                    return obj;
                };
                return GetSuggestions;
            })(starrez.library.service.AddInActionCallBase);
            appointments.GetSuggestions = GetSuggestions;
            var GetTimeslots = (function (_super) {
                __extends(GetTimeslots, _super);
                function GetTimeslots(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Appointments";
                    this.Controller = "appointments";
                    this.Action = "GetTimeslots";
                }
                GetTimeslots.prototype.CallData = function () {
                    var obj = {
                        appointmentProcessID: this.o.appointmentProcessID,
                        end: this.o.end,
                        portalPageID: this.o.portalPageID,
                        start: this.o.start
                    };
                    return obj;
                };
                return GetTimeslots;
            })(starrez.library.service.AddInActionCallBase);
            appointments.GetTimeslots = GetTimeslots;
        })(appointments = service.appointments || (service.appointments = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var booking;
    (function (booking) {
        "use strict";
        function Initialise($container) {
            new Booking($container);
        }
        booking.Initialise = Initialise;
        var Booking = (function () {
            function Booking($container) {
                this.$container = $container;
                this.$resultContainer = $container.find(".ui-group-selector-result");
                this.$groupCodeButton = $container.find(".ui-enter-group-code");
                this.$groupCodeText = this.$container.GetControl("GroupCode");
                this.AttachEvent();
                //Reload the result for the first time
                this.$groupCodeButton.click();
            }
            Booking.prototype.AttachEvent = function () {
                var _this = this;
                this.$groupCodeButton.SRClick(function (e) {
                    new starrez.service.booking.GetGroups({
                        portalPageID: portal.page.CurrentPage.PageID,
                        groupCode: _this.$groupCodeText.SRVal()
                    }).Get().done(function (data) {
                        _this.$resultContainer.html(data);
                    });
                });
                this.$groupCodeText.keydown(function (e) {
                    if (e.keyCode === starrez.keyboard.EnterCode) {
                        // The browsers have a behaviour where they will automatically submit the form if there is only one
                        // input field on it. This is not what we want to do, so call SafeStopPropagation to block this from happening.
                        // http://stackoverflow.com/questions/1370021/why-does-forms-with-single-input-field-submit-upon-pressing-enter-key-in-input
                        starrez.library.utils.SafeStopPropagation(e);
                        _this.$groupCodeButton.click();
                    }
                });
            };
            return Booking;
        })();
    })(booking = portal.booking || (portal.booking = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var booking;
        (function (booking) {
            "use strict";
            var GetGroups = (function (_super) {
                __extends(GetGroups, _super);
                function GetGroups(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Booking";
                    this.Controller = "booking";
                    this.Action = "GetGroups";
                }
                GetGroups.prototype.CallData = function () {
                    var obj = {
                        groupCode: this.o.groupCode,
                        portalPageID: this.o.portalPageID
                    };
                    return obj;
                };
                return GetGroups;
            })(starrez.library.service.AddInActionCallBase);
            booking.GetGroups = GetGroups;
        })(booking = service.booking || (service.booking = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var bookingroommateprofiles;
        (function (bookingroommateprofiles) {
            "use strict";
            function Initialise($container) {
                bookingroommateprofiles.Model = new BookingRoommateProfiles($container);
            }
            bookingroommateprofiles.Initialise = Initialise;
            var BookingRoommateProfiles = (function () {
                function BookingRoommateProfiles($container) {
                    this.$container = $container;
                    var $headerContainer = this.$container.find(".ui-booking-roommate-profile-type-container");
                    $headerContainer.SRClick(function (e) {
                        var $header = $(e.currentTarget);
                        var $matchContainer = $header.closest(".ui-booking-roommate-profile-container");
                        var expanded = false;
                        if ($matchContainer.hasClass("collapsed")) {
                            expanded = true;
                        }
                        var $toggleIcon = $header.find(".ui-profile-toggle");
                        var $profileItemsContainer = $matchContainer.find(".ui-booking-roommate-profile-items-container");
                        if (expanded) {
                            $toggleIcon.removeClass("fa-caret-right").addClass("fa-caret-down");
                            $profileItemsContainer.css("maxHeight", $profileItemsContainer[0].scrollHeight + "px");
                            $header.attr("aria-expanded", "true");
                        }
                        else {
                            $toggleIcon.removeClass("fa-caret-down").addClass("fa-caret-right");
                            $profileItemsContainer.css("maxHeight", "");
                            $header.attr("aria-expanded", "false");
                        }
                        $matchContainer.toggleClass("collapsed");
                    });
                    $headerContainer.on("keyup", function (e) {
                        if (e.keyCode === starrez.keyboard.EnterCode || e.keyCode === starrez.keyboard.SpaceCode) {
                            $(e.currentTarget).trigger("click");
                        }
                    });
                }
                return BookingRoommateProfiles;
            })();
        })(bookingroommateprofiles = general.bookingroommateprofiles || (general.bookingroommateprofiles = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var starrez;
(function (starrez) {
    var bpointregistration;
    (function (bpointregistration) {
        "use strict";
        function InitialiseRegistrationPage($container) {
            new RegistrationPage($container);
        }
        bpointregistration.InitialiseRegistrationPage = InitialiseRegistrationPage;
        var RegistrationPage = (function () {
            function RegistrationPage($container) {
                this.$container = $container;
                this.$createButton = $container.find(".ui-create");
                this.$updateButton = $container.find(".ui-update");
                this.$deleteButton = $container.find(".ui-delete");
                this.AttachButtonEvents();
            }
            RegistrationPage.prototype.AttachButtonEvents = function () {
                var _this = this;
                this.$createButton.SRClick(function () {
                    _this.CreateUpdateToken();
                });
                this.$updateButton.SRClick(function () {
                    _this.CreateUpdateToken();
                });
                this.$deleteButton.SRClick(function () {
                    _this.DeleteToken();
                });
            };
            RegistrationPage.prototype.CreateUpdateToken = function () {
                var call = new starrez.service.bpointregistration.Create({
                    pageID: portal.page.CurrentPage.PageID,
                    processID: portal.page.CurrentPage.ProcessID
                });
                var url = starrez.library.service.CreateUrl(call.GetURLWithParameters());
                if (window.parent) {
                    parent.location.href = url;
                }
                else {
                    location.href = url;
                }
            };
            RegistrationPage.prototype.DeleteToken = function () {
                var call = new starrez.service.bpointregistration.Delete({
                    pageID: portal.page.CurrentPage.PageID,
                    processID: portal.page.CurrentPage.ProcessID
                });
                var url = starrez.library.service.CreateUrl(call.GetURLWithParameters());
                if (window.parent) {
                    parent.location.href = url;
                }
                else {
                    location.href = url;
                }
            };
            return RegistrationPage;
        })();
    })(bpointregistration = starrez.bpointregistration || (starrez.bpointregistration = {}));
})(starrez || (starrez = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var bpointregistration;
        (function (bpointregistration) {
            "use strict";
            var Create = (function (_super) {
                __extends(Create, _super);
                function Create(o) {
                    _super.call(this);
                    this.o = o;
                    this.Area = "BPOINTRegistration";
                    this.Controller = "bpointregistration";
                    this.Action = "Create";
                }
                Create.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID,
                        processID: this.o.processID
                    };
                    return obj;
                };
                return Create;
            })(starrez.library.service.ActionCallBase);
            bpointregistration.Create = Create;
            var Delete = (function (_super) {
                __extends(Delete, _super);
                function Delete(o) {
                    _super.call(this);
                    this.o = o;
                    this.Area = "BPOINTRegistration";
                    this.Controller = "bpointregistration";
                    this.Action = "Delete";
                }
                Delete.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID,
                        processID: this.o.processID
                    };
                    return obj;
                };
                return Delete;
            })(starrez.library.service.ActionCallBase);
            bpointregistration.Delete = Delete;
        })(bpointregistration = service.bpointregistration || (service.bpointregistration = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var starrez;
(function (starrez) {
    var bpointv3registration;
    (function (bpointv3registration) {
        "use strict";
        function InitialiseRegistrationPage($container) {
            new RegistrationPage($container);
        }
        bpointv3registration.InitialiseRegistrationPage = InitialiseRegistrationPage;
        var RegistrationPage = (function () {
            function RegistrationPage($container) {
                this.$container = $container;
                this.$createButton = $container.find(".ui-create");
                this.$updateButton = $container.find(".ui-update");
                this.$deleteButton = $container.find(".ui-delete");
                this.AttachButtonEvents();
            }
            RegistrationPage.prototype.AttachButtonEvents = function () {
                var _this = this;
                this.$createButton.SRClick(function () {
                    _this.CreateUpdateToken();
                });
                this.$updateButton.SRClick(function () {
                    _this.CreateUpdateToken();
                });
                this.$deleteButton.SRClick(function () {
                    _this.DeleteToken();
                });
            };
            RegistrationPage.prototype.CreateUpdateToken = function () {
                var call = new starrez.service.bpointv3registration.Create({
                    pageID: portal.page.CurrentPage.PageID,
                    processID: portal.page.CurrentPage.ProcessID
                });
                var url = starrez.library.service.CreateUrl(call.GetURLWithParameters());
                if (window.parent) {
                    parent.location.href = url;
                }
                else {
                    location.href = url;
                }
            };
            RegistrationPage.prototype.DeleteToken = function () {
                var call = new starrez.service.bpointv3registration.Delete({
                    pageID: portal.page.CurrentPage.PageID,
                    processID: portal.page.CurrentPage.ProcessID
                });
                var url = starrez.library.service.CreateUrl(call.GetURLWithParameters());
                if (window.parent) {
                    parent.location.href = url;
                }
                else {
                    location.href = url;
                }
            };
            return RegistrationPage;
        })();
    })(bpointv3registration = starrez.bpointv3registration || (starrez.bpointv3registration = {}));
})(starrez || (starrez = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var bpointv3registration;
        (function (bpointv3registration) {
            "use strict";
            var Create = (function (_super) {
                __extends(Create, _super);
                function Create(o) {
                    _super.call(this);
                    this.o = o;
                    this.Area = "BPOINTv3Registration";
                    this.Controller = "bpointv3registration";
                    this.Action = "Create";
                }
                Create.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID,
                        processID: this.o.processID
                    };
                    return obj;
                };
                return Create;
            })(starrez.library.service.ActionCallBase);
            bpointv3registration.Create = Create;
            var Delete = (function (_super) {
                __extends(Delete, _super);
                function Delete(o) {
                    _super.call(this);
                    this.o = o;
                    this.Area = "BPOINTv3Registration";
                    this.Controller = "bpointv3registration";
                    this.Action = "Delete";
                }
                Delete.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID,
                        processID: this.o.processID
                    };
                    return obj;
                };
                return Delete;
            })(starrez.library.service.ActionCallBase);
            bpointv3registration.Delete = Delete;
        })(bpointv3registration = service.bpointv3registration || (service.bpointv3registration = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var common;
        (function (common) {
            var signature;
            (function (signature) {
                "use strict";
                function InitSettings($container) {
                    var $mode = $container.GetControl('Mode');
                    var $matchText = $container.GetControl('MatchText');
                    var $matchFailedMessage = $container.GetControl('MatchFailedMessage');
                    var toggle = function (e) {
                        if (Number($mode.SRVal()) === SignatureMode.MatchText) {
                            // Show the match fields
                            $matchText.closest('li').show();
                            $matchFailedMessage.closest('li').show();
                        }
                        else {
                            // Hide the match fields
                            $matchText.closest('li').hide();
                            $matchFailedMessage.closest('li').hide();
                        }
                        starrez.popup.AutoHeightPopup($container);
                    };
                    $mode.change(function (e) { toggle(e); });
                    toggle($mode);
                }
                signature.InitSettings = InitSettings;
                var SignatureMode;
                (function (SignatureMode) {
                    SignatureMode[SignatureMode["Checkbox"] = 0] = "Checkbox";
                    SignatureMode[SignatureMode["FreeText"] = 1] = "FreeText";
                    SignatureMode[SignatureMode["MatchText"] = 2] = "MatchText";
                })(SignatureMode || (SignatureMode = {}));
            })(signature = common.signature || (common.signature = {}));
        })(common = general.common || (general.common = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var concerns;
        (function (concerns) {
            "use strict";
            function InitConcerns($container) {
                new ConcernsManager($container);
            }
            concerns.InitConcerns = InitConcerns;
            var ConcernsManager = (function () {
                function ConcernsManager($container) {
                    var _this = this;
                    this.$container = $container;
                    this.$container.find(".ui-add-participant").SRClick(function (e) { return _this.AddParticipant(e); });
                    this.$container.find(".ui-remove-participant").SRClick(function (e) { return _this.RemoveParticipant(e); });
                    if (window.location.hash.indexOf("ParticipantModified") != -1) {
                        $.ScrollToWithAnimation(".ui-participants");
                    }
                }
                ConcernsManager.prototype.AddParticipant = function (e) {
                    portal.page.CurrentPage.FetchAdditionalData = function () {
                        return { AddParticipantAfterCreation: true };
                    };
                    portal.page.CurrentPage.SubmitPage();
                };
                ConcernsManager.prototype.RemoveParticipant = function (e) {
                    var $button = $(e.currentTarget);
                    portal.ConfirmAction($button.data("confirmmessage").toString(), "Remove Participant").done(function () {
                        new starrez.service.concerns.RemoveParticipant({
                            participantID: Number($button.data("participantid")),
                            hash: $button.data("hash").toString()
                        }).Post().done(function () {
                            $button.closest(".ui-action-panel").remove();
                        });
                    });
                };
                return ConcernsManager;
            })();
        })(concerns = general.concerns || (general.concerns = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var concerns;
        (function (concerns) {
            "use strict";
            var RemoveParticipant = (function (_super) {
                __extends(RemoveParticipant, _super);
                function RemoveParticipant(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Concerns";
                    this.Controller = "concerns";
                    this.Action = "RemoveParticipant";
                }
                RemoveParticipant.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                RemoveParticipant.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        participantID: this.o.participantID
                    };
                    return obj;
                };
                return RemoveParticipant;
            })(starrez.library.service.AddInActionCallBase);
            concerns.RemoveParticipant = RemoveParticipant;
        })(concerns = service.concerns || (service.concerns = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var contentblock;
        (function (contentblock) {
            "use strict";
            function InitContentBlockEditor($container) {
                new ContentBlockSettingEditorModel($container);
            }
            contentblock.InitContentBlockEditor = InitContentBlockEditor;
            var ContentBlockSettingEditorModel = (function () {
                function ContentBlockSettingEditorModel($container) {
                    this.$container = $container;
                    this.attachEvents();
                    this.model = starrez.model.WidgetModelBaseModel($container);
                }
                ContentBlockSettingEditorModel.prototype.attachEvents = function () {
                    var _this = this;
                    this.$container.find(".ui-delete-contentblockitem").each(function (index, elem) {
                        var $deletebutton = $(elem);
                        $deletebutton.SRClick(function () {
                            portal.ConfirmAction("Are you sure you want to delete this content item?", "Delete Content Item").done(function () {
                                var call = new starrez.service.contentblock.DeleteContentItem({
                                    portalPageWidgetID: _this.model.PortalPageWidgetID,
                                    portalSettingID: $deletebutton.data('portalsettingid')
                                });
                                call.Post().done(function (result) {
                                    var itemToReplace = _this.$container.find('.ui-content-item-list-editor');
                                    itemToReplace.html(result);
                                    _this.attachEvents();
                                });
                            });
                        });
                    });
                    // Becuase individual content items are saved to the database within the sub popup screen, we still need
                    // to reload the view even if the main popup is closed as there may be changes.
                    portal.editor.widget.OnWidgetSettingsClose = function () {
                        location.reload();
                    };
                    this.$container.find(".ui-add-contentblockitem").SRClick(function () {
                        var getEditViewcall = new starrez.service.contentblock.GetEditItemView({
                            portalPageWidgetID: _this.model.PortalPageWidgetID,
                            portalSettingID: null
                        });
                        portal.OpenSRWActionInDialog(getEditViewcall, function (popup) {
                            var uploadedImageID;
                            var $uploadContainer = portal.fileuploader.control.GetUploadContainer(popup.$container);
                            $uploadContainer.on("change", function (e, changeEvent) {
                                // We use MoreInformation to pass the new imageID to the typescript.
                                // In portal.fileuploader.control, it will trigger the change event with the MoreEvent populated. This gives
                                // us access to the MoreInformation property were the ImageID has been populated.
                                // We also need to check changeEvent is not null becuase sometimes this will get triggered outide of the call from
                                // portal.fileuploader.control. In which case we need to ignore it.
                                if (starrez.library.utils.IsNotNullUndefined(changeEvent)) {
                                    uploadedImageID = changeEvent.MoreInformation;
                                }
                            });
                            popup.$footer.find(".ui-btn-save").SRClick(function () {
                                var call = new starrez.service.contentblock.AddContentBlockItem({
                                    portalPageWidgetID: _this.model.PortalPageWidgetID,
                                    title: popup.$container.GetControl("Title").SRVal(),
                                    content: popup.$container.GetControl("Content").SRVal(),
                                    newImageID: uploadedImageID
                                });
                                call.Post().done(function () {
                                    starrez.popup.Close(popup.$container);
                                    _this.RefreshItemList();
                                });
                            });
                        });
                    });
                    this.$container.find(".ui-edit-contentblockitem").each(function (index, elem) {
                        var $editbutton = $(elem);
                        $editbutton.SRClick(function () {
                            var portalSettingID = $editbutton.data('portalsettingid');
                            var existingImageID = $editbutton.data('imageid');
                            // newImageID is the Image to save. This might be
                            // If the image is unchanged it will remain as the default of existingImageID
                            // If a new image is uploaded it will get set to the newly uploaded imageID
                            // If the image is deleted it will be set to null
                            var newImageID = existingImageID;
                            var getEditViewcall = new starrez.service.contentblock.GetEditItemView({
                                portalPageWidgetID: _this.model.PortalPageWidgetID,
                                portalSettingID: portalSettingID
                            });
                            portal.OpenSRWActionInDialog(getEditViewcall, function (popup) {
                                var $uploadContainer = portal.fileuploader.control.GetUploadContainer(popup.$container);
                                $uploadContainer.on("change", function (e, changeEvent) {
                                    // We use MoreInformation to pass the new imageID to the typescript.
                                    newImageID = changeEvent.MoreInformation;
                                });
                                // when the save button is clicked update the database and refresh the item list
                                popup.$footer.find(".ui-btn-save").SRClick(function () {
                                    var saveStatus = portal.fileuploader.control.GetSaveStatus(popup.$container);
                                    if (saveStatus.Delete) {
                                        newImageID = null;
                                    }
                                    var editContentBlockCall = new starrez.service.contentblock.EditContentBlockItem({
                                        title: popup.$container.GetControl("Title").SRVal(),
                                        content: popup.$container.GetControl("Content").SRVal(),
                                        portalSettingID: portalSettingID,
                                        portalPageWidgetID: _this.model.PortalPageWidgetID,
                                        existingImageID: existingImageID,
                                        newImageID: newImageID
                                    });
                                    editContentBlockCall.Post().done(function () {
                                        starrez.popup.Close(popup.$container);
                                        _this.RefreshItemList();
                                    });
                                });
                            });
                        });
                    });
                };
                ContentBlockSettingEditorModel.prototype.RefreshItemList = function () {
                    var _this = this;
                    var call = new starrez.service.contentblock.GetContentItemList({
                        portalPageWidgetID: this.model.PortalPageWidgetID
                    });
                    call.Post().done(function (result) {
                        var itemToReplace = _this.$container.find('.ui-content-item-list-editor');
                        itemToReplace.html(result);
                        _this.attachEvents();
                    });
                };
                return ContentBlockSettingEditorModel;
            })();
        })(contentblock = general.contentblock || (general.contentblock = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function UploadedImageModel($sys) {
            return {};
        }
        model.UploadedImageModel = UploadedImageModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var contentblock;
        (function (contentblock) {
            "use strict";
            var AddContentBlockItem = (function (_super) {
                __extends(AddContentBlockItem, _super);
                function AddContentBlockItem(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "ContentBlock";
                    this.Controller = "contentblock";
                    this.Action = "AddContentBlockItem";
                }
                AddContentBlockItem.prototype.CallData = function () {
                    var obj = {
                        content: this.o.content,
                        newImageID: this.o.newImageID,
                        portalPageWidgetID: this.o.portalPageWidgetID,
                        title: this.o.title
                    };
                    return obj;
                };
                return AddContentBlockItem;
            })(starrez.library.service.AddInActionCallBase);
            contentblock.AddContentBlockItem = AddContentBlockItem;
            var DeleteContentItem = (function (_super) {
                __extends(DeleteContentItem, _super);
                function DeleteContentItem(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "ContentBlock";
                    this.Controller = "contentblock";
                    this.Action = "DeleteContentItem";
                }
                DeleteContentItem.prototype.CallData = function () {
                    var obj = {
                        portalPageWidgetID: this.o.portalPageWidgetID,
                        portalSettingID: this.o.portalSettingID
                    };
                    return obj;
                };
                return DeleteContentItem;
            })(starrez.library.service.AddInActionCallBase);
            contentblock.DeleteContentItem = DeleteContentItem;
            var EditContentBlockItem = (function (_super) {
                __extends(EditContentBlockItem, _super);
                function EditContentBlockItem(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "ContentBlock";
                    this.Controller = "contentblock";
                    this.Action = "EditContentBlockItem";
                }
                EditContentBlockItem.prototype.CallData = function () {
                    var obj = {
                        content: this.o.content,
                        existingImageID: this.o.existingImageID,
                        newImageID: this.o.newImageID,
                        portalPageWidgetID: this.o.portalPageWidgetID,
                        portalSettingID: this.o.portalSettingID,
                        title: this.o.title
                    };
                    return obj;
                };
                return EditContentBlockItem;
            })(starrez.library.service.AddInActionCallBase);
            contentblock.EditContentBlockItem = EditContentBlockItem;
            var GetContentItemList = (function (_super) {
                __extends(GetContentItemList, _super);
                function GetContentItemList(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "ContentBlock";
                    this.Controller = "contentblock";
                    this.Action = "GetContentItemList";
                }
                GetContentItemList.prototype.CallData = function () {
                    var obj = {
                        portalPageWidgetID: this.o.portalPageWidgetID
                    };
                    return obj;
                };
                return GetContentItemList;
            })(starrez.library.service.AddInActionCallBase);
            contentblock.GetContentItemList = GetContentItemList;
            var GetEditItemView = (function (_super) {
                __extends(GetEditItemView, _super);
                function GetEditItemView(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "ContentBlock";
                    this.Controller = "contentblock";
                    this.Action = "GetEditItemView";
                }
                GetEditItemView.prototype.CallData = function () {
                    var obj = {
                        portalPageWidgetID: this.o.portalPageWidgetID,
                        portalSettingID: this.o.portalSettingID
                    };
                    return obj;
                };
                return GetEditItemView;
            })(starrez.library.service.AddInActionCallBase);
            contentblock.GetEditItemView = GetEditItemView;
        })(contentblock = service.contentblock || (service.contentblock = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/// <reference path="../../../../WebCommon/TypeScriptTypes/lib.d.ts" />
/// <reference path="../../../../WebCommon/TypeScriptTypes/jquery/jquery.d.ts" />
/// <reference path="../../../../WebCommon/TypeScriptTypes/starrez.jquery.d.ts" />
/// <reference path="../../../../WebCommon/TypeScriptTypes/jqueryui/jqueryui.d.ts" />
/* Wrappers for what will eventually be generated by TSMVC  */
var starrez;
(function (starrez) {
    var general;
    (function (general) {
        var datainput;
        (function (datainput) {
            var formwidget;
            (function (formwidget) {
                var servicewrapper;
                (function (servicewrapper) {
                    "use strict";
                })(servicewrapper = formwidget.servicewrapper || (formwidget.servicewrapper = {}));
            })(formwidget = datainput.formwidget || (datainput.formwidget = {}));
        })(datainput = general.datainput || (general.datainput = {}));
    })(general = starrez.general || (starrez.general = {}));
})(starrez || (starrez = {}));
var portal;
(function (portal) {
    var general;
    (function (general) {
        var datainput;
        (function (datainput) {
            "use strict";
            (function (ControlType) {
                ControlType[ControlType["Checkbox"] = 0] = "Checkbox";
                ControlType[ControlType["DatePicker"] = 1] = "DatePicker";
                ControlType[ControlType["DateTimePicker"] = 2] = "DateTimePicker";
                ControlType[ControlType["DecimalTextbox"] = 3] = "DecimalTextbox";
                ControlType[ControlType["Dropdown"] = 4] = "Dropdown";
                ControlType[ControlType["IntegerTextbox"] = 5] = "IntegerTextbox";
                ControlType[ControlType["TimePicker"] = 6] = "TimePicker";
            })(datainput.ControlType || (datainput.ControlType = {}));
            var ControlType = datainput.ControlType;
            (function (LookupType) {
                LookupType[LookupType["Lookup"] = 0] = "Lookup";
                LookupType[LookupType["DatabaseTable"] = 1] = "DatabaseTable";
                LookupType[LookupType["GenericTable"] = 2] = "GenericTable";
            })(datainput.LookupType || (datainput.LookupType = {}));
            var LookupType = datainput.LookupType;
            var editorDataName = "Editor";
            function InitializeFieldListInlineEditor($container) {
                var widget = starrez.model.WidgetModelBaseModel($container);
                $container.data(editorDataName, new FieldListEditor($container.data("tablename").toString(), widget.PortalPageWidgetID, $container, false));
                InitializeFormWidget($container);
            }
            datainput.InitializeFieldListInlineEditor = InitializeFieldListInlineEditor;
            function InitializeRepeatingFieldListInlineEditor($container) {
                var widget = starrez.model.WidgetModelBaseModel($container);
                $container.data(editorDataName, new FieldListEditor($container.data("tablename").toString(), widget.PortalPageWidgetID, $container, true));
                InitializeFormWidget($container);
            }
            datainput.InitializeRepeatingFieldListInlineEditor = InitializeRepeatingFieldListInlineEditor;
            function InitializeNewFieldEditor($container) {
                var portalPageWidgetID = Number($container.data("portalpagewidgetid"));
                $container.data(editorDataName, new NewFieldEditor($container, portalPageWidgetID));
            }
            datainput.InitializeNewFieldEditor = InitializeNewFieldEditor;
            function InitializeEditFieldEditor($container) {
                var portalPageWidgetID = Number($container.data("portalpagewidgetid"));
                $container.data(editorDataName, new EditFieldEditor($container, portalPageWidgetID));
            }
            datainput.InitializeEditFieldEditor = InitializeEditFieldEditor;
            function InitializeFormWidget($container) {
                var portalPageWidgetID = Number($container.data("portalpagewidgetid"));
                var formWidget = new FormWidget(portalPageWidgetID, $container);
                $container.data("FormWidget", formWidget);
                window.addEventListener("load", function () {
                    portal.page.RemoveDuplicateFields($container);
                    formWidget.CleanupAfterDuplicateRemoval();
                });
            }
            datainput.InitializeFormWidget = InitializeFormWidget;
            function InitializeNewLookupEditor($container) {
                $container.data(editorDataName, new LookupEditor($container));
            }
            datainput.InitializeNewLookupEditor = InitializeNewLookupEditor;
            var FormWidget = (function () {
                function FormWidget(portalPageWidgetID, $container) {
                    var _this = this;
                    this.portalPageWidgetID = portalPageWidgetID;
                    this.$container = $container;
                    portal.page.RegisterWidgetSaveData(portalPageWidgetID, function () { return _this.GetSaveData(); });
                    // Setup the Add record button
                    var $addButton = this.$container.find(".ui-add-record");
                    $addButton.SRClick(function (e) {
                        _this.AddNewRecord();
                    });
                }
                FormWidget.prototype.GetSaveData = function () {
                    var saveData = new starrez.library.collections.KeyValue();
                    var $allControls = this.$container.GetAllControls();
                    $allControls.each(function (index, element) {
                        var $control = $(element);
                        var fieldID = $control.closest("li").data("id").toString();
                        var recordID = $control.closest(".ui-field-record").data("id").toString();
                        var masterRecordID = $control.closest(".ui-field-record").data("masterid").toString();
                        var value = starrez.library.convert.ToValueForServer($control.SRVal());
                        // Prevent any field name from being submitted - it must be one of the pre-configured ones
                        // {guid}: value
                        saveData.Add(fieldID + "_" + recordID + "_" + masterRecordID, value);
                    });
                    var data = saveData.ToArray();
                    if (data.length === 0) {
                        return null;
                    }
                    return data;
                };
                FormWidget.prototype.CleanupAfterDuplicateRemoval = function () {
                    var fieldList = this.$container.find(".ui-field-list").get(0);
                    var $fieldList = $(fieldList);
                    var hrs = $fieldList.find("hr.repeating-field-list-divider");
                    var foundOrphans = false;
                    hrs.each(function (index, hr) {
                        var $hr = $(hr);
                        if ($hr.prev().length == 0) {
                            // If we're here, this is a divider HR with no previous item to divide, so
                            // get rid of it
                            $hr.remove();
                            foundOrphans = true;
                        }
                    });
                    if (foundOrphans && $fieldList.children().length == 0) {
                        // If we're here, this is a duplicate field and so we shouldn't show
                        // the 'add new record' button
                        var $addButton = this.$container.find(".ui-add-record");
                        $addButton.remove();
                    }
                };
                FormWidget.prototype.AddNewRecord = function () {
                    var _this = this;
                    var deferred = $.Deferred();
                    // Find the lowest master ID that exists.  Set the new master ID to -1, if no negative IDs yet exist, or decrement by 1 if they do
                    var children = this.$container.closest(".ui-field-list-container").find(".ui-field-list").children();
                    children = $.map(children, function (li) { return $(li).find(".ui-field-record").data("masterid"); });
                    var minID = Math.min.apply(this, children);
                    var addNewRecordCall = new starrez.service.repeatingformwidget.AddNewRecord({
                        portalPageWidgetID: this.portalPageWidgetID,
                        index: children.length
                    });
                    if (minID >= 0) {
                        minID = -1;
                    }
                    else {
                        minID--;
                    }
                    addNewRecordCall.Get().done(function (html) {
                        var newRecord = $(html);
                        newRecord.find(".ui-field-record").each(function () {
                            $(this).attr("data-masterid", minID);
                        });
                        _this.$container.closest(".ui-field-list-container").find(".ui-field-list").append(newRecord);
                        portal.page.RemoveDuplicateFields(_this.$container);
                        if (_this.$container.find(newRecord).length > 0) {
                            var hr = document.createElement("hr");
                            hr.AddClass("repeating-field-list-divider");
                            newRecord.append(hr);
                        }
                        deferred.resolve();
                    });
                    return deferred.promise();
                };
                return FormWidget;
            })();
            var FieldListEditor = (function () {
                function FieldListEditor(tableName, portalPageWidgetID, $container, repeatFlag) {
                    this.tableName = tableName;
                    this.portalPageWidgetID = portalPageWidgetID;
                    this.$container = $container;
                    this.repeatFlag = repeatFlag;
                    this.sortOptions = {
                        handle: ".ui-drag-handle",
                        axis: "y",
                        cursor: "move",
                        items: "> li:not(.ui-add-field)"
                    };
                    this.InitOrdering();
                    this.AttachEvents();
                }
                FieldListEditor.prototype.RefreshFieldList = function () {
                    var _this = this;
                    var deferred = $.Deferred();
                    var refreshFieldListCall = new starrez.service.formwidget.GetRefreshedFieldList({
                        portalPageWidgetID: this.portalPageWidgetID,
                        url: window.location.href,
                        repeatFlag: this.repeatFlag
                    });
                    refreshFieldListCall.Get().done(function (html) {
                        // Refreshing the list will register the save data - so remove the existing registration so we don"t end up with multiple
                        portal.page.RemoveWidgetSaveData(_this.portalPageWidgetID);
                        var $fieldContainer = _this.$container.closest(".ui-field-list-container");
                        $fieldContainer.html(html);
                        portal.validation.ValidateForm($fieldContainer);
                        deferred.resolve();
                    });
                    return deferred.promise();
                };
                FieldListEditor.prototype.AttachEvents = function () {
                    var _this = this;
                    // Setup the add field button/template
                    var $addFieldButton = this.$container.find(".ui-add-field");
                    $addFieldButton.SRClick(function () {
                        var call = new starrez.service.formwidget.CreateNewField({
                            tableName: _this.tableName,
                            portalPageWidgetID: _this.portalPageWidgetID
                        });
                        portal.OpenSRWActionInDialog(call, function (popup) {
                            _this.InitFieldEditor(popup);
                        });
                    });
                    // Setup the Edit buttons next to each field
                    var $editButtons = this.$container.find(".ui-edit-field");
                    $editButtons.click(function (e) {
                        var $fieldItem = $(e.currentTarget).closest("li");
                        _this.EditField($fieldItem);
                    });
                    // Setup the Remove buttons next to each field
                    var $removeButtons = this.$container.find(".ui-remove-field");
                    $removeButtons.click(function (e) {
                        var $button = $(e.currentTarget);
                        var $fieldItem = $button.closest("li");
                        var fieldLabel = $button.data("label");
                        portal.ConfirmAction("Do you want to delete '" + fieldLabel + "'?", "Delete").done(function () {
                            _this.RemoveField($fieldItem);
                        });
                    });
                };
                FieldListEditor.prototype.EditField = function ($fieldItem) {
                    var _this = this;
                    var id = String($fieldItem.closest("li").data("id"));
                    var editCall = new starrez.service.formwidget.EditField({
                        fieldID: id,
                        portalPageWidgetID: this.portalPageWidgetID
                    });
                    portal.OpenSRWActionInDialog(editCall, function (popup) {
                        _this.InitFieldEditor(popup);
                    });
                };
                FieldListEditor.prototype.RemoveField = function ($fieldItem) {
                    var _this = this;
                    var id = String($fieldItem.closest("li").data("id"));
                    var removeCall = new starrez.service.formwidget.RemoveField({
                        fieldID: id,
                        portalPageWidgetID: this.portalPageWidgetID,
                        errorHandler: starrez.error.CreateErrorObject()
                    });
                    removeCall.Post().done(function () {
                        _this.RefreshFieldList();
                    });
                };
                FieldListEditor.prototype.InitOrdering = function () {
                    var _this = this;
                    var $fieldList = this.$container.find(".ui-field-list");
                    $fieldList.sortable(this.sortOptions);
                    $fieldList.on("sortupdate", function (e) {
                        var idOrderMapping = new starrez.library.collections.KeyValue();
                        $fieldList.find("li:not(.ui-add-field, .ui-ignore-sort)").each(function (index, element) {
                            var id = String($(element).data("id"));
                            idOrderMapping.Add(id, index);
                        });
                        var updateCall = new starrez.service.formwidget.ReorderFields({
                            idOrderMapping: idOrderMapping.ToArray(),
                            portalPageWidgetID: _this.portalPageWidgetID,
                            errorHandler: starrez.error.CreateErrorObject()
                        });
                        updateCall.Post().done(function () {
                            _this.RefreshFieldList();
                        });
                    });
                };
                FieldListEditor.prototype.InitFieldEditor = function (popup) {
                    var $editorContainer = popup.$article.find(".ui-field-container");
                    var fieldEditor = $editorContainer.data(editorDataName);
                    fieldEditor.fieldListEditor = this;
                };
                return FieldListEditor;
            })();
            var FieldEditorBase = (function () {
                function FieldEditorBase($container, portalPageWidgetID) {
                    this.$container = $container;
                    this.portalPageWidgetID = portalPageWidgetID;
                    this.InitControls();
                }
                FieldEditorBase.prototype.InitControls = function () {
                    var _this = this;
                    var $saveButton = starrez.popup.GetPopupContainerAreas(this.$container).$footer.find(".ui-btn-save");
                    $saveButton.click(function () {
                        _this.Validate().done(function () {
                            _this.Save().done(function () {
                                _this.PostSaveOperation();
                            });
                        }).fail(function (message) {
                            starrez.ui.ShowAlertMessage(message);
                        });
                    });
                };
                FieldEditorBase.prototype.Validate = function () {
                    var validationDeferred = $.Deferred();
                    var message = this.SynchronousValidation();
                    if (starrez.library.utils.IsNotNullUndefined(message)) {
                        validationDeferred.reject(message);
                    }
                    else {
                        validationDeferred.resolve(null);
                    }
                    return validationDeferred.promise();
                };
                /**
                  *Simple validation that is Synchronous. Complicated valudation will require overriding Validate()
                  * returns message when invalid null/undefined when valid
                  */
                FieldEditorBase.prototype.SynchronousValidation = function () {
                    return null;
                };
                FieldEditorBase.prototype.Get = function (controlName) {
                    return this.$container.GetControl(controlName).SRVal();
                };
                return FieldEditorBase;
            })();
            var NewFieldEditor = (function (_super) {
                __extends(NewFieldEditor, _super);
                function NewFieldEditor($container, portalPageWidgetID) {
                    _super.call(this, $container, portalPageWidgetID);
                    this.$fieldNameControl = this.$container.GetControl(NewFieldEditor.FieldPropertyName);
                }
                NewFieldEditor.prototype.Save = function () {
                    var _this = this;
                    var selectedFields = this.$selectedNodes.map(function (i, e) {
                        var fieldData = {
                            FieldName: $(e).data("field-uniqueid").toString(),
                            DisplayName: $(e).data("field-displayname").toString(),
                            TableName: $(e).closest(".ui-treeview-list").find(".ui-tree-view-row-item:first").data("caption").toString(),
                            LookupID: Number(_this.$container.GetControl("LookupID").SRVal())
                        };
                        return fieldData;
                    }).toArray();
                    var call = new starrez.service.formwidget.AddFields({
                        fields: selectedFields,
                        portalPageWidgetID: this.portalPageWidgetID,
                        errorHandler: starrez.error.CreateErrorObject()
                    });
                    return call.Post();
                };
                NewFieldEditor.prototype.PostSaveOperation = function () {
                    //1. Form widgets detect duplicate fields by assigning same HTML ID to same fields loaded on CURRENT request.
                    //   This means that if there are multiple form widgets on one page, admin won't know if they added duplicate fields/not
                    //   until they reload the page and force reload all fields in all form widgets on the page in a single request.
                    //   Long story short, just reload the page here, don't use RefreshFieldList method. Otherwise, duplicate fields checking won't work.
                    //2. IE has issues where SRClickDelegate attached to iFrame contents won't work if only the iframe is refreshed,
                    //   hence why we need to refresh the whole window
                    if (starrez.library.browser.GetBrowser() === starrez.library.browser.BrowserType.InternetExplorer) {
                        window.top.location.reload(true);
                    }
                    else {
                        location.reload(true);
                    }
                };
                NewFieldEditor.prototype.SynchronousValidation = function () {
                    this.$selectedNodes = starrez.library.controls.treeview.SelectedItem(this.$fieldNameControl);
                    if (!this.$selectedNodes.isFound()) {
                        return "You must select at least one field to continue.";
                    }
                    return null;
                };
                NewFieldEditor.FieldPropertyName = "FieldName";
                return NewFieldEditor;
            })(FieldEditorBase);
            var EditFieldEditor = (function (_super) {
                __extends(EditFieldEditor, _super);
                function EditFieldEditor() {
                    _super.apply(this, arguments);
                }
                EditFieldEditor.prototype.InitControls = function () {
                    var _this = this;
                    _super.prototype.InitControls.call(this);
                    this.editableRelatedFields = [EditFieldEditor.MaxLengthPropertyName, EditFieldEditor.PatternPropertyName, EditFieldEditor.ErrorTextPropertyName,
                        EditFieldEditor.DefaultValuePropertyName, EditFieldEditor.IsRequiredPropertyName, EditFieldEditor.RequiredErrorMessage, EditFieldEditor.PatternErrorMessage,
                        EditFieldEditor.MaxLengthErrorMessage, EditFieldEditor.UsePatternValidation];
                    this.$isReadOnlyControl = this.$container.GetControl(EditFieldEditor.IsReadOnlyPropertyName);
                    this.$isReadOnlyControl.change(function () { return _this.ToggleEditableRelatedFields(false); });
                    this.ToggleEditableRelatedFields(true);
                    this.$isControlTypeOverrideControl = this.$container.GetControl(EditFieldEditor.IsControlTypeOverride);
                    this.$isControlTypeOverrideControl.change(function () {
                        _this.ToggleControlOverride(false, true);
                    });
                    this.ToggleControlOverride(true, false);
                    this.$controlTypeOverrideControl = this.$container.GetControl(EditFieldEditor.ControlTypeOverride);
                    this.$controlTypeOverrideControl.change(function () {
                        _this.ToggleDropdownControls(false, true);
                    });
                    this.$lookupTypeControl = this.$container.GetControl(EditFieldEditor.LookupType);
                    this.$lookupTypeControl.change(function () {
                        _this.ToggleLookupControls(false, true);
                    });
                    this.$container.GetControl(EditFieldEditor.LookupID).change(function () {
                        _this.UpdateDefaultValueControl();
                    });
                    this.$isRequiredControl = this.$container.GetControl(EditFieldEditor.IsRequiredPropertyName);
                    this.$isRequiredControl.change(function () { return _this.ToggleControl(false, starrez.library.convert.ToBoolean(_this.$isRequiredControl.SRVal()), EditFieldEditor.RequiredErrorMessage); });
                    this.ToggleControl(true, starrez.library.convert.ToBoolean(this.$isRequiredControl.SRVal()), EditFieldEditor.RequiredErrorMessage);
                    this.$usePatternValidationControl = this.$container.GetControl(EditFieldEditor.UsePatternValidation);
                    this.$usePatternValidationControl.change(function () {
                        _this.TogglePatternValidationControls(false);
                    });
                    this.TogglePatternValidationControls(true);
                    this.$lookupTableNameControl = this.$container.GetControl(EditFieldEditor.LookupTableName);
                    this.$lookupTableValueColumnNameControl = this.$container.GetControl(EditFieldEditor.LookupTableValueColumnName);
                    this.$lookupTableTextColumnNameControl = this.$container.GetControl(EditFieldEditor.LookupTableTextColumnName);
                    this.$defaultValueControl = this.$container.find(".ui-default-value-control");
                    this.$lookupTableNameControl.change(function (e) {
                        _this.GetLookupTableColumns();
                        _this.UpdateDefaultValueControl();
                    });
                    this.$lookupTableTextColumnNameControl.change(function () {
                        _this.UpdateDefaultValueControl();
                    });
                    this.$lookupTableValueColumnNameControl.change(function () {
                        _this.UpdateDefaultValueControl();
                    });
                    var $addLookupButton = this.$container.find(".ui-btn-add-lookup");
                    $addLookupButton.click(function (e) {
                        _this.AddLookup();
                    });
                };
                EditFieldEditor.prototype.AddLookup = function () {
                    var _this = this;
                    var addLookupCall = new starrez.service.formwidget.AddLookup();
                    portal.OpenSRWActionInDialog(addLookupCall, function (popup) {
                        _this.InitLookupEditor(popup);
                    });
                };
                EditFieldEditor.prototype.RefreshLookups = function (value, innerHtml) {
                    var option = document.createElement("option");
                    option.value = value.toString();
                    ;
                    option.innerText = innerHtml;
                    var $select = this.$container.GetControl(EditFieldEditor.LookupID).children("div").children("select");
                    $select.append(option);
                };
                EditFieldEditor.prototype.GetLookupTables = function () {
                    var _this = this;
                    var call = new starrez.service.formwidget.GetLookupTables({
                        lookupType: this.$container.GetControl(EditFieldEditor.LookupType).SRVal()
                    });
                    call.Get().done(function (json) {
                        starrez.library.controls.dropdown.FillDropDown(json, _this.$lookupTableNameControl, "Value", "Text", "", false);
                        _this.GetLookupTableColumns();
                    });
                };
                EditFieldEditor.prototype.GetLookupTableColumns = function () {
                    var _this = this;
                    var call = new starrez.service.formwidget.GetTableColumns({
                        lookupType: this.$container.GetControl(EditFieldEditor.LookupType).SRVal(),
                        tableName: this.$container.GetControl(EditFieldEditor.LookupTableName).SRVal()
                    });
                    call.Get().done(function (json) {
                        starrez.library.controls.dropdown.FillDropDown(json, _this.$lookupTableValueColumnNameControl, "Value", "Text", "", false);
                        starrez.library.controls.dropdown.FillDropDown(json, _this.$lookupTableTextColumnNameControl, "Value", "Text", "", false);
                        _this.UpdateDefaultValueControl();
                    });
                };
                EditFieldEditor.prototype.GetEditableField = function () {
                    return {
                        Label: this.Get(EditFieldEditor.LabelPropertyName),
                        IsRequired: starrez.library.convert.ToBoolean(this.Get(EditFieldEditor.IsRequiredPropertyName)),
                        MaxLength: this.Get(EditFieldEditor.MaxLengthPropertyName),
                        PatternString: this.Get(EditFieldEditor.PatternPropertyName),
                        DefaultValue: this.Get(EditFieldEditor.DefaultValuePropertyName),
                        ID: this.Get(EditFieldEditor.IDPropertyName),
                        IsReadOnly: starrez.library.convert.ToBoolean(this.Get(EditFieldEditor.IsReadOnlyPropertyName)),
                        UsePatternValidation: starrez.library.convert.ToBoolean(this.Get(EditFieldEditor.UsePatternValidation)),
                        PatternErrorMessage: this.Get(EditFieldEditor.PatternErrorMessage),
                        MaxLengthErrorMessage: this.Get(EditFieldEditor.MaxLengthErrorMessage),
                        MinValueErrorMessage: this.Get(EditFieldEditor.MinValueErrorMessage),
                        MaxValueErrorMessage: this.Get(EditFieldEditor.MaxValueErrorMessage),
                        RequiredErrorMessage: this.Get(EditFieldEditor.RequiredErrorMessage),
                        LookupType: this.Get(EditFieldEditor.LookupType),
                        LookupID: this.Get(EditFieldEditor.LookupID),
                        ControlTypeOverride: this.Get(EditFieldEditor.ControlTypeOverride),
                        IsControlTypeOverride: starrez.library.convert.ToBoolean(this.Get(EditFieldEditor.IsControlTypeOverride)),
                        LookupTableName: this.Get(EditFieldEditor.LookupTableName),
                        LookupTableValueColumnName: this.Get(EditFieldEditor.LookupTableValueColumnName),
                        LookupTableTextColumnName: this.Get(EditFieldEditor.LookupTableTextColumnName),
                        IsUniqueID: this.Get(EditFieldEditor.IsUniqueIDPropertyName)
                    };
                };
                EditFieldEditor.prototype.Save = function () {
                    var fieldData = this.GetEditableField();
                    var call = new starrez.service.formwidget.SaveField({
                        field: fieldData,
                        portalPageWidgetID: this.portalPageWidgetID,
                        errorHandler: starrez.error.CreateErrorObject()
                    });
                    return call.Post();
                };
                EditFieldEditor.prototype.PostSaveOperation = function () {
                    var _this = this;
                    this.fieldListEditor.RefreshFieldList().done(function () {
                        starrez.popup.Close(_this.$container);
                    });
                };
                EditFieldEditor.prototype.ToggleEditableRelatedFields = function (beQuick) {
                    var _this = this;
                    var isReadOnly = starrez.library.convert.ToBoolean(this.$isReadOnlyControl.SRVal());
                    var effect = beQuick ? undefined : "slideup";
                    this.editableRelatedFields.forEach(function (controlName) {
                        var $controlRow = _this.$container.GetControl(controlName).closest("li");
                        if (isReadOnly) {
                            $controlRow.hide(effect);
                        }
                        else if (!$controlRow.hasClass("ui-hide")) {
                            $controlRow.show(effect, function () {
                                starrez.popup.AutoHeightPopup(_this.$container);
                            });
                        }
                    });
                };
                EditFieldEditor.prototype.ToggleControlOverride = function (beQuick, populateTables) {
                    var isOverride = starrez.library.convert.ToBoolean(this.$isControlTypeOverrideControl.SRVal());
                    if (isOverride) {
                        this.ToggleControl(beQuick, true, EditFieldEditor.ControlTypeOverride);
                        this.ToggleDropdownControls(beQuick, populateTables);
                    }
                    else {
                        this.ToggleControl(beQuick, false, EditFieldEditor.ControlTypeOverride);
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupType);
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupID);
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupTableName);
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupTableTextColumnName);
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupTableValueColumnName);
                    }
                    this.UpdateDefaultValueControl();
                };
                EditFieldEditor.prototype.ToggleDropdownControls = function (beQuick, populateTables) {
                    var overrideType = this.$container.GetControl(EditFieldEditor.ControlTypeOverride).SRVal();
                    if (overrideType == ControlType.Dropdown) {
                        this.ToggleControl(beQuick, true, EditFieldEditor.LookupType);
                        this.ToggleLookupControls(beQuick, populateTables);
                    }
                    else {
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupType);
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupID);
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupTableName);
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupTableTextColumnName);
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupTableValueColumnName);
                    }
                    this.UpdateDefaultValueControl();
                };
                EditFieldEditor.prototype.UpdateDefaultValueControl = function () {
                    var _this = this;
                    //make sure we send request only when the control type is overridden and edit field's state has changed
                    if (starrez.library.convert.ToBoolean(this.Get(EditFieldEditor.IsControlTypeOverride))) {
                        var editField = this.GetEditableField();
                        var editFieldCurrentState = JSON.stringify(editField);
                        var isEditFieldStateChanged = starrez.library.stringhelper.IsUndefinedOrEmpty(this.editFieldState) || !starrez.library.stringhelper.Equals(this.editFieldState, editFieldCurrentState, false);
                        if (isEditFieldStateChanged) {
                            this.editFieldState = editFieldCurrentState;
                            new starrez.service.formwidget.UpdateDefaultValueControl({
                                portalPageWidgetID: this.portalPageWidgetID,
                                strUnsavedEditField: editFieldCurrentState
                            }).Get().done(function (html) {
                                _this.$defaultValueControl.html(html);
                            });
                        }
                    }
                };
                EditFieldEditor.prototype.ToggleLookupControls = function (beQuick, populateTables) {
                    var lookupType = this.$container.GetControl(EditFieldEditor.LookupType).SRVal();
                    if (lookupType == LookupType.Lookup) {
                        this.ToggleControl(beQuick, true, EditFieldEditor.LookupID);
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupTableName);
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupTableTextColumnName);
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupTableValueColumnName);
                        this.UpdateDefaultValueControl();
                    }
                    else {
                        if (populateTables) {
                            //We can't have simultaneous AJAX calls at the same time,
                            //otherwise the loading animation on the dropdown will get confused on when to stop.
                            //Hence, in this case, UpdateDefaultValueControl is called when all the requests have finished
                            this.GetLookupTables();
                        }
                        else {
                            this.UpdateDefaultValueControl();
                        }
                        this.ToggleControl(beQuick, false, EditFieldEditor.LookupID);
                        this.ToggleControl(beQuick, true, EditFieldEditor.LookupTableName);
                        this.ToggleControl(beQuick, true, EditFieldEditor.LookupTableTextColumnName);
                        this.ToggleControl(beQuick, true, EditFieldEditor.LookupTableValueColumnName);
                    }
                };
                EditFieldEditor.prototype.TogglePatternValidationControls = function (beQuick) {
                    var usePattern = this.$container.GetControl(EditFieldEditor.UsePatternValidation).SRVal();
                    if (usePattern) {
                        this.ToggleControl(beQuick, true, EditFieldEditor.PatternPropertyName);
                        this.ToggleControl(beQuick, true, EditFieldEditor.PatternErrorMessage);
                    }
                    else {
                        this.ToggleControl(beQuick, false, EditFieldEditor.PatternPropertyName);
                        this.ToggleControl(beQuick, false, EditFieldEditor.PatternErrorMessage);
                    }
                };
                EditFieldEditor.prototype.ToggleControl = function (beQuick, show, controlName) {
                    var effect = beQuick ? undefined : "slideup";
                    var $controlRow = this.$container.GetControl(controlName).closest("li");
                    if (show) {
                        $controlRow.show(effect);
                        $controlRow.removeClass("ui-hide");
                    }
                    else {
                        $controlRow.hide(effect);
                        $controlRow.addClass("ui-hide");
                    }
                };
                EditFieldEditor.prototype.InitLookupEditor = function (popup) {
                    var $editorContainer = popup.$article.find(".ui-lookup-container");
                    var lookupEditor = $editorContainer.data(editorDataName);
                    lookupEditor.editFieldEditor = this;
                };
                EditFieldEditor.MaxLengthPropertyName = "MaxLength";
                EditFieldEditor.LabelPropertyName = "Label";
                EditFieldEditor.IsRequiredPropertyName = "IsRequired";
                EditFieldEditor.PatternPropertyName = "PatternString";
                EditFieldEditor.ErrorTextPropertyName = "ErrorText";
                EditFieldEditor.DefaultValuePropertyName = "DefaultValue";
                EditFieldEditor.IDPropertyName = "ID";
                EditFieldEditor.IsReadOnlyPropertyName = "IsReadOnly";
                EditFieldEditor.UsePatternValidation = "UsePatternValidation";
                EditFieldEditor.PatternErrorMessage = "PatternErrorMessage";
                EditFieldEditor.MaxLengthErrorMessage = "MaxLengthErrorMessage";
                EditFieldEditor.MinValueErrorMessage = "MinValueErrorMessage";
                EditFieldEditor.MaxValueErrorMessage = "MaxValueErrorMessage";
                EditFieldEditor.RequiredErrorMessage = "RequiredErrorMessage";
                EditFieldEditor.LookupType = "LookupType";
                EditFieldEditor.LookupID = "LookupID";
                EditFieldEditor.ControlTypeOverride = "ControlTypeOverride";
                EditFieldEditor.IsControlTypeOverride = "IsControlTypeOverride";
                EditFieldEditor.LookupTableName = "LookupTableName";
                EditFieldEditor.LookupTableValueColumnName = "LookupTableValueColumnName";
                EditFieldEditor.LookupTableTextColumnName = "LookupTableTextColumnName";
                EditFieldEditor.IsUniqueIDPropertyName = "IsUniqueID";
                return EditFieldEditor;
            })(FieldEditorBase);
            var LookupEditor = (function () {
                function LookupEditor($container) {
                    this.$container = $container;
                    this.InitControls();
                }
                LookupEditor.prototype.InitControls = function () {
                    var _this = this;
                    this.$srEditor = this.$container.find(".ui-sr-editor");
                    var $saveButton = starrez.popup.GetPopupContainerAreas(this.$container).$footer.find(".ui-btn-save");
                    $saveButton.click(function () {
                        _this.Save().done(function (result) {
                            _this.editFieldEditor.RefreshLookups(result, _this.$container.GetControl(LookupEditor.LookupDescription).SRVal());
                            starrez.popup.Close(_this.$container);
                        }).fail(function () {
                        });
                    });
                    var $addValueButton = this.$container.find(".ui-btn-add-value");
                    $addValueButton.click(function (e) {
                        var clone = _this.$srEditor.clone(false, false);
                        clone.removeClass("hidden");
                        var $valuesContainer = _this.$container.find(".ui-field-properties");
                        $valuesContainer.append(clone);
                    });
                };
                LookupEditor.prototype.Save = function () {
                    var deferred = $.Deferred();
                    var description = this.$container.GetControl(LookupEditor.LookupDescription).SRVal();
                    if (starrez.library.stringhelper.IsUndefinedOrEmpty(description)) {
                        starrez.ui.ShowAlertMessage("You must enter a Lookup Description");
                        deferred.reject(-1);
                        return deferred.promise();
                    }
                    var values = new Array();
                    var $allControls = this.$container.GetAllControls();
                    var text = undefined;
                    for (var i = 1; i < $allControls.length - 2; i++) {
                        var $textControl = $($allControls[i]);
                        var $valueControl = $($allControls[++i]);
                        if ($textControl.hasClass("text") && !$textControl.hasClass("hidden") && $valueControl.hasClass("text") && !$valueControl.hasClass("hidden")) {
                            var text = $textControl.SRVal();
                            var value = $valueControl.SRVal();
                            if (!starrez.library.stringhelper.IsUndefinedOrEmpty(text)) {
                                if (values.indexOf(text) === -1) {
                                    values.push(text);
                                    values.push(value);
                                }
                                else {
                                    starrez.ui.ShowAlertMessage("Every item in the list must have a unique display text.");
                                    deferred.reject(-1);
                                    return deferred.promise();
                                }
                            }
                            else {
                                starrez.ui.ShowAlertMessage("Every item must have a Display Text");
                                deferred.reject(-1);
                                return deferred.promise();
                            }
                        }
                    }
                    if (values.length == 0) {
                        starrez.ui.ShowAlertMessage("You must enter at least one value");
                        deferred.reject(-1);
                        return deferred.promise();
                    }
                    var call = new starrez.service.formwidget.SaveLookup({
                        description: description,
                        lookupTextValues: values,
                        errorHandler: starrez.error.CreateErrorObject()
                    });
                    call.Post().done(function (result) {
                        deferred.resolve(result);
                    });
                    return deferred.promise();
                };
                LookupEditor.LookupDescription = "LookupDescription";
                return LookupEditor;
            })();
        })(datainput = general.datainput || (general.datainput = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function FieldModel($sys) {
            return {
                TableName: $sys.data('tablename')
            };
        }
        model.FieldModel = FieldModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var formwidget;
        (function (formwidget) {
            "use strict";
            var AddFields = (function (_super) {
                __extends(AddFields, _super);
                function AddFields(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DataInput";
                    this.Controller = "formwidget";
                    this.Action = "AddFields";
                }
                AddFields.prototype.CallData = function () {
                    var obj = {
                        errorHandler: this.o.errorHandler,
                        fields: this.o.fields,
                        portalPageWidgetID: this.o.portalPageWidgetID
                    };
                    return obj;
                };
                return AddFields;
            })(starrez.library.service.AddInActionCallBase);
            formwidget.AddFields = AddFields;
            var AddLookup = (function (_super) {
                __extends(AddLookup, _super);
                function AddLookup() {
                    _super.call(this);
                    this.Customer = "General";
                    this.Area = "DataInput";
                    this.Controller = "formwidget";
                    this.Action = "AddLookup";
                }
                return AddLookup;
            })(starrez.library.service.AddInActionCallBase);
            formwidget.AddLookup = AddLookup;
            var CreateNewField = (function (_super) {
                __extends(CreateNewField, _super);
                function CreateNewField(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DataInput";
                    this.Controller = "formwidget";
                    this.Action = "CreateNewField";
                }
                CreateNewField.prototype.CallData = function () {
                    var obj = {
                        portalPageWidgetID: this.o.portalPageWidgetID,
                        tableName: this.o.tableName
                    };
                    return obj;
                };
                return CreateNewField;
            })(starrez.library.service.AddInActionCallBase);
            formwidget.CreateNewField = CreateNewField;
            var EditField = (function (_super) {
                __extends(EditField, _super);
                function EditField(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DataInput";
                    this.Controller = "formwidget";
                    this.Action = "EditField";
                }
                EditField.prototype.CallData = function () {
                    var obj = {
                        fieldID: this.o.fieldID,
                        portalPageWidgetID: this.o.portalPageWidgetID
                    };
                    return obj;
                };
                return EditField;
            })(starrez.library.service.AddInActionCallBase);
            formwidget.EditField = EditField;
            var GetLookupTables = (function (_super) {
                __extends(GetLookupTables, _super);
                function GetLookupTables(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DataInput";
                    this.Controller = "formwidget";
                    this.Action = "GetLookupTables";
                }
                GetLookupTables.prototype.CallData = function () {
                    var obj = {
                        lookupType: this.o.lookupType
                    };
                    return obj;
                };
                return GetLookupTables;
            })(starrez.library.service.AddInActionCallBase);
            formwidget.GetLookupTables = GetLookupTables;
            var GetRefreshedFieldList = (function (_super) {
                __extends(GetRefreshedFieldList, _super);
                function GetRefreshedFieldList(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DataInput";
                    this.Controller = "formwidget";
                    this.Action = "GetRefreshedFieldList";
                }
                GetRefreshedFieldList.prototype.CallData = function () {
                    var obj = {
                        portalPageWidgetID: this.o.portalPageWidgetID,
                        repeatFlag: this.o.repeatFlag,
                        url: this.o.url
                    };
                    return obj;
                };
                return GetRefreshedFieldList;
            })(starrez.library.service.AddInActionCallBase);
            formwidget.GetRefreshedFieldList = GetRefreshedFieldList;
            var GetTableColumns = (function (_super) {
                __extends(GetTableColumns, _super);
                function GetTableColumns(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DataInput";
                    this.Controller = "formwidget";
                    this.Action = "GetTableColumns";
                }
                GetTableColumns.prototype.CallData = function () {
                    var obj = {
                        lookupType: this.o.lookupType,
                        tableName: this.o.tableName
                    };
                    return obj;
                };
                return GetTableColumns;
            })(starrez.library.service.AddInActionCallBase);
            formwidget.GetTableColumns = GetTableColumns;
            var RemoveField = (function (_super) {
                __extends(RemoveField, _super);
                function RemoveField(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DataInput";
                    this.Controller = "formwidget";
                    this.Action = "RemoveField";
                }
                RemoveField.prototype.CallData = function () {
                    var obj = {
                        errorHandler: this.o.errorHandler,
                        fieldID: this.o.fieldID,
                        portalPageWidgetID: this.o.portalPageWidgetID
                    };
                    return obj;
                };
                return RemoveField;
            })(starrez.library.service.AddInActionCallBase);
            formwidget.RemoveField = RemoveField;
            var ReorderFields = (function (_super) {
                __extends(ReorderFields, _super);
                function ReorderFields(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DataInput";
                    this.Controller = "formwidget";
                    this.Action = "ReorderFields";
                }
                ReorderFields.prototype.CallData = function () {
                    var obj = {
                        errorHandler: this.o.errorHandler,
                        idOrderMapping: this.o.idOrderMapping,
                        portalPageWidgetID: this.o.portalPageWidgetID
                    };
                    return obj;
                };
                return ReorderFields;
            })(starrez.library.service.AddInActionCallBase);
            formwidget.ReorderFields = ReorderFields;
            var SaveField = (function (_super) {
                __extends(SaveField, _super);
                function SaveField(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DataInput";
                    this.Controller = "formwidget";
                    this.Action = "SaveField";
                }
                SaveField.prototype.CallData = function () {
                    var obj = {
                        errorHandler: this.o.errorHandler,
                        field: this.o.field,
                        portalPageWidgetID: this.o.portalPageWidgetID
                    };
                    return obj;
                };
                return SaveField;
            })(starrez.library.service.AddInActionCallBase);
            formwidget.SaveField = SaveField;
            var SaveLookup = (function (_super) {
                __extends(SaveLookup, _super);
                function SaveLookup(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DataInput";
                    this.Controller = "formwidget";
                    this.Action = "SaveLookup";
                }
                SaveLookup.prototype.CallData = function () {
                    var obj = {
                        description: this.o.description,
                        errorHandler: this.o.errorHandler,
                        lookupTextValues: this.o.lookupTextValues
                    };
                    return obj;
                };
                return SaveLookup;
            })(starrez.library.service.AddInActionCallBase);
            formwidget.SaveLookup = SaveLookup;
            var UpdateDefaultValueControl = (function (_super) {
                __extends(UpdateDefaultValueControl, _super);
                function UpdateDefaultValueControl(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DataInput";
                    this.Controller = "formwidget";
                    this.Action = "UpdateDefaultValueControl";
                }
                UpdateDefaultValueControl.prototype.CallData = function () {
                    var obj = {
                        portalPageWidgetID: this.o.portalPageWidgetID,
                        strUnsavedEditField: this.o.strUnsavedEditField
                    };
                    return obj;
                };
                return UpdateDefaultValueControl;
            })(starrez.library.service.AddInActionCallBase);
            formwidget.UpdateDefaultValueControl = UpdateDefaultValueControl;
        })(formwidget = service.formwidget || (service.formwidget = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var repeatingformwidget;
        (function (repeatingformwidget) {
            "use strict";
            var AddNewRecord = (function (_super) {
                __extends(AddNewRecord, _super);
                function AddNewRecord(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DataInput";
                    this.Controller = "repeatingformwidget";
                    this.Action = "AddNewRecord";
                }
                AddNewRecord.prototype.CallData = function () {
                    var obj = {
                        portalPageWidgetID: this.o.portalPageWidgetID,
                        index: this.o.index
                    };
                    return obj;
                };
                return AddNewRecord;
            })(starrez.library.service.AddInActionCallBase);
            repeatingformwidget.AddNewRecord = AddNewRecord;
        })(repeatingformwidget = service.repeatingformwidget || (service.repeatingformwidget = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var starrez;
(function (starrez) {
    var general;
    (function (general) {
        var daterangepicker;
        (function (daterangepicker) {
            "use strict";
            function InitSettingsEditor($container) {
                debugger;
                var $selectedTable = $container.GetControl("SelectedTable");
                var $dateStartField = $container.GetControl("DateStartField");
                var $dateEndField = $container.GetControl("DateEndField");
                $selectedTable.change(function () {
                    var selectedValue = $selectedTable.SRVal();
                    var call = new starrez.service.daterangepicker.GetTableDateColumns({ tableOption: selectedValue });
                    call.Post().done(function (data) {
                        starrez.library.controls.dropdown.Clear($dateStartField);
                        starrez.library.controls.dropdown.FillDropDown(data, $dateStartField, "Value", "Key", "-1", false);
                        starrez.library.controls.dropdown.Clear($dateEndField);
                        starrez.library.controls.dropdown.FillDropDown(data, $dateEndField, "Value", "Key", "-1", false);
                    });
                });
            }
            daterangepicker.InitSettingsEditor = InitSettingsEditor;
        })(daterangepicker = general.daterangepicker || (general.daterangepicker = {}));
    })(general = starrez.general || (starrez.general = {}));
})(starrez || (starrez = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var daterangepicker;
        (function (daterangepicker) {
            "use strict";
            var GetTableDateColumns = (function (_super) {
                __extends(GetTableDateColumns, _super);
                function GetTableDateColumns(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DateRangePicker";
                    this.Controller = "daterangepicker";
                    this.Action = "GetTableDateColumns";
                }
                GetTableDateColumns.prototype.CallData = function () {
                    var obj = {
                        tableOption: this.o.tableOption
                    };
                    return obj;
                };
                return GetTableDateColumns;
            })(starrez.library.service.AddInActionCallBase);
            daterangepicker.GetTableDateColumns = GetTableDateColumns;
        })(daterangepicker = service.daterangepicker || (service.daterangepicker = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var docraptor;
        (function (docraptor) {
            "use strict";
            function Initialise($container) {
                new DocRaptor($container);
            }
            docraptor.Initialise = Initialise;
            var DocRaptor = (function () {
                function DocRaptor($container) {
                    var _this = this;
                    this.$container = $container;
                    this.model = starrez.model.DocRaptorModel($container);
                    this.widgetID = Number(this.$container.data("portalpagewidgetid"));
                    if (this.model.SendEmail) {
                        portal.page.RegisterWidgetSaveData(this.widgetID, function () { return _this.GetData(); });
                    }
                    $container.find(".ui-docraptor").SRClick(function () {
                        _this.SendRequest();
                    });
                }
                DocRaptor.prototype.SendRequest = function () {
                    new starrez.service.docraptor.GeneratePdf({
                        portalPageWidgetID: this.widgetID,
                        content: this.BuildHtmlToPdf()
                    }).Post().done(function (url) {
                        if (starrez.library.utils.IsNotNullUndefined(url)) {
                            location.href = url;
                        }
                    });
                };
                /**
                 * Takes all the css,js and page content under the "portalx" class and wraps it up to be rendered
                 */
                DocRaptor.prototype.BuildHtmlToPdf = function () {
                    var htmlUnderPortalXClass = portal.PageElements.$pageContainer.closest(".portalx").get(0).outerHTML;
                    var $html = $("<html></html>");
                    var $head = $("<head></head>");
                    var $body = $("<body></body>").append(htmlUnderPortalXClass);
                    $.each(document.styleSheets, function (index, stylesheet) {
                        if (starrez.library.utils.IsNotNullUndefined(stylesheet.href)) {
                            var $link = $("<link href='" + stylesheet.href + "' rel='Stylesheet' type='" + stylesheet.type + "' />");
                            $head.append($link);
                        }
                    });
                    $html.append($head).append($body);
                    $html.find("script").remove(); // remove any script tags as we are not running javascript
                    $html.find("link[rel='shortcut icon']").remove(); // remove favicon it's one less thing to download before pdf-ing
                    return $html.get(0).outerHTML;
                };
                /**
                 * On Save and Continue send the html for the pdf along with the page data
                 */
                DocRaptor.prototype.GetData = function () {
                    return [{
                            Key: "HtmlContent",
                            Value: this.BuildHtmlToPdf()
                        }];
                };
                return DocRaptor;
            })();
        })(docraptor = general.docraptor || (general.docraptor = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function DocRaptorModel($sys) {
            return {
                SendEmail: starrez.library.convert.ToBoolean($sys.data('sendemail')),
                ShowButton: starrez.library.convert.ToBoolean($sys.data('showbutton'))
            };
        }
        model.DocRaptorModel = DocRaptorModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var docraptor;
        (function (docraptor) {
            "use strict";
            var GeneratePdf = (function (_super) {
                __extends(GeneratePdf, _super);
                function GeneratePdf(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "DocRaptor";
                    this.Controller = "docraptor";
                    this.Action = "GeneratePdf";
                }
                GeneratePdf.prototype.CallData = function () {
                    var obj = {
                        content: this.o.content,
                        portalPageWidgetID: this.o.portalPageWidgetID
                    };
                    return obj;
                };
                return GeneratePdf;
            })(starrez.library.service.AddInActionCallBase);
            docraptor.GeneratePdf = GeneratePdf;
        })(docraptor = service.docraptor || (service.docraptor = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var starrez;
(function (starrez) {
    var general;
    (function (general) {
        var docusign;
        (function (docusign) {
            "use strict";
            function NotifyWidget(portalPageWidgetID, action, returnUrlKey) {
                var $widgetContainer = $('#DocuSignSignature_' + portalPageWidgetID);
                var $document = $widgetContainer.find('.ui-docusign-document');
                var $notification;
                var signed = false;
                if (action === NotificationAction.Signed && !starrez.library.stringhelper.IsUndefinedOrEmpty(returnUrlKey)) {
                    var $key = $widgetContainer.GetControl('ReturnUrlKey');
                    $key.SRVal(returnUrlKey);
                    $notification = $widgetContainer.find('.ui-signed');
                    signed = true;
                }
                else if (action === NotificationAction.Declined) {
                    $notification = $widgetContainer.find('.ui-declined');
                }
                else {
                    $notification = $widgetContainer.find('.ui-error');
                }
                $.ScrollToWithAnimation($widgetContainer);
                $document.slideUp(function () {
                    $notification.fadeIn();
                    if (signed) {
                        var model = starrez.model.DocuSignWidgetModel($widgetContainer.closest('.ui-docusign'));
                        if (model.SavePageOnDocumentSigned) {
                            portal.page.CurrentPage.SubmitPage();
                            return;
                        }
                        portal.page.CurrentPage.RemoveErrorMessagsByWidgetReference(portalPageWidgetID);
                    }
                });
            }
            docusign.NotifyWidget = NotifyWidget;
            var NotificationAction;
            (function (NotificationAction) {
                NotificationAction[NotificationAction["InvalidKey"] = 0] = "InvalidKey";
                NotificationAction[NotificationAction["Signed"] = 1] = "Signed";
                NotificationAction[NotificationAction["Declined"] = 2] = "Declined";
                NotificationAction[NotificationAction["Error"] = 3] = "Error";
            })(NotificationAction || (NotificationAction = {}));
        })(docusign = general.docusign || (general.docusign = {}));
    })(general = starrez.general || (starrez.general = {}));
})(starrez || (starrez = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function DocuSignWidgetModel($sys) {
            return {
                SavePageOnDocumentSigned: starrez.library.convert.ToBoolean($sys.data('savepageondocumentsigned'))
            };
        }
        model.DocuSignWidgetModel = DocuSignWidgetModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var entryinvitation;
        (function (entryinvitation) {
            var confirmation;
            (function (confirmation) {
                "use strict";
                function InitialiseInvitationConfirmation($container) {
                    new InvitationConfirmation($container);
                }
                confirmation.InitialiseInvitationConfirmation = InitialiseInvitationConfirmation;
                var InvitationConfirmation = (function () {
                    function InvitationConfirmation($container) {
                        this.$container = $container;
                        this.model = starrez.model.EntryInvitationConfirmationModel(this.$container);
                        this.SetupDeclineAction();
                    }
                    InvitationConfirmation.prototype.SetupDeclineAction = function () {
                        var _this = this;
                        var $declineButton = portal.PageElements.$actions.find(".ui-decline-invitation");
                        $declineButton.SRClick(function () {
                            new starrez.service.entryinvitation.DeclineInvitation({
                                hash: $declineButton.data("hash"),
                                pageID: portal.page.CurrentPage.PageID,
                                entryInvitationID: _this.model.EntryInvitationID
                            }).Post().done(function (url) {
                                location.href = url;
                            });
                        });
                    };
                    return InvitationConfirmation;
                })();
            })(confirmation = entryinvitation.confirmation || (entryinvitation.confirmation = {}));
        })(entryinvitation = general.entryinvitation || (general.entryinvitation = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function EntryInvitationConfirmationModel($sys) {
            return {
                EntryInvitationID: Number($sys.data('entryinvitationid'))
            };
        }
        model.EntryInvitationConfirmationModel = EntryInvitationConfirmationModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var entryinvitation;
        (function (entryinvitation) {
            "use strict";
            var CancelInvitation = (function (_super) {
                __extends(CancelInvitation, _super);
                function CancelInvitation(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "EntryInvitation";
                    this.Controller = "entryinvitation";
                    this.Action = "CancelInvitation";
                }
                CancelInvitation.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                CancelInvitation.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        entryInvitationID: this.o.entryInvitationID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return CancelInvitation;
            })(starrez.library.service.AddInActionCallBase);
            entryinvitation.CancelInvitation = CancelInvitation;
            var DeclineInvitation = (function (_super) {
                __extends(DeclineInvitation, _super);
                function DeclineInvitation(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "EntryInvitation";
                    this.Controller = "entryinvitation";
                    this.Action = "DeclineInvitation";
                }
                DeclineInvitation.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                DeclineInvitation.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        entryInvitationID: this.o.entryInvitationID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return DeclineInvitation;
            })(starrez.library.service.AddInActionCallBase);
            entryinvitation.DeclineInvitation = DeclineInvitation;
        })(entryinvitation = service.entryinvitation || (service.entryinvitation = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

/// <reference path="../../../../WebCommon/TypeScriptTypes/starrez.jquery.d.ts" />
/// <reference path="../../../../WebCommon/TypeScriptTypes/jquery/jquery.d.ts" />
var portal;
(function (portal) {
    var entryphotouploadwidget;
    (function (entryphotouploadwidget) {
        "use strict";
        var update = "update";
        var del = "delete";
        function InitEntryPhotoUploadWidget($container) {
            new EntryPhotoUpload($container);
        }
        entryphotouploadwidget.InitEntryPhotoUploadWidget = InitEntryPhotoUploadWidget;
        var EntryPhotoUpload = (function () {
            function EntryPhotoUpload($container) {
                var _this = this;
                this.$container = $container;
                this.widgetID = Number($container.data('portalpagewidgetid'));
                this.$uploadContainer = portal.fileuploader.control.GetUploadContainer($container);
                this.model = starrez.model.EntryPhotoUploadModel($container);
                this.$uploadContainer.data("upload-instance").CustomValidation = function (files) { return _this.ValidateFile(files); };
                portal.page.RegisterWidgetSaveData(this.widgetID, function () { return _this.GetSaveData(); });
            }
            EntryPhotoUpload.prototype.GetSaveData = function () {
                var saveData = new starrez.library.collections.KeyValue();
                var saveStatus = portal.fileuploader.control.GetSaveStatus(this.$uploadContainer);
                if (saveStatus.Update) {
                    saveData.Add(update, saveStatus.Update);
                }
                if (saveStatus.Delete) {
                    saveData.Add(del, saveStatus.Delete);
                }
                var data = saveData.ToArray();
                if (data.length === 0) {
                    return null;
                }
                return data;
            };
            EntryPhotoUpload.prototype.ValidateFile = function (files) {
                var deferred = $.Deferred();
                var isValid = true;
                // Should only ever be 1 file in the list as we don't use multi upload in this case
                if (files.length > 0) {
                    // Validate file extensions
                    var validExtensions = this.model.ValidFileExtensions.split(",");
                    $(validExtensions).each(function (index, elem) { validExtensions[index] = elem.toString().toLowerCase().trim(); });
                    if ($.inArray(files[0].name.split(".").pop().toLowerCase(), validExtensions) < 0) {
                        this.SetWarning(this.model.ValidFileExtensionsErrorMessage + validExtensions.join(", "));
                        isValid = false;
                    }
                    // Validate file size
                    if (files[0].size > this.model.MaxAttachmentBytes) {
                        this.SetWarning(this.model.MaxAttachmentBytesErrorMessage);
                        isValid = false;
                    }
                }
                deferred.resolve(isValid);
                return deferred.promise();
            };
            EntryPhotoUpload.prototype.SetWarning = function (message) {
                var $notification = portal.fileuploader.control.GetNotification(this.$uploadContainer);
                portal.fileuploader.control.ClearNotification($notification);
                portal.fileuploader.control.SetNotification($notification, "uploader-alert-warning", message);
            };
            return EntryPhotoUpload;
        })();
    })(entryphotouploadwidget = portal.entryphotouploadwidget || (portal.entryphotouploadwidget = {}));
})(portal || (portal = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function EntryPhotoUploadModel($sys) {
            return {
                MaxAttachmentBytes: Number($sys.data('maxattachmentbytes')),
                MaxAttachmentBytesErrorMessage: $sys.data('maxattachmentbyteserrormessage'),
                ValidFileExtensions: $sys.data('validfileextensions'),
                ValidFileExtensionsErrorMessage: $sys.data('validfileextensionserrormessage')
            };
        }
        model.EntryPhotoUploadModel = EntryPhotoUploadModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

var starrez;
(function (starrez) {
    var facebookfeed;
    (function (facebookfeed) {
        "use strict";
        function Initialise($container) {
            var facebookSDKInjector;
            if (facebookSDKInjector === undefined) {
                facebookSDKInjector = injectFacebookSDK;
                facebookSDKInjector(document, 'script', 'facebook-jssdk');
            }
        }
        facebookfeed.Initialise = Initialise;
        function injectFacebookSDK(document, tagName, id) {
            var js, fjs = document.getElementsByTagName(tagName)[0];
            if (document.getElementById(id))
                return;
            js = document.createElement(tagName);
            js.id = id;
            js.src = 'https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v3.0';
            fjs.parentNode.insertBefore(js, fjs);
        }
    })(facebookfeed = starrez.facebookfeed || (starrez.facebookfeed = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var filedownloadwidget;
        (function (filedownloadwidget) {
            "use strict";
            function InitialiseFileDownloadSettings($container) {
                var model = starrez.model.WidgetModelBaseModel($container);
                portal.editor.widget.OnWidgetSettingsClose = function () {
                    new starrez.service.filedownload.Cancel({
                        portalPageWidgetID: model.PortalPageWidgetID
                    }).Post();
                };
                portal.editor.widget.OnWidgetSettingsSave = function () {
                    var def = $.Deferred();
                    // Pass in the DisplayOption as the Save function needs to know this to ensure that an invalid option is
                    // not able to be used with non PDF files	
                    new starrez.service.filedownload.Save({
                        portalPageWidgetID: model.PortalPageWidgetID, displayOption: $container.GetControl("DisplayOption").SRVal()
                    }).Post().done(function () {
                        def.resolve();
                    });
                    return def.promise();
                };
            }
            filedownloadwidget.InitialiseFileDownloadSettings = InitialiseFileDownloadSettings;
            function InitialiseFileDownload($container) {
                // This will setup the PDF Popup display
                $container.find(".ui-colorbox-iframe").colorbox({ iframe: true, innerWidth: '80%', innerHeight: '80%' });
            }
            filedownloadwidget.InitialiseFileDownload = InitialiseFileDownload;
        })(filedownloadwidget = general.filedownloadwidget || (general.filedownloadwidget = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var filedownload;
        (function (filedownload) {
            "use strict";
            var Cancel = (function (_super) {
                __extends(Cancel, _super);
                function Cancel(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "FileDownload";
                    this.Controller = "filedownload";
                    this.Action = "Cancel";
                }
                Cancel.prototype.CallData = function () {
                    var obj = {
                        portalPageWidgetID: this.o.portalPageWidgetID
                    };
                    return obj;
                };
                return Cancel;
            })(starrez.library.service.AddInActionCallBase);
            filedownload.Cancel = Cancel;
            var Save = (function (_super) {
                __extends(Save, _super);
                function Save(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "FileDownload";
                    this.Controller = "filedownload";
                    this.Action = "Save";
                }
                Save.prototype.CallData = function () {
                    var obj = {
                        displayOption: this.o.displayOption,
                        portalPageWidgetID: this.o.portalPageWidgetID
                    };
                    return obj;
                };
                return Save;
            })(starrez.library.service.AddInActionCallBase);
            filedownload.Save = Save;
        })(filedownload = service.filedownload || (service.filedownload = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var fileuploadwidget;
    (function (fileuploadwidget) {
        "use strict";
        function InitFileUploadWidget($container) {
            new FileUpload($container);
        }
        fileuploadwidget.InitFileUploadWidget = InitFileUploadWidget;
        var FileUpload = (function () {
            function FileUpload($container) {
                var _this = this;
                this.$container = $container;
                this.$uploadContainer = portal.fileuploader.control.GetUploadContainer($container);
                this.fileUploadModel = starrez.model.FileUploadModel($container);
                this.$uploadedFilesTableDiv = $container.find(".ui-uploaded-files-table");
                this.uploadedFilesTable = starrez.tablesetup.CreateTableManager(this.$container.find(".ui-uploaded-files-table table"), $("body"))[0];
                this.files = [];
                this.$tablebody = this.uploadedFilesTable.$table.find("tbody");
                this.widgetID = Number($container.data("portalpagewidgetid"));
                this.$maximumNumberOfFilesError = $container.find(".ui-maximum-attachments-error");
                this.$maximumFileSizeError = $container.find(".ui-filesize-error");
                this.$notification = portal.fileuploader.control.GetNotification(this.$uploadContainer);
                this.AttachDeleteFileEvents();
                this.AttachUploadedFilesEvents();
                var fileUpload = this.$uploadContainer.data("upload-instance");
                if (starrez.library.utils.IsNotNullUndefined(fileUpload)) {
                    fileUpload.AutomaticallySubmitFiles = true;
                    fileUpload.CustomValidation = function (files) { return _this.FileUploadValidate(files); };
                    fileUpload.LoadingText = this.fileUploadModel.UploadLoadingMessage;
                    this.$uploadContainer.on("upload-success", function (e, info) {
                        _this.RefreshTable();
                    });
                }
            }
            FileUpload.prototype.RefreshTable = function () {
                var _this = this;
                var hash = this.$uploadedFilesTableDiv.data("hash");
                new starrez.service.fileupload.GetUploadedFileRow({
                    widgetID: this.widgetID,
                    existingQuery: window.location.search.substr(1),
                    hash: hash
                }).Post().done(function (results) {
                    if (!_this.$tablebody.isFound()) {
                        _this.uploadedFilesTable.$table.append("<tbody></tbody>");
                        _this.$tablebody = _this.uploadedFilesTable.$table.find("tbody");
                    }
                    _this.$tablebody.html(results);
                    _this.AttachUploadedFilesEvents();
                });
            };
            FileUpload.prototype.AttachUploadedFilesEvents = function () {
                var $tableRows = this.$tablebody.find("tr");
                if ($tableRows.length === this.fileUploadModel.MaximumNumberOfFiles) {
                    this.$container.find(".ui-file-upload-label").hide();
                    this.$uploadContainer.hide();
                    this.$maximumNumberOfFilesError.show();
                }
                else {
                    this.$container.find(".ui-file-upload-label").show();
                    this.$uploadContainer.show();
                    this.$maximumNumberOfFilesError.hide();
                }
                if ($tableRows.length > 0) {
                    this.$uploadedFilesTableDiv.show();
                    this.uploadedFilesTable = starrez.tablesetup.CreateTableManager(this.$container.find(".ui-uploaded-files-table table"), $("body"))[0];
                }
                else {
                    this.$uploadedFilesTableDiv.hide();
                }
            };
            FileUpload.prototype.AttachDeleteFileEvents = function () {
                var _this = this;
                this.uploadedFilesTable.$table.SRClickDelegate("delete", ".ui-btn-delete", function (e) {
                    portal.fileuploader.control.ClearNotification(_this.$notification);
                    portal.ConfirmAction(_this.fileUploadModel.DeleteFileConfirmText, "Delete File").done(function () {
                        var $row = $(e.currentTarget).closest("tr");
                        var id = Number($row.data("id"));
                        var hash = $row.data("deletehash").toString();
                        new starrez.service.fileupload.DeleteFile({
                            recordAttachmentID: id,
                            hash: hash
                        }).Post().done(function (success) {
                            if (success) {
                                _this.SetNotification(_this.fileUploadModel.DeleteFileSuccessMessage, false);
                                _this.uploadedFilesTable.RemoveRows($row);
                            }
                            else {
                                _this.SetNotification(_this.fileUploadModel.DeleteFileErrorMessage, true);
                            }
                            _this.AttachUploadedFilesEvents();
                        });
                        portal.fileuploader.control.ClearNotification(_this.$notification);
                    });
                });
            };
            FileUpload.prototype.FileUploadValidate = function (files) {
                portal.fileuploader.control.ClearNotification(this.$notification);
                var deferred = $.Deferred();
                var fileData = [];
                var isValid = true;
                var isNotificationDone;
                var numberOfFiles = this.$tablebody.find("tr").length + files.length;
                if (numberOfFiles > this.fileUploadModel.MaximumNumberOfFiles) {
                    this.SetNotification(this.fileUploadModel.MaximumNumberOfFilesErrorMessage);
                    isNotificationDone = true;
                    isValid = false;
                }
                else {
                    for (var x = 0; x < files.length; x++) {
                        if (files[x].size > this.fileUploadModel.MaxAttachmentBytes) {
                            this.SetNotification(this.fileUploadModel.MaxAttachmentBytesErrorMessage);
                            isNotificationDone = true;
                            isValid = false;
                            break;
                        }
                        var ext = files[x].name.split(".").pop();
                        var isNamevalid = false;
                        $.each(this.fileUploadModel.ValidFileExtensions.split(","), (function (key, value) {
                            if (starrez.library.stringhelper.Equals(value.trim(), ext, true)) {
                                isNamevalid = true;
                                return false;
                            }
                        }));
                        if (!isNamevalid && !isNotificationDone) {
                            this.SetNotification(this.fileUploadModel.AttachmentTypeErrorMessage + this.fileUploadModel.ValidFileExtensions.split(",").join(", "));
                            isValid = false;
                            break;
                        }
                        else {
                            fileData.push({
                                Key: files[x].name,
                                Value: files[x].size
                            });
                        }
                    }
                }
                if (isValid) {
                    deferred.resolve(true);
                }
                else {
                    deferred.reject(false);
                }
                return deferred.promise();
            };
            FileUpload.prototype.SetNotification = function (message, isWarning) {
                if (isWarning === void 0) { isWarning = true; }
                var warningClass = "uploader-alert-warning";
                var infoClass = "uploader-alert-info";
                //Make sure $notification doesn't have any warning or info class
                this.$notification.removeClass(warningClass + " " + infoClass);
                var alertClass;
                if (isWarning) {
                    alertClass = warningClass;
                }
                else {
                    alertClass = infoClass;
                }
                portal.fileuploader.control.SetNotification(this.$notification, alertClass, message);
            };
            return FileUpload;
        })();
    })(fileuploadwidget = portal.fileuploadwidget || (portal.fileuploadwidget = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function FileUploadModel($sys) {
            return {
                AttachmentTypeErrorMessage: $sys.data('attachmenttypeerrormessage'),
                DeleteFileConfirmText: $sys.data('deletefileconfirmtext'),
                DeleteFileErrorMessage: $sys.data('deletefileerrormessage'),
                DeleteFileSuccessMessage: $sys.data('deletefilesuccessmessage'),
                MaxAttachmentBytes: Number($sys.data('maxattachmentbytes')),
                MaxAttachmentBytesErrorMessage: $sys.data('maxattachmentbyteserrormessage'),
                MaximumNumberOfFiles: Number($sys.data('maximumnumberoffiles')),
                MaximumNumberOfFilesErrorMessage: $sys.data('maximumnumberoffileserrormessage'),
                MinimumNumberOfFiles: Number($sys.data('minimumnumberoffiles')),
                MinimumNumberOfFilesErrorMessage: $sys.data('minimumnumberoffileserrormessage'),
                UploadLoadingMessage: $sys.data('uploadloadingmessage'),
                ValidFileExtensions: $sys.data('validfileextensions')
            };
        }
        model.FileUploadModel = FileUploadModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var fileupload;
        (function (fileupload) {
            "use strict";
            var DeleteFile = (function (_super) {
                __extends(DeleteFile, _super);
                function DeleteFile(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "FileUpload";
                    this.Controller = "fileupload";
                    this.Action = "DeleteFile";
                }
                DeleteFile.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                DeleteFile.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        recordAttachmentID: this.o.recordAttachmentID
                    };
                    return obj;
                };
                return DeleteFile;
            })(starrez.library.service.AddInActionCallBase);
            fileupload.DeleteFile = DeleteFile;
            var GetUploadedFileRow = (function (_super) {
                __extends(GetUploadedFileRow, _super);
                function GetUploadedFileRow(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "FileUpload";
                    this.Controller = "fileupload";
                    this.Action = "GetUploadedFileRow";
                }
                GetUploadedFileRow.prototype.CallData = function () {
                    var obj = {
                        existingQuery: this.o.existingQuery
                    };
                    return obj;
                };
                GetUploadedFileRow.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        widgetID: this.o.widgetID
                    };
                    return obj;
                };
                return GetUploadedFileRow;
            })(starrez.library.service.AddInActionCallBase);
            fileupload.GetUploadedFileRow = GetUploadedFileRow;
            var UploadFiles = (function (_super) {
                __extends(UploadFiles, _super);
                function UploadFiles(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "FileUpload";
                    this.Controller = "fileupload";
                    this.Action = "UploadFiles";
                }
                UploadFiles.prototype.CallData = function () {
                    var obj = {
                        existingQuery: this.o.existingQuery,
                        pageID: this.o.pageID,
                        widgetID: this.o.widgetID
                    };
                    return obj;
                };
                return UploadFiles;
            })(starrez.library.service.AddInActionCallBase);
            fileupload.UploadFiles = UploadFiles;
        })(fileupload = service.fileupload || (service.fileupload = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var image;
        (function (image) {
            "use strict";
            function InitSettingsEditor($container) {
                new ImageSettingsEditor($container);
            }
            image.InitSettingsEditor = InitSettingsEditor;
            var ImageSettingsEditor = (function () {
                function ImageSettingsEditor($container) {
                    var _this = this;
                    this.model = starrez.model.ImageEditorModel($container);
                    this.$uploadContainer = portal.fileuploader.control.GetUploadContainer($container);
                    this.portalPageWidgetID = Number($container.data("portalpagewidgetid"));
                    this.fileUpload = portal.fileuploader.control.GetUploadInstance($container);
                    this.fileUpload.CustomValidation = function (files) { return _this.ValidateFiles(files); };
                    portal.editor.widget.OnWidgetSettingsSave = function () {
                        var def = $.Deferred();
                        var call = new starrez.service.image.Save({
                            portalPageWidgetID: _this.portalPageWidgetID,
                            scaledHeight: Number($container.GetControl("ScaledHeight").SRVal())
                        });
                        call.Post().done(function () {
                            def.resolve();
                        });
                        return def.promise();
                    };
                }
                ImageSettingsEditor.prototype.ValidateFiles = function (files) {
                    var deferred = $.Deferred();
                    var isValid = true;
                    // Should only ever be 1 file in the list as we don't use multi upload in this case
                    if (files.length > 0) {
                        // Validate file extensions
                        var validExtensions = ["jpg", "jpeg", "jpe", "gif", "png", "bmp", "svg"];
                        var extension = files[0].name.split(".").pop().toLowerCase();
                        if (validExtensions.indexOf(extension) == -1) {
                            portal.fileuploader.control.SetNotification(portal.fileuploader.control.GetNotification(this.$uploadContainer), "uploader-alert-warning", "Invalid file type. File must be one of " + validExtensions.join(", ") + ". Filename was " + files[0].name + ".");
                            isValid = false;
                        }
                        // Validate file size
                        if (files[0].size > this.model.MaxAttachmentLengthBytes) {
                            portal.fileuploader.control.SetNotification(portal.fileuploader.control.GetNotification(this.$uploadContainer), "uploader-alert-warning", "Uploaded file is too large. Maximum allowed size is " + this.model.MaxAttachmentLengthBytes + " bytes. File size is " + files[0].size + " bytes.");
                            isValid = false;
                        }
                    }
                    deferred.resolve(isValid);
                    return deferred.promise();
                };
                return ImageSettingsEditor;
            })();
            function InitializeImageWidget($container) {
                var model = starrez.model.ImageModel($container);
                if (model.Is360Image && !portal.editor.IsInLiveEditMode) {
                    var mousemove = true;
                    var navbar = [
                        'autorotate',
                        'zoom',
                        'download',
                        'caption',
                        'gyroscope',
                        'fullscreen'
                    ];
                    if (!starrez.library.stringhelper.IsUndefinedOrEmpty(model.HyperLink)) {
                        mousemove = false;
                        navbar = false;
                    }
                    var photoSphereViewer = new PhotoSphereViewer({
                        panorama: model.ImageUrl,
                        container: $container.find('.ui-photo-sphere-viewer').get(0),
                        caption: model.AltText,
                        mousemove: mousemove,
                        mousewheel: false,
                        navbar: navbar
                    });
                }
            }
            image.InitializeImageWidget = InitializeImageWidget;
        })(image = general.image || (general.image = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function ImageModel($sys) {
            return {
                AltText: $sys.data('alttext'),
                HyperLink: $sys.data('hyperlink'),
                HyperLinkTarget: $sys.data('hyperlinktarget'),
                ImageUrl: $sys.data('imageurl'),
                Is360Image: starrez.library.convert.ToBoolean($sys.data('is360image'))
            };
        }
        model.ImageModel = ImageModel;
        function ImageEditorModel($sys) {
            return {
                MaxAttachmentLengthBytes: Number($sys.data('maxattachmentlengthbytes'))
            };
        }
        model.ImageEditorModel = ImageEditorModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var image;
        (function (image) {
            "use strict";
            var Save = (function (_super) {
                __extends(Save, _super);
                function Save(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Image";
                    this.Controller = "image";
                    this.Action = "Save";
                }
                Save.prototype.CallData = function () {
                    var obj = {
                        portalPageWidgetID: this.o.portalPageWidgetID,
                        scaledHeight: this.o.scaledHeight
                    };
                    return obj;
                };
                return Save;
            })(starrez.library.service.AddInActionCallBase);
            image.Save = Save;
        })(image = service.image || (service.image = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

/// <reference path="../../../../WebCommon/TypeScriptTypes/lib.d.ts" />
var portal;
(function (portal) {
    var general;
    (function (general) {
        var inventory;
        (function (inventory) {
            "use strict";
            function InitialiseInventoryList($container) {
                $container.find(".ui-inventory-review").SRClick(function (e) {
                    var $button = $(e.currentTarget);
                    var inspectionID = Number($button.closest("tr").data("roomspaceinventoryinspection"));
                    new starrez.service.inventory.GetInventoryDetailsUrl({
                        pageID: portal.page.CurrentPage.PageID,
                        inspectionID: inspectionID
                    }).Post().done(function (url) {
                        location.href = url;
                    });
                });
            }
            inventory.InitialiseInventoryList = InitialiseInventoryList;
            function InitialiseDetailPage($container) {
                new InventoryInspectionDetails($container);
            }
            inventory.InitialiseDetailPage = InitialiseDetailPage;
            var InventoryInspectionDetails = (function () {
                function InventoryInspectionDetails($container) {
                    this.$container = $container;
                    this.pageModel = starrez.model.InventoryInspectionDetailsModel($container);
                    this.AttachEvents();
                }
                InventoryInspectionDetails.prototype.AttachEvents = function () {
                    var _this = this;
                    this.$container.find(".ui-btn-more").SRClick(function (e) {
                        starrez.library.utils.SafeStopPropagation(e);
                        var $button = $(e.currentTarget);
                        var $inventoryItem = $button.closest(".ui-inventory-item");
                        _this.ToggleInformation($button, $inventoryItem);
                    });
                    this.$container.find(".ui-accept").SRClick(function (e) {
                        _this.ToggleAccepted(true, $(e.currentTarget));
                    });
                    this.$container.find(".ui-reject").SRClick(function (e) {
                        _this.ToggleAccepted(false, $(e.currentTarget));
                    });
                    portal.PageElements.$actions.find(".ui-btn-save-review").SRClick(function () {
                        var reviewItems = [];
                        var allAccepted = true;
                        _this.$container.find(".ui-inventory-item").each(function (index, element) {
                            var $item = $(element);
                            var accepted = starrez.library.convert.ToBoolean($item.data("accepted"));
                            allAccepted = allAccepted && accepted;
                            reviewItems.push({
                                Accepted: accepted,
                                ReviewComments: $item.GetControl("ReviewComments").SRVal(),
                                RoomSpaceInventoryInspectionItemID: $item.data("roomspaceinventoryinspectionitemid")
                            });
                        });
                        if (_this.pageModel.ShowNotAcceptedConfirmation && !allAccepted) {
                            portal.ConfirmAction(_this.pageModel.NotAcceptedConfirmationMessage, _this.pageModel.NotAcceptedConfirmationTitle).done(function () {
                                _this.SaveReview(_this.$container, reviewItems);
                            });
                        }
                        else {
                            _this.SaveReview(_this.$container, reviewItems);
                        }
                    });
                };
                InventoryInspectionDetails.prototype.ToggleAccepted = function (accepted, $button) {
                    var $inventoryItem = $button.closest(".ui-inventory-item");
                    var $acceptButton = $inventoryItem.find(".ui-accept");
                    var $rejectButton = $inventoryItem.find(".ui-reject");
                    $inventoryItem.data("accepted", accepted);
                    if (accepted) {
                        $rejectButton.AriaShow();
                        $rejectButton.show();
                        $rejectButton.focus();
                        $acceptButton.AriaHide();
                        $acceptButton.hide();
                    }
                    else {
                        $acceptButton.AriaShow();
                        $acceptButton.show();
                        $acceptButton.focus();
                        $rejectButton.AriaHide();
                        $rejectButton.hide();
                    }
                };
                InventoryInspectionDetails.prototype.ToggleInformation = function ($button, $inventoryItem) {
                    var $details = $inventoryItem.find(".ui-toggle-show");
                    if ($details.is(":visible")) {
                        $button.text(this.pageModel.MoreLinkText);
                        $button.removeClass("shown");
                    }
                    else {
                        $button.text(this.pageModel.LessLinkText);
                        $button.addClass("shown");
                    }
                    $details.slideToggle();
                };
                InventoryInspectionDetails.prototype.SaveReview = function ($container, reviewItems) {
                    var _this = this;
                    if (reviewItems.length > 0) {
                        new starrez.service.inventory.SaveReview({
                            inspectionID: this.pageModel.RoomSpaceInventoryInspectionID,
                            pageID: portal.page.CurrentPage.PageID,
                            items: reviewItems
                        }).Post().done(function (success) {
                            if (success) {
                                portal.page.CurrentPage.SubmitPage();
                            }
                            else {
                                portal.page.CurrentPage.SetErrorMessage(_this.pageModel.SaveReviewErrorMessage);
                            }
                        }).fail(function () {
                            portal.page.CurrentPage.SetErrorMessage(_this.pageModel.SaveReviewErrorMessage);
                        });
                    }
                };
                return InventoryInspectionDetails;
            })();
        })(inventory = general.inventory || (general.inventory = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function InventoryInspectionDetailsModel($sys) {
            return {
                AcceptAllOnSave: starrez.library.convert.ToBoolean($sys.data('acceptallonsave')),
                AcceptButtonText: $sys.data('acceptbuttontext'),
                AcceptedButtonText: $sys.data('acceptedbuttontext'),
                LessLinkText: $sys.data('lesslinktext'),
                MoreLinkText: $sys.data('morelinktext'),
                NotAcceptedConfirmationMessage: $sys.data('notacceptedconfirmationmessage'),
                NotAcceptedConfirmationTitle: $sys.data('notacceptedconfirmationtitle'),
                ReadOnly: starrez.library.convert.ToBoolean($sys.data('readonly')),
                RoomSpaceInventoryInspectionID: Number($sys.data('roomspaceinventoryinspectionid')),
                SaveReviewErrorMessage: $sys.data('savereviewerrormessage'),
                ShowAcceptButton: starrez.library.convert.ToBoolean($sys.data('showacceptbutton')),
                ShowNotAcceptedConfirmation: starrez.library.convert.ToBoolean($sys.data('shownotacceptedconfirmation'))
            };
        }
        model.InventoryInspectionDetailsModel = InventoryInspectionDetailsModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var inventory;
        (function (inventory) {
            "use strict";
            var GetInventoryDetailsUrl = (function (_super) {
                __extends(GetInventoryDetailsUrl, _super);
                function GetInventoryDetailsUrl(o) {
                    _super.call(this);
                    this.o = o;
                    this.Area = "Inventory";
                    this.Controller = "inventory";
                    this.Action = "GetInventoryDetailsUrl";
                }
                GetInventoryDetailsUrl.prototype.CallData = function () {
                    var obj = {
                        inspectionID: this.o.inspectionID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return GetInventoryDetailsUrl;
            })(starrez.library.service.ActionCallBase);
            inventory.GetInventoryDetailsUrl = GetInventoryDetailsUrl;
            var SaveReview = (function (_super) {
                __extends(SaveReview, _super);
                function SaveReview(o) {
                    _super.call(this);
                    this.o = o;
                    this.Area = "Inventory";
                    this.Controller = "inventory";
                    this.Action = "SaveReview";
                }
                SaveReview.prototype.CallData = function () {
                    var obj = {
                        inspectionID: this.o.inspectionID,
                        items: this.o.items,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return SaveReview;
            })(starrez.library.service.ActionCallBase);
            inventory.SaveReview = SaveReview;
        })(inventory = service.inventory || (service.inventory = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var starrez;
(function (starrez) {
    var livechat;
    (function (livechat) {
        "use strict";
        function Initialise($container) {
            var model = starrez.model.LiveChatModel($container);
        }
        livechat.Initialise = Initialise;
    })(livechat = starrez.livechat || (starrez.livechat = {}));
})(starrez || (starrez = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function LiveChatModel($sys) {
            return {};
        }
        model.LiveChatModel = LiveChatModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var MailMerge;
        (function (MailMerge) {
            "use strict";
            function InitMailMergeWidget($container) {
                new MailMergeModel($container);
            }
            MailMerge.InitMailMergeWidget = InitMailMergeWidget;
            var MailMergeModel = (function () {
                function MailMergeModel($container) {
                    this.model = starrez.model.MailMergeModel($container);
                    this.$container = $container;
                    this.SetupHasDownloadedFlagEvent();
                    this.DisplayInlineTemplate();
                }
                MailMergeModel.prototype.SetupHasDownloadedFlagEvent = function () {
                    var _this = this;
                    var downloadTemplate = this.$container.find(".ui-download-mailmerge");
                    // The PDF download is a link, so that will get downloaded without the need for any extra code here.
                    // We still need to set the HasDownloadedFile hidden form field
                    // to mark the PDF file as having been downloaded.
                    downloadTemplate.SRClick(function () {
                        var hasDownloadedFile = _this.$container.GetControl("HasDownloadedFile");
                        hasDownloadedFile.SRVal(true);
                    });
                };
                MailMergeModel.prototype.DisplayInlineTemplate = function () {
                    var $mailMergeView = this.$container.find(".ui-mailmergeview");
                    var call = new starrez.service.mailmerge.GetInlineDocument({
                        portalPageWidgetID: this.$container.data('portalpagewidgetid'),
                        hash: $mailMergeView.data("hash")
                    });
                    call.Request({
                        ActionVerb: starrez.library.service.RequestType.Post,
                        ShowLoading: false
                    }).done(function (result) {
                        $mailMergeView.html(result);
                    });
                };
                return MailMergeModel;
            })();
        })(MailMerge = general.MailMerge || (general.MailMerge = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function MailMergeModel($sys) {
            return {
                MailMergeTemplate: Number($sys.data('mailmergetemplate'))
            };
        }
        model.MailMergeModel = MailMergeModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var mailmerge;
        (function (mailmerge) {
            "use strict";
            var DownloadMailMergeDocument = (function (_super) {
                __extends(DownloadMailMergeDocument, _super);
                function DownloadMailMergeDocument(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "MailMerge";
                    this.Controller = "mailmerge";
                    this.Action = "DownloadMailMergeDocument";
                }
                DownloadMailMergeDocument.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                DownloadMailMergeDocument.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        portalPageWidgetID: this.o.portalPageWidgetID
                    };
                    return obj;
                };
                return DownloadMailMergeDocument;
            })(starrez.library.service.AddInActionCallBase);
            mailmerge.DownloadMailMergeDocument = DownloadMailMergeDocument;
            var GetInlineDocument = (function (_super) {
                __extends(GetInlineDocument, _super);
                function GetInlineDocument(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "MailMerge";
                    this.Controller = "mailmerge";
                    this.Action = "GetInlineDocument";
                }
                GetInlineDocument.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                GetInlineDocument.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        portalPageWidgetID: this.o.portalPageWidgetID
                    };
                    return obj;
                };
                return GetInlineDocument;
            })(starrez.library.service.AddInActionCallBase);
            mailmerge.GetInlineDocument = GetInlineDocument;
        })(mailmerge = service.mailmerge || (service.mailmerge = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var mealplanselection;
        (function (mealplanselection) {
            "use strict";
            function InitMealPlanSelectionWidget($container) {
                var portalPageWidgetID = Number($container.data('portalpagewidgetid'));
                $container.data('MealPlanSelectionWidget', new MealPlanSelectionWidget(portalPageWidgetID, $container));
            }
            mealplanselection.InitMealPlanSelectionWidget = InitMealPlanSelectionWidget;
            // Copied from FormWidget. This should be made reusable.
            var MealPlanSelectionWidget = (function () {
                function MealPlanSelectionWidget(portalPageWidgetID, $container) {
                    var _this = this;
                    this.portalPageWidgetID = portalPageWidgetID;
                    this.$container = $container;
                    portal.page.RegisterWidgetSaveData(portalPageWidgetID, function () { return _this.GetSaveData(); });
                }
                MealPlanSelectionWidget.prototype.GetSaveData = function () {
                    var saveData = new starrez.library.collections.KeyValue();
                    var $allControls = this.$container.GetAllControls();
                    $allControls.each(function (index, element) {
                        var $control = $(element);
                        if ($control.HasChanged()) {
                            var fieldID = $control.closest('li').data('id').toString();
                            var value = $control.SRVal();
                            saveData.Add(fieldID, value);
                        }
                    });
                    var data = saveData.ToArray();
                    if (data.length === 0) {
                        return null;
                    }
                    return data;
                };
                return MealPlanSelectionWidget;
            })();
        })(mealplanselection = general.mealplanselection || (general.mealplanselection = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var messaging;
        (function (messaging) {
            "use strict";
            var UnreadUiClass = "ui-unread";
            var UnreadClasses = UnreadUiClass + " unread";
            var SelectedClass = "selected";
            var MessagingNavBarIconName = "MessagingNavigationBarIcon";
            var MessageType;
            (function (MessageType) {
                MessageType[MessageType["New"] = 0] = "New";
                MessageType[MessageType["Reply"] = 1] = "Reply";
                MessageType[MessageType["Forward"] = 2] = "Forward";
            })(MessageType || (MessageType = {}));
            ;
            /**
                * Adds disabled fields to save page function
                * @param $container
                */
            function InitComposeMessage($container) {
                portal.page.CurrentPage.FetchAdditionalData = function () {
                    return {
                        Subject: $container.GetControl("Subject").SRVal(),
                        Recipient: $container.GetControl("Recipient").SRVal()
                    };
                };
            }
            messaging.InitComposeMessage = InitComposeMessage;
            /**
                * On message click, redirects to the messaging module with the info of the selected
                * message. This allows the messaging page to show the message thread on load.
                * @param $container the messaging widget container
                */
            function InitialiseWidget($container) {
                $container.SRClickDelegate("convo-click", ".ui-widget-conversation", function (e) {
                    var $message = $(e.currentTarget);
                    var model = starrez.model.MessagingWidgetModel($container);
                    location.href = model.MessagingProcessUrl
                        + "#subject=" + encodeURIComponent($message.find(".ui-subject").text())
                        + "&correspondentID=" + encodeURIComponent($message.data("correspondentid"));
                });
            }
            messaging.InitialiseWidget = InitialiseWidget;
            function InitialisePage($container) {
                messaging.Model = new MessagingPage($container);
            }
            messaging.InitialisePage = InitialisePage;
            var Conversation = (function () {
                function Conversation() {
                }
                return Conversation;
            })();
            var MessagingPage = (function () {
                function MessagingPage($container) {
                    this.$container = $container;
                    this.$conversationsContainer = this.$container.find(".ui-conversations-container");
                    this.LoadConversations(1);
                    this.$messagesContainer = this.$container.find(".ui-messages-container");
                    var $selectedConvo = this.FindSelectedConvoOnPage(this.GetSelectedConvoFromHash());
                    if (starrez.library.utils.IsNotNullUndefined($selectedConvo)) {
                        $selectedConvo.click();
                    }
                    if (!portal.mobile.IsInMobileResolution()) {
                        var $firstConvo = this.$container.find(".ui-page-conversation").first();
                        if ($firstConvo.isFound()) {
                            $firstConvo.click();
                        }
                    }
                }
                MessagingPage.prototype.LoadConversations = function (currentPageNumber) {
                    var _this = this;
                    this.currentPageNumber = currentPageNumber;
                    new starrez.service.messaging.GetPagedConversations({
                        pageID: portal.page.CurrentPage.PageID,
                        currentPageNumber: this.currentPageNumber
                    }).Post().done(function (result) {
                        _this.$conversationsContainer.html($.toHTML(result));
                        portal.actionpanel.control.AutoAdjustActionPanelHeights(_this.$container);
                        _this.AttachConversationClick();
                        portal.paging.AttachPagingClickEvent(_this, _this.$conversationsContainer, _this.LoadConversations);
                    });
                };
                /**
                    * If a hash is supplied in the Url then the it is extracted and a Conversation is created
                    * and returned. This will be set when linking from the messaging widget, or from an email
                    * that is sent to the student.
                    */
                MessagingPage.prototype.GetSelectedConvoFromHash = function () {
                    var convo = new Conversation;
                    // removes the '#' from the start of the string. Then splits on the '&', then again on the '='
                    location.hash.substring(1).split("&").forEach(function (pair) {
                        var values = pair.split("=");
                        convo[values[0]] = decodeURIComponent(values[1]);
                    });
                    return convo;
                };
                /**
                    * Finds the conversation element on the dom based on the supplied conversation's
                    * correspondenceID and subject
                    * @param conversation the Conversation to find
                    */
                MessagingPage.prototype.FindSelectedConvoOnPage = function (conversation) {
                    var $allConvos = this.$container.find(".ui-page-conversation");
                    if (starrez.library.utils.IsNotNullUndefined(conversation.correspondentID) && starrez.library.utils.IsNotNullUndefined(conversation.subject)) {
                        // loop through all conversations to find the matching element
                        for (var i = 0; i < $allConvos.length; i++) {
                            var $convo = $($allConvos[i]);
                            var correspondentMatch = Number($convo.data("correspondentid")) === Number(conversation.correspondentID);
                            var subjectMatch = starrez.library.stringhelper.Equals($convo.find(".ui-subject").text(), conversation.subject, false);
                            if (correspondentMatch && subjectMatch) {
                                return $convo;
                            }
                        }
                    }
                    return null;
                };
                MessagingPage.prototype.AttachConversationClick = function () {
                    var _this = this;
                    var $convos = this.$container.find(".ui-page-conversation");
                    $convos.SRClick(function (e) {
                        var $convo = $(e.currentTarget);
                        var $innerContainer = _this.$container.find(".ui-messaging-inner-container");
                        _this.Highlight($convo);
                        var call = new starrez.service.messaging.GetConversationMessages({
                            pageID: portal.page.CurrentPage.PageID,
                            subject: $convo.find(".ui-subject").text(),
                            otherEntryID: Number($convo.data("correspondentid"))
                        }).Request({ ActionVerb: starrez.library.service.RequestType.Post, UseStandardError: false });
                        call.done(function (html) {
                            $convo.removeClass(UnreadClasses);
                            $innerContainer.addClass(SelectedClass);
                            $convo.find(".ui-new-message-count").SRHide();
                            _this.$messagesContainer.html($.toHTML(html));
                            _this.MarkMessagesRead();
                            _this.AttachMessageHeaderClick();
                            _this.AttachMessageReplyClick();
                            _this.AttachMessageForwardClick();
                            _this.AttachMessageBackClick();
                            _this.$messagesContainer.find(".ui-message-subject").focus();
                            // scroll to top
                            portal.page.CurrentPage.ScrollToTop();
                        }).fail(function () {
                            portal.page.CurrentPage.SetErrorMessage(starrez.model.MessagingPageModel(_this.$container).MessageLoadingErrorMessage);
                        });
                    });
                    starrez.keyboard.AttachSelectEvent($convos, function (e) { $(e.target).click(); });
                };
                /**
                    * When in mobile mode, hooks up the back link to take you to the list of conversations
                    */
                MessagingPage.prototype.AttachMessageBackClick = function () {
                    var _this = this;
                    var $backButton = this.$messagesContainer.find(".ui-message-back-link");
                    $backButton.SRClick(function (e) {
                        _this.$container.find(".ui-messaging-inner-container").removeClass(SelectedClass);
                    });
                    starrez.keyboard.AttachSelectEvent($backButton, function (e) { $(e.target).click(); });
                };
                /**
                    * Finds all unread messages, retrieves the correspondenceIDs and marks them as "read"
                    */
                MessagingPage.prototype.MarkMessagesRead = function () {
                    var _this = this;
                    var $unreadMessages = this.$messagesContainer.find(".ui-message." + UnreadUiClass);
                    // get array of correspondence IDs
                    var unreadCorrespondenceIDs = $unreadMessages.map(function (index, msg) {
                        return Number($(msg).data("correspondenceid"));
                    }).toArray();
                    if (unreadCorrespondenceIDs.length > 0) {
                        var call = new starrez.service.messaging.MarkMessagesRead({
                            correspondenceIDs: unreadCorrespondenceIDs
                        }).Request({ ActionVerb: starrez.library.service.RequestType.Post, UseStandardError: false });
                        call.done(function (totalUnreadRemaining) {
                            // update the navbar with the new unread badge count
                            portal.navigation.NavigationBar.UpdateNavIconBadgeCount(MessagingNavBarIconName, totalUnreadRemaining);
                        }).fail(function () {
                            portal.page.CurrentPage.SetErrorMessage(starrez.model.MessagingPageModel(_this.$container).MarkingAsReadErrorMessage);
                        });
                    }
                };
                MessagingPage.prototype.AttachMessageHeaderClick = function () {
                    var $collapseButton = this.$messagesContainer.find(".ui-collapse");
                    $collapseButton.SRClick(function (e) {
                        $(e.currentTarget).closest(".ui-message").toggleClass("collapsed");
                    });
                };
                MessagingPage.prototype.AttachMessageReplyClick = function () {
                    var _this = this;
                    var $replyButton = this.$messagesContainer.find(".ui-reply");
                    $replyButton.SRClick(function (e) {
                        _this.RespondToMessage(e, MessageType.Reply);
                    });
                };
                MessagingPage.prototype.AttachMessageForwardClick = function () {
                    var _this = this;
                    var $forwardButton = this.$messagesContainer.find(".ui-forward");
                    $forwardButton.SRClick(function (e) {
                        _this.RespondToMessage(e, MessageType.Forward);
                    });
                };
                MessagingPage.prototype.RespondToMessage = function (e, type) {
                    var $msg = $(e.currentTarget).closest(".ui-message");
                    var correspondenceID = Number($msg.data("correspondenceid"));
                    var hash = $msg.data("hash").toString();
                    new starrez.service.messaging.GetSendMessageUrl({
                        correspondenceID: correspondenceID,
                        pageID: portal.page.CurrentPage.PageID,
                        hash: hash,
                        messageType: type
                    }).Post().done(function (url) {
                        location.href = url;
                    });
                    starrez.library.utils.SafeStopPropagation(e);
                };
                MessagingPage.prototype.Highlight = function ($convo) {
                    this.$container.find(".ui-highlight").SRUnHighlight();
                    $convo.SRHighlight();
                };
                return MessagingPage;
            })();
        })(messaging = general.messaging || (general.messaging = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function ComposeMessageModel($sys) {
            return {
                Body: $sys.data('body'),
                MessageType: $sys.data('messagetype'),
                Recipient: $sys.data('recipient'),
                Recipient_EntryID: $sys.data('recipient_entryid'),
                Subject: $sys.data('subject')
            };
        }
        model.ComposeMessageModel = ComposeMessageModel;
        function MessagingPageModel($sys) {
            return {
                MarkingAsReadErrorMessage: $sys.data('markingasreaderrormessage'),
                MessageLoadingErrorMessage: $sys.data('messageloadingerrormessage')
            };
        }
        model.MessagingPageModel = MessagingPageModel;
        function MessagingWidgetModel($sys) {
            return {
                MessagingProcessUrl: $sys.data('messagingprocessurl')
            };
        }
        model.MessagingWidgetModel = MessagingWidgetModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var messaging;
        (function (messaging) {
            "use strict";
            var GetConversationMessages = (function (_super) {
                __extends(GetConversationMessages, _super);
                function GetConversationMessages(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Messaging";
                    this.Controller = "messaging";
                    this.Action = "GetConversationMessages";
                }
                GetConversationMessages.prototype.CallData = function () {
                    var obj = {
                        otherEntryID: this.o.otherEntryID,
                        pageID: this.o.pageID,
                        subject: this.o.subject
                    };
                    return obj;
                };
                return GetConversationMessages;
            })(starrez.library.service.AddInActionCallBase);
            messaging.GetConversationMessages = GetConversationMessages;
            var GetPagedConversations = (function (_super) {
                __extends(GetPagedConversations, _super);
                function GetPagedConversations(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Messaging";
                    this.Controller = "messaging";
                    this.Action = "GetPagedConversations";
                }
                GetPagedConversations.prototype.CallData = function () {
                    var obj = {
                        currentPageNumber: this.o.currentPageNumber,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return GetPagedConversations;
            })(starrez.library.service.AddInActionCallBase);
            messaging.GetPagedConversations = GetPagedConversations;
            var GetSendMessageUrl = (function (_super) {
                __extends(GetSendMessageUrl, _super);
                function GetSendMessageUrl(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Messaging";
                    this.Controller = "messaging";
                    this.Action = "GetSendMessageUrl";
                }
                GetSendMessageUrl.prototype.CallData = function () {
                    var obj = {
                        messageType: this.o.messageType
                    };
                    return obj;
                };
                GetSendMessageUrl.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        correspondenceID: this.o.correspondenceID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return GetSendMessageUrl;
            })(starrez.library.service.AddInActionCallBase);
            messaging.GetSendMessageUrl = GetSendMessageUrl;
            var MarkMessagesRead = (function (_super) {
                __extends(MarkMessagesRead, _super);
                function MarkMessagesRead(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Messaging";
                    this.Controller = "messaging";
                    this.Action = "MarkMessagesRead";
                }
                MarkMessagesRead.prototype.CallData = function () {
                    var obj = {
                        correspondenceIDs: this.o.correspondenceIDs
                    };
                    return obj;
                };
                return MarkMessagesRead;
            })(starrez.library.service.AddInActionCallBase);
            messaging.MarkMessagesRead = MarkMessagesRead;
        })(messaging = service.messaging || (service.messaging = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var mydetails;
        (function (mydetails) {
            "use strict";
            function InitialiseMyDetails($container) {
                new MyDetails($container);
            }
            mydetails.InitialiseMyDetails = InitialiseMyDetails;
            var MyDetails = (function () {
                function MyDetails($container) {
                    this.$container = $container;
                    this.AttachEvents();
                    this.model = starrez.model.MyDetailsModel($container);
                }
                MyDetails.prototype.AttachEvents = function () {
                    var _this = this;
                    this.$container.find(".ui-btn-change-password").SRClick(function (e) {
                        var call = new starrez.service.mydetails.ChangePassword({ pageID: portal.page.CurrentPage.PageID });
                        ;
                        call.Post().done(function (result) {
                            if (starrez.library.convert.ToBoolean(result)) {
                                portal.page.CurrentPage.SetSuccessMessage(_this.model.PasswordChangeRequestConfirmationMessage);
                            }
                            else {
                                portal.page.CurrentPage.SetErrorMessage(_this.model.PasswordChangeRequestErrorMessage);
                            }
                        });
                    });
                };
                return MyDetails;
            })();
            mydetails.MyDetails = MyDetails;
        })(mydetails = general.mydetails || (general.mydetails = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function MyDetailsModel($sys) {
            return {
                PasswordChangeMessageTitle: $sys.data('passwordchangemessagetitle'),
                PasswordChangeRequestConfirmationMessage: $sys.data('passwordchangerequestconfirmationmessage'),
                PasswordChangeRequestErrorMessage: $sys.data('passwordchangerequesterrormessage')
            };
        }
        model.MyDetailsModel = MyDetailsModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var mydetails;
        (function (mydetails) {
            "use strict";
            var ChangePassword = (function (_super) {
                __extends(ChangePassword, _super);
                function ChangePassword(o) {
                    _super.call(this);
                    this.o = o;
                    this.Area = "MyDetails";
                    this.Controller = "mydetails";
                    this.Action = "ChangePassword";
                }
                ChangePassword.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return ChangePassword;
            })(starrez.library.service.ActionCallBase);
            mydetails.ChangePassword = ChangePassword;
        })(mydetails = service.mydetails || (service.mydetails = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var starrez;
(function (starrez) {
    var ngigradguard;
    (function (ngigradguard) {
        "use strict";
        function Initialise($container) {
            var model = starrez.model.NGIGradGuardModel($container);
        }
        ngigradguard.Initialise = Initialise;
    })(ngigradguard = starrez.ngigradguard || (starrez.ngigradguard = {}));
})(starrez || (starrez = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function NGIGradGuardModel($sys) {
            return {
                CancelledMessage: $sys.data('cancelledmessage'),
                DefaultMessage: $sys.data('defaultmessage'),
                RedirectParameters: $sys.data('redirectparameters'),
                RedirectURL: $sys.data('redirecturl'),
                ResultCustomField: $sys.data('resultcustomfield'),
                SuccessMessage: $sys.data('successmessage'),
                UseEntryCustomField: starrez.library.convert.ToBoolean($sys.data('useentrycustomfield'))
            };
        }
        model.NGIGradGuardModel = NGIGradGuardModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

/// <reference path="../../../../WebCommon/TypeScriptTypes/lib.d.ts" />
var portal;
(function (portal) {
    var general;
    (function (general) {
        var paymentschedule;
        (function (paymentschedule) {
            "use strict";
            function InitPaymentScheduleWidget($container) {
                new PaymentScheduleModel($container);
            }
            paymentschedule.InitPaymentScheduleWidget = InitPaymentScheduleWidget;
            var PaymentScheduleModel = (function () {
                function PaymentScheduleModel($container) {
                    this.$container = $container;
                    this.pageID = portal.page.CurrentPage.PageID;
                    this.widgetID = Number($container.data("portalpagewidgetid"));
                    this.model = starrez.model.PaymentScheduleModel($container);
                    this.AttachEvents();
                }
                PaymentScheduleModel.prototype.AttachEvents = function () {
                    var _this = this;
                    var $roomRate = this.$container.GetControl("RoomRateID");
                    var $roomRateContainer = this.$container.find(".ui-roomrate-container");
                    $roomRate.change(function (e) {
                        var roomRate = $roomRate.SRVal();
                        if (starrez.library.utils.IsNotNullUndefined(roomRate)) {
                            var call = new starrez.service.paymentschedule.UpdateTransactionRecords({
                                portalPageWidgetID: _this.widgetID,
                                rateID: roomRate,
                                bookingIDs: _this.model.BookingIDs,
                                hash: $roomRateContainer.data("hash")
                            });
                            call.Post().done(function (result) {
                                var $transactionListContainer = _this.$container.find(".ui-payment-schedule-transactions");
                                $transactionListContainer.html(result);
                                // Need to do this to esure the event to show the active table settings is still attached after
                                // the table is refreshed due to a room rate change.
                                starrez.tablesetup.InitActiveTableEditor($transactionListContainer.find(".ui-active-table"), null);
                            });
                        }
                    });
                };
                return PaymentScheduleModel;
            })();
        })(paymentschedule = general.paymentschedule || (general.paymentschedule = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var paymentschedule;
        (function (paymentschedule) {
            "use strict";
            function InitSettings($container) {
                new PaymentScheduleModelSettings($container);
            }
            paymentschedule.InitSettings = InitSettings;
            var PaymentScheduleModelSettings = (function () {
                function PaymentScheduleModelSettings($container) {
                    this.$container = $container;
                    this.widgetID = Number($container.data("portalpagewidgetid"));
                    this.AttachEvents();
                }
                PaymentScheduleModelSettings.prototype.AttachEvents = function () {
                    this.$calculationMethod = this.$container.GetControl("CalculationMethod");
                    this.$customMethodConfig = this.$container.GetControl("CustomMethodConfig");
                    this.$proRateName = this.$container.GetControl("ProRateName");
                    this.SetupCalculationMethodchange();
                    this.SetupProRateReservationFilenameChange();
                    // Trigger a change so the dropdowns further down get populated with values	if not already set
                    if (starrez.library.stringhelper.IsUndefinedOrEmpty(this.$calculationMethod.SRVal())) {
                        this.$proRateName.change();
                    }
                    if (starrez.library.stringhelper.IsUndefinedOrEmpty(this.$customMethodConfig.SRVal())) {
                        this.$calculationMethod.change();
                    }
                };
                PaymentScheduleModelSettings.prototype.SetupProRateReservationFilenameChange = function () {
                    var _this = this;
                    this.$proRateName.change(function (e) {
                        var call = new starrez.service.paymentschedule.GetCalculationMethodConfig({
                            portalPageWidgetID: _this.widgetID,
                            proRateReservationDll: _this.$proRateName.SRVal()
                        });
                        call.Get().done(function (json) {
                            starrez.library.controls.dropdown.FillDropDown(json, _this.$calculationMethod, "Value", "Text", "", false);
                            _this.$calculationMethod.change(); // Need to do this to ensure the next dropdown gets populated
                        });
                    });
                };
                PaymentScheduleModelSettings.prototype.SetupCalculationMethodchange = function () {
                    var _this = this;
                    this.$calculationMethod.change(function (e) {
                        var call = new starrez.service.paymentschedule.GetCustomMethodConfig({
                            portalPageWidgetID: _this.widgetID,
                            proRateName: _this.$proRateName.SRVal(),
                            calculationMethod: _this.$calculationMethod.SRVal()
                        });
                        call.Get().done(function (json) {
                            starrez.library.controls.dropdown.FillDropDown(json, _this.$customMethodConfig, "Value", "Text", "", false);
                            _this.$customMethodConfig.change();
                        });
                    });
                };
                return PaymentScheduleModelSettings;
            })();
        })(paymentschedule = general.paymentschedule || (general.paymentschedule = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function PaymentScheduleModel($sys) {
            return {
                BookingIDs: ($sys.data('bookingids') === '') ? [] : ($sys.data('bookingids')).toString().split(',').map(function (e) { return Number(e); }),
                HasPleaseSelectRoomRate: starrez.library.convert.ToBoolean($sys.data('haspleaseselectroomrate'))
            };
        }
        model.PaymentScheduleModel = PaymentScheduleModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var paymentschedule;
        (function (paymentschedule) {
            "use strict";
            var GetCalculationMethodConfig = (function (_super) {
                __extends(GetCalculationMethodConfig, _super);
                function GetCalculationMethodConfig(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "PaymentSchedule";
                    this.Controller = "paymentschedule";
                    this.Action = "GetCalculationMethodConfig";
                }
                GetCalculationMethodConfig.prototype.CallData = function () {
                    var obj = {
                        portalPageWidgetID: this.o.portalPageWidgetID,
                        proRateReservationDll: this.o.proRateReservationDll
                    };
                    return obj;
                };
                return GetCalculationMethodConfig;
            })(starrez.library.service.AddInActionCallBase);
            paymentschedule.GetCalculationMethodConfig = GetCalculationMethodConfig;
            var GetCustomMethodConfig = (function (_super) {
                __extends(GetCustomMethodConfig, _super);
                function GetCustomMethodConfig(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "PaymentSchedule";
                    this.Controller = "paymentschedule";
                    this.Action = "GetCustomMethodConfig";
                }
                GetCustomMethodConfig.prototype.CallData = function () {
                    var obj = {
                        calculationMethod: this.o.calculationMethod,
                        portalPageWidgetID: this.o.portalPageWidgetID,
                        proRateName: this.o.proRateName
                    };
                    return obj;
                };
                return GetCustomMethodConfig;
            })(starrez.library.service.AddInActionCallBase);
            paymentschedule.GetCustomMethodConfig = GetCustomMethodConfig;
            var UpdateTransactionRecords = (function (_super) {
                __extends(UpdateTransactionRecords, _super);
                function UpdateTransactionRecords(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "PaymentSchedule";
                    this.Controller = "paymentschedule";
                    this.Action = "UpdateTransactionRecords";
                }
                UpdateTransactionRecords.prototype.CallData = function () {
                    var obj = {
                        rateID: this.o.rateID
                    };
                    return obj;
                };
                UpdateTransactionRecords.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        bookingIDs: this.o.bookingIDs,
                        portalPageWidgetID: this.o.portalPageWidgetID
                    };
                    return obj;
                };
                return UpdateTransactionRecords;
            })(starrez.library.service.AddInActionCallBase);
            paymentschedule.UpdateTransactionRecords = UpdateTransactionRecords;
        })(paymentschedule = service.paymentschedule || (service.paymentschedule = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var starrez;
(function (starrez) {
    var paymentsvirtualterminal;
    (function (paymentsvirtualterminal) {
        "use strict";
        function InitialiseEntrySearch($container) {
            new EntrySearch($container);
        }
        paymentsvirtualterminal.InitialiseEntrySearch = InitialiseEntrySearch;
        var EntrySearch = (function () {
            function EntrySearch($container) {
                this.$container = $container;
                this.$searchButton = $container.find(".ui-search-button");
                this.$searchEntryID = $container.GetControl("Search_EntryID");
                this.$id1 = $container.GetControl("ID1");
                this.$nameLast = $container.GetControl("NameLast");
                this.$nameFirst = $container.GetControl("NameFirst");
                this.$dob = $container.GetControl("Dob");
                this.$selectedEntryID = $container.GetControl("Selected_EntryID");
                this.$entryTable = $container.find(".ui-found-entries-table");
                this.$entrySearchModel = starrez.model.EntrySearchModel($container);
                this.AttachButtonEvents();
                this.InitialiseTableEvents();
            }
            EntrySearch.prototype.AttachButtonEvents = function () {
                var _this = this;
                this.$searchButton.SRClick(function () {
                    _this.GetEntries();
                });
            };
            EntrySearch.prototype.InitialiseTableEvents = function () {
                var _this = this;
                this.$entryTable.on("click", ".ui-select-entry", function (e) {
                    var entryID = Number($(e.target).closest("tr").data("entry"));
                    _this.$selectedEntryID.SRVal(entryID);
                    portal.page.CurrentPage.SubmitPage();
                });
            };
            EntrySearch.prototype.GetEntries = function () {
                var _this = this;
                new starrez.service.entrysearch.GetEntriesSearch({
                    searchEntryID: this.$searchEntryID.SRVal(),
                    id1: this.$id1.SRVal(),
                    nameLast: this.$nameLast.SRVal(),
                    nameFirst: this.$nameFirst.SRVal(),
                    dob: this.$dob.SRVal(),
                    pageID: portal.page.CurrentPage.PageID
                }).Post().done(function (searchResults) {
                    _this.$entryTable.SRShow();
                    _this.$entryTable.html(searchResults);
                });
            };
            ;
            return EntrySearch;
        })();
    })(paymentsvirtualterminal = starrez.paymentsvirtualterminal || (starrez.paymentsvirtualterminal = {}));
})(starrez || (starrez = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function EntrySearchModel($sys) {
            return {
                Selected_EntryID: Number($sys.data('selected_entryid'))
            };
        }
        model.EntrySearchModel = EntrySearchModel;
        function ProxyAccountSummaryModel($sys) {
            return {};
        }
        model.ProxyAccountSummaryModel = ProxyAccountSummaryModel;
        function ProxyShoppingCartCheckoutModel($sys) {
            return {};
        }
        model.ProxyShoppingCartCheckoutModel = ProxyShoppingCartCheckoutModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var entrysearch;
        (function (entrysearch) {
            "use strict";
            var GetEntriesSearch = (function (_super) {
                __extends(GetEntriesSearch, _super);
                function GetEntriesSearch(o) {
                    _super.call(this);
                    this.o = o;
                    this.Area = "PaymentsVirtualTerminal";
                    this.Controller = "entrysearch";
                    this.Action = "GetEntriesSearch";
                }
                GetEntriesSearch.prototype.CallData = function () {
                    var obj = {
                        dob: this.o.dob,
                        id1: this.o.id1,
                        nameFirst: this.o.nameFirst,
                        nameLast: this.o.nameLast,
                        pageID: this.o.pageID,
                        searchEntryID: this.o.searchEntryID
                    };
                    return obj;
                };
                return GetEntriesSearch;
            })(starrez.library.service.ActionCallBase);
            entrysearch.GetEntriesSearch = GetEntriesSearch;
        })(entrysearch = service.entrysearch || (service.entrysearch = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var starrez;
(function (starrez) {
    var printpage;
    (function (printpage) {
        "use strict";
        function InitialisePrintPageWidget($container) {
            var $printButton = $container.find(".ui-print-page");
            $printButton.SRClick(function () {
                window.print();
            });
        }
        printpage.InitialisePrintPageWidget = InitialisePrintPageWidget;
    })(printpage = starrez.printpage || (starrez.printpage = {}));
})(starrez || (starrez = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var profiles;
        (function (profiles) {
            "use strict";
            function Initialise($container) {
                var widget = starrez.model.WidgetModelBaseModel($container);
                InitializeProfileWidget($container);
            }
            profiles.Initialise = Initialise;
            function InitializeProfileWidget($container) {
                var portalPageWidgetID = Number($container.data('portalpagewidgetid'));
                $container.data('FormWidget', new ProfileWidget(portalPageWidgetID, $container));
            }
            profiles.InitializeProfileWidget = InitializeProfileWidget;
            var ProfileWidget = (function () {
                function ProfileWidget(portalPageWidgetID, $container) {
                    var _this = this;
                    this.portalPageWidgetID = portalPageWidgetID;
                    this.$container = $container;
                    portal.page.RegisterWidgetSaveData(portalPageWidgetID, function () { return _this.GetSaveData(); });
                }
                ProfileWidget.prototype.GetSaveData = function () {
                    var saveData = new starrez.library.collections.KeyValue();
                    var $allControls = this.$container.GetAllControls();
                    $allControls.each(function (index, element) {
                        var $control = $(element);
                        var profileID = $control.closest('.ui-profile-data').data('id');
                        var profileValue = $control.SRVal();
                        saveData.Add(profileID, profileValue);
                    });
                    var data = saveData.ToArray();
                    if (data.length === 0) {
                        return null;
                    }
                    return data;
                };
                return ProfileWidget;
            })();
        })(profiles = general.profiles || (general.profiles = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var programming;
        (function (programming) {
            "use strict";
            function InitProgramDetails($container) {
                new ProgramDetailsManager($container);
            }
            programming.InitProgramDetails = InitProgramDetails;
            var ProgramDetailsManager = (function () {
                function ProgramDetailsManager($container) {
                    var _this = this;
                    this.$container = $container;
                    this.programID = starrez.model.ProgramDetailsModel($container).ProgramID;
                    this.$totalAmount = this.$container.find(".ui-quantity-total");
                    this.$qtyControl = this.$container.GetControl("SelectedQuantity");
                    this.getTotalAmountHash = this.$qtyControl.closest("li").data("hash").toString();
                    this.$qtyControl.change(function (e) {
                        var qty = Number(_this.$qtyControl.SRVal());
                        var call = new starrez.service.programming.GetTotalAmount({
                            pageID: portal.page.CurrentPage.PageID,
                            programID: _this.programID,
                            quantity: qty,
                            hash: _this.getTotalAmountHash
                        });
                        call.Post().done(function (amount) {
                            _this.$totalAmount.text(amount);
                        });
                    });
                }
                return ProgramDetailsManager;
            })();
            programming.ProgramDetailsManager = ProgramDetailsManager;
        })(programming = general.programming || (general.programming = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function ProgramDetailsModel($sys) {
            return {
                ProgramID: Number($sys.data('programid'))
            };
        }
        model.ProgramDetailsModel = ProgramDetailsModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var programming;
        (function (programming) {
            "use strict";
            var GetTotalAmount = (function (_super) {
                __extends(GetTotalAmount, _super);
                function GetTotalAmount(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Programming";
                    this.Controller = "programming";
                    this.Action = "GetTotalAmount";
                }
                GetTotalAmount.prototype.CallData = function () {
                    var obj = {
                        quantity: this.o.quantity
                    };
                    return obj;
                };
                GetTotalAmount.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID,
                        programID: this.o.programID
                    };
                    return obj;
                };
                return GetTotalAmount;
            })(starrez.library.service.AddInActionCallBase);
            programming.GetTotalAmount = GetTotalAmount;
        })(programming = service.programming || (service.programming = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var promocodes;
        (function (promocodes) {
            "use strict";
            function InitialisePromoCodesWidget($container) {
                var portalPageWidgetID = Number($container.data("portalpagewidgetid"));
                var $promoCode = $container.GetControl("PromoCode");
                var $apply = $container.find(".ui-apply-promocode");
                $container.keydown(function (e) {
                    if (e.keyCode === starrez.keyboard.EnterCode) {
                        // The browsers have a behaviour where they will automatically submit the form if there is only one
                        // input field on it. This is not what we want to do, so call SafeStopPropagation to block this from happening.
                        // http://stackoverflow.com/questions/1370021/why-does-forms-with-single-input-field-submit-upon-pressing-enter-key-in-input
                        starrez.library.utils.SafeStopPropagation(e);
                        $apply.click();
                    }
                });
                $apply.SRClick(function () {
                    new starrez.service.promocodes.ApplyPromoCode({
                        portalPageWidgetID: portalPageWidgetID,
                        processID: portal.page.CurrentPage.ProcessID,
                        promoCode: $promoCode.SRVal()
                    }).Post().done(function (result) {
                        if (result.Message.trim().length > 0) {
                            if (result.IsSuccess) {
                                var model = starrez.model.PromoCodesModel($container);
                                if (model.ReloadPageOnSuccess) {
                                    location.reload();
                                }
                                else {
                                    portal.page.CurrentPage.SetSuccessMessage(result.Message);
                                }
                            }
                            else {
                                portal.page.CurrentPage.SetErrorMessage(result.Message);
                            }
                        }
                    });
                });
            }
            promocodes.InitialisePromoCodesWidget = InitialisePromoCodesWidget;
        })(promocodes = general.promocodes || (general.promocodes = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function PromoCodesModel($sys) {
            return {
                ReloadPageOnSuccess: starrez.library.convert.ToBoolean($sys.data('reloadpageonsuccess'))
            };
        }
        model.PromoCodesModel = PromoCodesModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var promocodes;
        (function (promocodes) {
            "use strict";
            var ApplyPromoCode = (function (_super) {
                __extends(ApplyPromoCode, _super);
                function ApplyPromoCode(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "PromoCodes";
                    this.Controller = "promocodes";
                    this.Action = "ApplyPromoCode";
                }
                ApplyPromoCode.prototype.CallData = function () {
                    var obj = {
                        portalPageWidgetID: this.o.portalPageWidgetID,
                        processID: this.o.processID,
                        promoCode: this.o.promoCode
                    };
                    return obj;
                };
                return ApplyPromoCode;
            })(starrez.library.service.AddInActionCallBase);
            promocodes.ApplyPromoCode = ApplyPromoCode;
        })(promocodes = service.promocodes || (service.promocodes = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var proxy;
    (function (proxy) {
        "use strict";
        function InitProxyAgreementPage($container) {
            "use strict";
            new ProxyAgreementModel($container);
        }
        proxy.InitProxyAgreementPage = InitProxyAgreementPage;
        function InitProxyPage($container) {
            "use strict";
            new ProxyPageModel($container);
        }
        proxy.InitProxyPage = InitProxyPage;
        var ProxyMessageType;
        (function (ProxyMessageType) {
            ProxyMessageType[ProxyMessageType["ProxyComplete"] = 0] = "ProxyComplete";
            ProxyMessageType[ProxyMessageType["ProxyNew"] = 1] = "ProxyNew";
            ProxyMessageType[ProxyMessageType["ProxySuccess"] = 2] = "ProxySuccess";
        })(ProxyMessageType || (ProxyMessageType = {}));
        var ProxyAgreementModel = (function () {
            function ProxyAgreementModel($container) {
                this.$container = $container;
                this.$addProxyButton = $container.find('.ui-add-proxy');
                this.pageID = portal.page.CurrentPage.PageID;
                this.$proxyTableDiv = this.$container.find(".ui-proxy-table");
                this.proxyTable = starrez.tablesetup.CreateTableManager(this.$container.find(".ui-proxy-table table"), $('body'))[0];
                this.proxyAgreementModel = starrez.model.ProxyAgreementModel($container);
                this.maximumProxies = this.proxyAgreementModel.MaximumProxies;
                this.deleteProxyConfirmText = this.proxyAgreementModel.DeleteProxyConfirmText;
                this.refreshProxyConfirmText = this.proxyAgreementModel.RefreshProxyConfirmText;
                this.maximumProxiesErrorNotification = $container.find('.ui-maximum-proxies-error');
                this.deleteProxyErrorMessage = this.proxyAgreementModel.DeleteProxyErrorMessage;
                this.deleteCompleteProxyErrorMessage = this.proxyAgreementModel.DeleteCompleteProxyErrorMessage;
                this.refreshProxyErrorMessage = this.proxyAgreementModel.RefreshProxyErrorMessage;
                this.refreshCompleteProxyErrorMessage = this.proxyAgreementModel.RefreshCompleteProxyErrorMessage;
                this.deleteProxySuccessMessage = this.proxyAgreementModel.DeleteProxySuccessMessage;
                this.refreshProxySuccessMessage = this.proxyAgreementModel.RefreshProxySuccessMessage;
                this.AttachClickEvents();
                this.AttachRowEvents();
                this.ProxyLimitReachedCheck();
            }
            ProxyAgreementModel.prototype.AttachClickEvents = function () {
                var _this = this;
                this.$addProxyButton.SRClick(function () {
                    _this.RedirectToProxyPage();
                });
            };
            ProxyAgreementModel.prototype.AttachRowEvents = function () {
                var _this = this;
                this.proxyTable.$table.SRClickDelegate('delete', '.ui-btn-delete', function (e) {
                    portal.ConfirmAction(_this.deleteProxyConfirmText, "Delete Proxy").done(function () {
                        var $row = $(e.currentTarget).closest('tr');
                        var id = Number($row.data('id'));
                        var hash = $row.data('deletehash').toString();
                        new starrez.service.proxy.DeleteProxy({
                            entryApplicationProxyID: id,
                            hash: hash
                        }).Post().done(function (isDeleted) {
                            var deleteType = ProxyMessageType[isDeleted];
                            var studentFacingErrors = [];
                            if (deleteType == ProxyMessageType.ProxyComplete) {
                                studentFacingErrors.push(_this.deleteCompleteProxyErrorMessage);
                            }
                            if (deleteType == ProxyMessageType.ProxyNew) {
                                studentFacingErrors.push(_this.deleteProxyErrorMessage);
                            }
                            if (studentFacingErrors.length > 0) {
                                portal.page.CurrentPage.SetErrorMessages(studentFacingErrors);
                            }
                            if (deleteType == ProxyMessageType.ProxySuccess) {
                                portal.page.CurrentPage.SetSuccessMessage(_this.deleteProxySuccessMessage);
                                _this.proxyTable.RemoveRows($row);
                                _this.ProxyLimitReachedCheck();
                            }
                        });
                    });
                });
                this.proxyTable.$table.SRClickDelegate('refresh', '.ui-btn-refresh', function (e) {
                    portal.ConfirmAction(_this.refreshProxyConfirmText, "Refresh Proxy").done(function () {
                        var $row = $(e.currentTarget).closest('tr');
                        var id = Number($row.data('id'));
                        var hash = $row.data('refreshhash').toString();
                        new starrez.service.proxy.RefreshProxy({
                            pageID: portal.page.CurrentPage.PageID,
                            entryApplicationProxyID: id,
                            hash: hash
                        }).Post().done(function (isRefreshed) {
                            var refreshType = ProxyMessageType[isRefreshed];
                            var studentFacingErrors = [];
                            if (refreshType == ProxyMessageType.ProxyComplete) {
                                studentFacingErrors.push(_this.refreshCompleteProxyErrorMessage);
                            }
                            if (refreshType == ProxyMessageType.ProxyNew) {
                                studentFacingErrors.push(_this.refreshProxyErrorMessage);
                            }
                            if (studentFacingErrors.length > 0) {
                                portal.page.CurrentPage.SetErrorMessages(studentFacingErrors);
                            }
                            if (refreshType == ProxyMessageType.ProxySuccess) {
                                new starrez.service.proxy.GetProxyTable({
                                    pageID: portal.page.CurrentPage.PageID
                                }).Post().done(function (results) {
                                    _this.$proxyTableDiv.html(results);
                                    _this.ProxyLimitReachedCheck();
                                    _this.proxyTable = starrez.tablesetup.CreateTableManager(_this.$container.find(".ui-proxy-table table"), $('body'))[0];
                                    _this.AttachRowEvents();
                                });
                                portal.page.CurrentPage.SetSuccessMessage(_this.refreshProxySuccessMessage);
                            }
                        });
                    });
                });
            };
            ProxyAgreementModel.prototype.ProxyLimitReachedCheck = function () {
                if (this.maximumProxies > 0 && this.proxyTable.Rows().length >= this.maximumProxies) {
                    this.$addProxyButton.Disable();
                    this.maximumProxiesErrorNotification.SRShow();
                }
                else {
                    this.$addProxyButton.Enable();
                    this.maximumProxiesErrorNotification.SRHide();
                }
            };
            ProxyAgreementModel.prototype.RedirectToProxyPage = function () {
                new starrez.service.proxy.AddNewProxy({
                    pageID: this.pageID,
                    index: this.proxyTable.Rows().length
                }).Post().done(function (results) {
                    if (results != null) {
                        location.href = results;
                    }
                });
            };
            return ProxyAgreementModel;
        })();
        var ProxyPageModel = (function () {
            function ProxyPageModel($container) {
                var _this = this;
                this.$container = $container;
                this.proxyPageModel = starrez.model.ProxyFormModel($container);
                this.inProxyMode = this.proxyPageModel.InProxyMode;
                this.recordID = this.proxyPageModel.EntryApplicationProxyID;
                this.detailsErrorMessage = this.proxyPageModel.MatchCustomErrorMessage;
                this.$matchingWidgetFields = $container.find('.ui-matching-widget').GetAllControls();
                portal.page.CurrentPage.FetchAdditionalWidgetData = function () { return _this.GetData(); };
                portal.page.CurrentPage.AddCustomValidation(this);
            }
            ProxyPageModel.prototype.Validate = function () {
                var _this = this;
                var deferred = $.Deferred();
                var values = [];
                if (this.inProxyMode) {
                    this.$matchingWidgetFields.each(function (i, e) {
                        values.push({
                            Key: $(e).closest('.ui-field-record').data('fieldname'),
                            Value: $(e).SRVal()
                        });
                    });
                    new starrez.service.proxy.MatchProxy({
                        values: values,
                        entryApplicationProxyID: this.recordID
                    }).Post().done(function (isValid) {
                        if (starrez.library.convert.ToBoolean(isValid)) {
                            deferred.resolve();
                        }
                        else {
                            portal.page.CurrentPage.SetErrorMessage(_this.detailsErrorMessage);
                            deferred.reject();
                        }
                    });
                }
                else {
                    deferred.resolve();
                }
                return deferred.promise();
            };
            ProxyPageModel.prototype.GetData = function () {
                return {
                    Key: "RecordID",
                    Value: this.recordID.toString()
                };
            };
            return ProxyPageModel;
        })();
    })(proxy = portal.proxy || (portal.proxy = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function ProxyAgreementModel($sys) {
            return {
                DeleteCompleteProxyErrorMessage: $sys.data('deletecompleteproxyerrormessage'),
                DeleteProxyConfirmText: $sys.data('deleteproxyconfirmtext'),
                DeleteProxyErrorMessage: $sys.data('deleteproxyerrormessage'),
                DeleteProxySuccessMessage: $sys.data('deleteproxysuccessmessage'),
                MaximumProxies: Number($sys.data('maximumproxies')),
                MaximumProxiesErrorMessage: $sys.data('maximumproxieserrormessage'),
                RefreshCompleteProxyErrorMessage: $sys.data('refreshcompleteproxyerrormessage'),
                RefreshProxyConfirmText: $sys.data('refreshproxyconfirmtext'),
                RefreshProxyErrorMessage: $sys.data('refreshproxyerrormessage'),
                RefreshProxySuccessMessage: $sys.data('refreshproxysuccessmessage')
            };
        }
        model.ProxyAgreementModel = ProxyAgreementModel;
        function ProxyFormModel($sys) {
            return {
                EntryApplicationProxyID: Number($sys.data('entryapplicationproxyid')),
                InProxyMode: starrez.library.convert.ToBoolean($sys.data('inproxymode')),
                MatchCustomErrorMessage: $sys.data('matchcustomerrormessage')
            };
        }
        model.ProxyFormModel = ProxyFormModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var proxy;
        (function (proxy) {
            "use strict";
            var AddNewProxy = (function (_super) {
                __extends(AddNewProxy, _super);
                function AddNewProxy(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Proxy";
                    this.Controller = "proxy";
                    this.Action = "AddNewProxy";
                }
                AddNewProxy.prototype.CallData = function () {
                    var obj = {
                        index: this.o.index,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return AddNewProxy;
            })(starrez.library.service.AddInActionCallBase);
            proxy.AddNewProxy = AddNewProxy;
            var DeleteProxy = (function (_super) {
                __extends(DeleteProxy, _super);
                function DeleteProxy(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Proxy";
                    this.Controller = "proxy";
                    this.Action = "DeleteProxy";
                }
                DeleteProxy.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                DeleteProxy.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        entryApplicationProxyID: this.o.entryApplicationProxyID
                    };
                    return obj;
                };
                return DeleteProxy;
            })(starrez.library.service.AddInActionCallBase);
            proxy.DeleteProxy = DeleteProxy;
            var GetProxyTable = (function (_super) {
                __extends(GetProxyTable, _super);
                function GetProxyTable(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Proxy";
                    this.Controller = "proxy";
                    this.Action = "GetProxyTable";
                }
                GetProxyTable.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return GetProxyTable;
            })(starrez.library.service.AddInActionCallBase);
            proxy.GetProxyTable = GetProxyTable;
            var MatchProxy = (function (_super) {
                __extends(MatchProxy, _super);
                function MatchProxy(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Proxy";
                    this.Controller = "proxy";
                    this.Action = "MatchProxy";
                }
                MatchProxy.prototype.CallData = function () {
                    var obj = {
                        entryApplicationProxyID: this.o.entryApplicationProxyID,
                        values: this.o.values
                    };
                    return obj;
                };
                return MatchProxy;
            })(starrez.library.service.AddInActionCallBase);
            proxy.MatchProxy = MatchProxy;
            var RefreshProxy = (function (_super) {
                __extends(RefreshProxy, _super);
                function RefreshProxy(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Proxy";
                    this.Controller = "proxy";
                    this.Action = "RefreshProxy";
                }
                RefreshProxy.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                RefreshProxy.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        entryApplicationProxyID: this.o.entryApplicationProxyID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return RefreshProxy;
            })(starrez.library.service.AddInActionCallBase);
            proxy.RefreshProxy = RefreshProxy;
        })(proxy = service.proxy || (service.proxy = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

/*! rxp-js - v1.3.1 - 2018-08-30
 * The official Realex Payments JS Library
 * https://github.com/realexpayments/rxp-js
 * Licensed MIT
 */

var RealexHpp = function () { "use strict"; var g, d, i, n, A, l = "https://pay.realexpayments.com/pay", I = I || Math.random().toString(16).substr(2, 8), e = /Windows Phone|IEMobile/.test(navigator.userAgent), t = /Android|iPad|iPhone|iPod/.test(navigator.userAgent), o = (0 < window.innerWidth ? window.innerWidth : screen.width) <= 360 || (0 < window.innerHeight ? window.innerHeight : screen.Height) <= 360, E = e, C = !e && (t || o), h = { createFormHiddenInput: function (e, t) { var A = document.createElement("input"); return A.setAttribute("type", "hidden"), A.setAttribute("name", e), A.setAttribute("value", t), A }, checkDevicesOrientation: function () { return 90 === window.orientation || -90 === window.orientation }, createOverlay: function () { var e = document.createElement("div"); return e.setAttribute("id", "rxp-overlay-" + I), e.style.position = "fixed", e.style.width = "100%", e.style.height = "100%", e.style.top = "0", e.style.left = "0", e.style.transition = "all 0.3s ease-in-out", e.style.zIndex = "100", E && (e.style.position = "absolute !important", e.style.WebkitOverflowScrolling = "touch", e.style.overflowX = "hidden", e.style.overflowY = "scroll"), document.body.appendChild(e), setTimeout(function () { e.style.background = "rgba(0, 0, 0, 0.7)" }, 1), e }, closeModal: function (e, t, A, i) { e && e.parentNode && e.parentNode.removeChild(e), t && t.parentNode && t.parentNode.removeChild(t), A && A.parentNode && A.parentNode.removeChild(A), i && (i.className = "", setTimeout(function () { i.parentNode && i.parentNode.removeChild(i) }, 300)) }, createCloseButton: function (e) { if (null === document.getElementById("rxp-frame-close-" + I)) { var t = document.createElement("img"); return t.setAttribute("id", "rxp-frame-close-" + I), t.setAttribute("src", "data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAARCAYAAAA7bUf6AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6QUJFRjU1MEIzMUQ3MTFFNThGQjNERjg2NEZCRjFDOTUiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6QUJFRjU1MEMzMUQ3MTFFNThGQjNERjg2NEZCRjFDOTUiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpBQkVGNTUwOTMxRDcxMUU1OEZCM0RGODY0RkJGMUM5NSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpBQkVGNTUwQTMxRDcxMUU1OEZCM0RGODY0RkJGMUM5NSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PlHco5QAAAHpSURBVHjafFRdTsJAEF42JaTKn4glGIg++qgX4AAchHAJkiZcwnAQD8AF4NFHCaC2VgWkIQQsfl/jNJUik8Duzs/XmW9mN7Xb7VRc5vP5zWKxaK5Wq8Zmu72FqobfJG0YQ9M0+/l8/qFQKDzGY1JxENd1288vLy1s786KRZXJZCLber1Wn7MZt4PLarVnWdZ9AmQ8Hncc17UvymVdBMB/MgPQm+cFFcuy6/V6lzqDf57ntWGwYdBIVx0TfkBD6I9M35iRJgfIoAVjBLDZbA4CiJ5+9AdQi/EahibqDTkQx6fRSIHcPwA8Uy9A9Gcc47Xv+w2wzhRDYzqdVihLIbsIiCvP1NNOoX/29FQx3vgOgtt4FyRdCgPRarX4+goB9vkyAMh443cOEsIAAcjncuoI4TXWMAmCIGFhCQLAdZ8jym/cRJ+Y5nC5XCYAhINKpZLgSISZgoqh5iiLQrojAFICVwGS7tCfe5DbZzkP56XS4NVxwvTI/vXVVYIDnqmnnX70ZxzjNS8THHooK5hMpxHQIREA+tEfA9djfHR3MHkdx3Hspe9r3B+VzWaj2RESyR2mlCUE4MoGQDdxiwHURq2t94+PO9bMIYyTyDNLwMoM7g8+BfKeYGniyw2MdfSehF3Qmk1IvCc/AgwAaS86Etp38bUAAAAASUVORK5CYII="), t.setAttribute("style", "transition: all 0.5s ease-in-out; opacity: 0; float: left; position: absolute; left: 50%; margin-left: 173px; z-index: 99999999; top: 30px;"), setTimeout(function () { t.style.opacity = "1" }, 500), E && (t.style.position = "absolute", t.style.float = "right", t.style.top = "20px", t.style.left = "initial", t.style.marginLeft = "0px", t.style.right = "20px"), t } }, createForm: function (e, t, A) { var i = document.createElement("form"); i.setAttribute("method", "POST"), i.setAttribute("action", l); var n = !1; for (var o in t) "HPP_VERSION" === o && (n = !0), i.appendChild(h.createFormHiddenInput(o, t[o])); if (!1 === n && i.appendChild(h.createFormHiddenInput("HPP_VERSION", "2")), A) i.appendChild(h.createFormHiddenInput("MERCHANT_RESPONSE_URL", d)); else { var r = h.getUrlParser(window.location.href), a = r.protocol + "//" + r.host; i.appendChild(h.createFormHiddenInput("HPP_POST_RESPONSE", a)), i.appendChild(h.createFormHiddenInput("HPP_POST_DIMENSIONS", a)) } return i }, createSpinner: function () { var e = document.createElement("img"); return e.setAttribute("src", "data:image/gif;base64,R0lGODlhHAAcAPYAAP////OQHv338fzw4frfwPjIkPzx4/nVq/jKlfe7dv337/vo0fvn0Pzy5/WrVv38+vjDhva2bfzq1fe/f/vkyve8d/WoT/nRpP327ve9e/zs2vrWrPWqVPWtWfvmzve5cvazZvrdvPjKlPfAgPnOnPvp0/zx5fawYfe+ff317PnTp/nMmfvgwvfBgv39/PrXsPSeO/vjx/jJkvzz6PnNm/vkyfnUqfjLl/revvnQoPSfPfSgP/348/nPnvratfrYsvWlSvSbNPrZs/vhw/zv4P306vrXrvzq1/359f369vjHjvSjRvOXLfORIfOQHvjDh/rduvSaM/jEifvlzPzu3v37+Pvixfzr2Pzt3Pa1afa3b/nQovnSpfaxYvjFi/rbt/rcufWsWPjGjfSjRPShQfjChPOUJva0aPa2a/awX/e6dPWnTfWkSPScNve4cPWpUfSdOvOSI/OVKPayZPe9efauW/WpUvOYL/SiQ/OZMfScOPOTJfavXfWmSwAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAHAAcAAAH/4AAgoOEhYaHiIUKKYmNh0ofjoklL4RLUQ+DVZmSAAswOYIKTE1UglUCVZ0AGBYwPwBHTU44AFU8PKuCEzpARB5OTjYAPEi5jQYNgzE7QS1ET1JTD7iqgi6chAcOFRsmABUQBoQuSAIALjwpMwqHCBYcJyrHhulF9xiJFx0WMo0Y99o18oBCWSIXKZI0eoBhkaQHEA0JIIAAQoYPKiSlwIKFyIAUnAYUSBAhAogVkmZc0aChIz0ACiQQCLFAEhIMKXhkO8RiRqMqBnYe0iAigwoXiah4KMEI0QIII1rQyHeoypUFWH0aWjABAgkPLigIKUIIiQQNrDQs8EC2EAMKBlIV9EBgRAHWFEes1DiWpIjWRDVurCCCBAqUGUhqxEC7yoUNBENg4sChbICVaasw3PCBNAkLHAI1DBEoyQSObDGGZMPyV5egElNcNxJAVbZtQoEAACH5BAkKAAAALAAAAAAcABwAAAf/gACCg4SFhoeIhUVFiY2HYlKOiUdDgw9hDg+DPjWSgh4WX4JYY2MagipOBJ4AGF0OnTVkZDEAX05mDawAXg5dGCxBQQRFTE5djkQYgwxhFghYSjIDZU6qgy6ahS8RSj6MEyImhAoFHYJJPAJIhz1ZERVfCi6HVelISDyJNloRCI08ArJrdEQKEUcKtCF6oEDBDEkPIhoSwEKFDCktDkhyuAgDD3oADOR40qIFCi4bZywqkqIKISRYKAwpIalKwCQgD7kYMi6RC0aOsGxB8KLRDA1YBCQqsaLpBqU6DSDVsMzQFRkkXhwBcIUBVHREDmIYgOWKAkMMSpwFwINAiCkCTI5cEaCBwYKBVTAAnYQjBAYFVqx4XLBgwK6dIa4AUFCjxjIDDCTkdIQBzAJBPBrrA0DFw2ZJM2gKcjGFgsIBa3cNOrJVdaKArmMbCgQAIfkECQoAAAAsAAAAABwAHAAAB/+AAIKDhIWGh4iFRSmJjYckK46JEjWECWqEQgSSghJnIYIzaSdFghdRQ5wAPBlalRIdHUcALzBrGKoAPVoJPBQWa1MNbDsJjgOMggtaaDkaCDREKG06OIMDHoYhEzRgpTQiWIQmCJhUEGxOT4dGEy1SYMmGLgVmTk5uiWBlLTQuiSTutXBERcSVRi5OWEtUBUMKE6r+FeJR48cFEjdeSEoigIfHJBIb/MixYgWCDZKQeFz5gFAVE0cWHHRUJUmSKhIRHSnVCENORCZYhJjys5CAGUWQJCISAsdQHolSLCoC1ZABMASmGACApYQCQg+kAkCCocgMpYWIGEBLMQYDBVRMiPAwoUFDEkEPPDrCUiOGAAUePCioogFLg1wuPMSgAkDAggUCAMzQwFiVgCEzkzy+C6DBFbSSiogbJEECoQZfcxEiUlk1IpWuYxsKBAAh+QQJCgAAACwAAAAAHAAcAAAH/4AAgoOEhYaHiIUzDYmNhxckjolXVoQQIy6DX5WSAFQZIYIKFQlFgjZrU50ASUojMZ4fblcAUBxdCqsALy1PKRpoZ0czJ2FKjgYpmQBEZSNbAys5DUpvDh6CVVdDy4M1IiohMwBcKwOEGFwQABIjYW3HhiwIKzQEM0mISmQ7cCOJU2is4PIgUQ44OxA4wrDhSKMqKEo0QpJCQZFuiIqwmGKiUJIrMQjgCFFDUggnTuKQKWNAEA8GLHCMLOkIB0oncuZgIfTAYooUkky8CLEASaIqwxzlczSjRgwGE3nwWHqISAynEowiEsADSddDBoZQOAKUigYehQQAreJVgFZCM1JSVBGEZMGCK1UapEiCoUiRpS6qzG00wO5UDVd4PPCba5ULCQw68tBwFoAAvxgbCfBARNADLFgGK8C3CsO5QUSoEFLwVpcgEy1dJ0LSWrZtQYEAACH5BAkKAAAALAAAAAAcABwAAAf/gACCg4SFhoeIhRgziY2HQgeOiUQ1hDcyLoNgFJKCJiIEggpSEIwALyALnQBVFzdTAANlZVcAQxEVCqsABCs0ClgTKCUCFVo9jg0pVYIpNDc/VBcqRFtZWrUASAtDhlhgLCUpAFAq2Z4XJAAaK2drW4dHITg4CwrMhg8IHQ52CIlUCISw8iARlzd1IjVCwsBEowciBjRKogDDOEdEQsSgUnAQEg0MasSwwkCSiig7loRBcURQEg0eatQgKekASjwcMpQohCRFkYuNDHwhcCVJoipYMDhSosHRjAULWib64STOjUQGGEDVgO8QHSdgMxxq4KEEFQEAZhjo6JEHAAZqUu44EWNIgQB8LzWYqKJAQRIegDsqiPElGRauSWbMQOKCBxK3q1xQ0VCEVZEiSAD85ZGpE5IrDgE8uIwPyd1VAkw1q+yx6y5RSl8nesBWtu1BgQAAIfkECQoAAAAsAAAAABwAHAAAB/+AAIKDhIWGh4iFGEWJjYcEX46JDUeEG1sPgwQlkoIYUAuCPD00M4JfGVedAC5DIRoAMzQrWAA1I14CqwBHODg8JggiVwpPLQeORSlVor4UJj8/RDYTZUSCAiUxLoUGQxRHGABXMSaEA1wqABoXdCAvh0QxNTUlPNyGSDluWhHqiCYoxPCQCRGXLGrAOEoiwVQiJBdSNEKiAIM4R1SGTCFSUFASKhIWLGCgypGKNWHqoJECC0CSAUdEMmjZaMOaDmncILhGKIkABbocmfAgoUGjByaQOGrBwFEKLBrMJbIBh4yMSRqgmsB3CAKZHXAyHCpyBUtSABa5sjoAAoAECG9QgngxJAAJvgdF8lbhwQOAEidOYghSMCVEx0MK8j7Ye4+IHCdzdgHIq+sBX2YHnJhxKCnJjIsuBPAo+BfKqiQKCPEllCOS5EFIlL5OpHa27UAAIfkECQoAAAAsAAAAABwAHAAAB/+AAIKDhIWGh4iFPBiJjYdXDI6JAlSENUMugx4akoJIVpwAVQQ4AoI1Mgadgh5WRAAKOCENAEc3PTyrABo1NQICIVAzPD00Qo4YCg+evR4YFBRFQjcrA4JJWAuGMx4lVAoAV1O0g1QbPgADP0oZYIcmDAsLGjyZhikqZS0Tx4gz8hLsGXJxYQQEAo6SaDCVCMMFE40e8ECSRJKBI0eKCASQxAQRLBo0WHPE5YwbNS1oVOLoEeQViI6MmEwwgsYrQhIpSiqi4UqKjYUeYAAaVMkRRzyKFGGU6IedDjYSKSiSgirRQTLChLGD4JCAGUsrTixU5QCdWivOrNliiKI9iRNNZ3wBY0KKHh1DPJVggRRJrhhOnBgxwIYMGl0AeIw9EjgEACMw2JCT5EKxIAxynFwRhCBKjFUSCQHJs0xQjy+ICbXoUuhqJyIlUss2FAgAIfkECQoAAAAsAAAAABwAHAAAB/+AAIKDhIWGh4iFVQKJjYdEDI6JPESECzVVg0RUkoJVHliCLlMxCoJUYAadglcMAwBJFDFFAA0hBEirACYLCwpJMVYNDyw4U44CPA+CSb0SPAsMKUdQIaqwDVguhQpXWAOmJhIYhBhTx0UhWyIEhykaWBoGSYgKUCQrCCGJCvHXhy583FhRw1GVBvQSpRAyo1GVJFUyORpw5IqBXINcYCjCsUgKST9QlCkjhss1jR1nfHT0BQUEKQUOmCjk4gFESSkGmEixDJELZY14iDjiKAkPJDwa+UDjZkMipEgZIUqyIYGWLDR6EkqSjEcmJTeSDuLxY8QuLi2ybDFUReuAPU5W+KTgkkOCCgsc9gF4wEvrISlOnLAgAiePCgFnHKDQBQCIkycADADR4QPAFAd8Gqwy4ESLIAF2dlAQ5KMPlFULpBACgUezIChfGBOiAUJ2oiJXbOsmFAgAIfkECQoAAAAsAAAAABwAHAAAB/+AAIKDhIWGh4iFDzyJjYcNEo6JSAaEGgtJgyZEkoIPGgODEgwKggZDJp2CAxoNAA8lDEUAKTE1jKopWBoKDwsMMw9TNQuOSUkuglVYWERJWFe6VjGuAFUKJsmESDNFKUgAGAaZgwKxAAILLFDFhjzeRUVViEgSBDghDJPxKY0LISGuOHKBYd4kD6USPVj4QJIJKkQakBvEo2JFAZJCiFhBI4eQVIKQWKwoCQcCGj0ufJlRyEXDTkVmzOiViIgblokU0IjU6EUeJy0a/ZjQQshLQ1ucKE2Dy5ACMFJaTLhgkNAXJ3m6DAFwwwtOQQpeeAnnA8EEG4Y8MMBlgA2cEylSVORY8OVMhBCDihw5emiFDh1gFITp8+LBCC1jVQE40+YJAAUgOOA94sZNqE4mYKiZVyWCA30ArJzB20mClKMtOnylAEVxIR8VXDfiQUW2bUOBAAAh+QQJCgAAACwAAAAAHAAcAAAH/4AAgoOEhYaHiIUuAomNhwpUjokPKYQGGkmDKSaSgi4zlYJUGowAMx4NnYIYRZVVWFiVCgsLPKoAAkVFSA8aGhgAJQtHjg9VLp6tM0kNJjwGDAupAC48RciEVQI8PJkCKdiCrxIASRpTVuSGSTxIPAJViElYNTUxJYna7o1HMTEakqo8aMTDg4JGM6aAYSApRYoiAsIBwABhzB4nTiZIkgAFB44hDGYIUgCBjRyMGh1x9GglZCEMC4ZckYRBQRFbiTDQAZgohQ0ijkKs0TOiEZQbKwhIJLRBxw4dXaYZwmClx4obP5YCINCGTZYQAIx4CTVyg4xqLLggEGLIA4VpCldAcNDS4AIJBkNQtGAhiBKRgYmMOHDAQoGWM2AAyCiz4haAEW+8TKygBSyWMmUMqOJRpwWyBy0iUBDkIQPfTiZIxBNEA41mQRIIOCYUo8zsRDx43t4tKBAAIfkECQoAAAAsAAAAABwAHAAAB/+AAIKDhIWGh4iGSYmMh0gzjYkuPIQYRQ+DPA2RgwKUgilFSIICV5ucAEhIn6ECqVgarqhJPDyLRUUKAFRYVI1HMZAALgJIAg8KGDwKGlinAEkKLoU1Tnt1BABVAtOEKb4PBhIMR4c+cU5OaymILiYlCwtHmIcxQU4fjAYMDFjdiApQSGBU5QgGRjOmEFgQCUMKZf8AKLgBAgiZNvkaURkSo8aUI+wAYJDSYcyONloibexIoYQwQS6oEPgxpOGMXPQOPdjCMFESCgcZHdFiYUROQ0dChCgRkRCFOg4cRMCCiIcGAjhCUDgq6AiHDhWyxShAhJACKFweJJHAAgoFQ1dfrAwQlKRMhAwpfnCZMkXEihqCHmAwUIXRkAgRoLiQgsIHABsrVDRl1OPMDQAPZIzAAcAEjRVzOT2gI+XTjREMBF0RUZMThhyyAGyYYGCQhtaoCJVQMjk3ISQafAtHFAgAIfkECQoAAAAsAAAAABwAHAAAB/+AAIKDhIWGh4iGD4mMh1UCjYkNXlWDSQKVgo+Rgkl3HZkCSEmdMwqcgnNOWoI8SDwAD0VFSKgAP05ONgACPLApKUUujAsesABIek46CkmuAjNFp4IPPIuEQ3p2dDgAJBEmhdAuLikDGljDhTY6OjtZM4guAlRYWFSZhmB9cF3Xhxg0aBjw75ABNVYaGcDACEkDA+EaVUmSJJ8gF2AmgDgRBkWkGQwWlJBA5ViSG3PqOHiTIFIDDwtESkhBqAqRKTgoROJRJAUmRlA8MHoggSEjA16yQKiFiEqMGFgSXaETQcsEKoiSYIlRI0YJdYRMuIkgxYcLCSs0gEVyxcq8K1NhhpQwxCDEgEE3WrQggsPHFCpQcGCNlYKIRUNXyrTA4aIHAigArOAYUrDRhgk0yF1YQQBAChwhGqB6IEbJNCMIpggaAOYKKgwXjAJggSAiAANHbBW6kgMsAN+6q7jWTfxQIAA7AAAAAAAAAAAA"), e.setAttribute("id", "rxp-loader-" + I), e.style.left = "50%", e.style.position = "fixed", e.style.background = "#FFFFFF", e.style.borderRadius = "50%", e.style.width = "30px", e.style.zIndex = "200", e.style.marginLeft = "-15px", e.style.top = "120px", e }, createIFrame: function (e, t) { var A = h.createSpinner(); document.body.appendChild(A); var i, n = document.createElement("iframe"); if (n.setAttribute("name", "rxp-frame-" + I), n.setAttribute("id", "rxp-frame-" + I), n.setAttribute("height", "562px"), n.setAttribute("frameBorder", "0"), n.setAttribute("width", "360px"), n.setAttribute("seamless", "seamless"), n.style.zIndex = "10001", n.style.position = "absolute", n.style.transition = "transform 0.5s ease-in-out", n.style.transform = "scale(0.7)", n.style.opacity = "0", e.appendChild(n), E) { n.style.top = "0px", n.style.bottom = "0px", n.style.left = "0px", n.style.marginLeft = "0px;", n.style.width = "100%", n.style.height = "100%", n.style.minHeight = "100%", n.style.WebkitTransform = "translate3d(0,0,0)", n.style.transform = "translate3d(0, 0, 0)"; var o = document.createElement("meta"); o.name = "viewport", o.content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0", document.getElementsByTagName("head")[0].appendChild(o) } else n.style.top = "40px", n.style.left = "50%", n.style.marginLeft = "-180px"; n.onload = function () { n.style.opacity = "1", n.style.transform = "scale(1)", n.style.backgroundColor = "#ffffff", A.parentNode && A.parentNode.removeChild(A), i = h.createCloseButton(), e.appendChild(i), i.addEventListener("click", function () { h.closeModal(i, n, A, e) }, !0) }; var r = h.createForm(document, t); return n.contentWindow.document.body ? n.contentWindow.document.body.appendChild(r) : n.contentWindow.document.appendChild(r), r.submit(), { spinner: A, iFrame: n, closeButton: i } }, openWindow: function (e) { var t = window.open(); if (!t) return null; var A = t.document, i = A.createElement("meta"), n = A.createAttribute("name"); n.value = "viewport", i.setAttributeNode(n); var o = A.createAttribute("content"); o.value = "width=device-width", i.setAttributeNode(o), A.head.appendChild(i); var r = h.createForm(A, e); return A.body.appendChild(r), r.submit(), t }, getUrlParser: function (e) { var t = document.createElement("a"); return t.href = e, t }, getHostnameFromUrl: function (e) { return h.getUrlParser(e).hostname }, isMessageFromHpp: function (e, t) { return h.getHostnameFromUrl(e) === h.getHostnameFromUrl(t) }, receiveMessage: function (d, s, c) { return function (e) { if (h.isMessageFromHpp(e.origin, l)) if (e.data && JSON.parse(e.data).iframe) { if (!C) { var t, A = JSON.parse(e.data).iframe.width, i = JSON.parse(e.data).iframe.height, n = !1; if (t = c ? d.getIframe() : document.getElementById("rxp-frame-" + I), "390px" === A && "440px" === i && (t.setAttribute("width", A), t.setAttribute("height", i), n = !0), t.style.backgroundColor = "#ffffff", E) { if (t.style.marginLeft = "0px", t.style.WebkitOverflowScrolling = "touch", t.style.overflowX = "scroll", t.style.overflowY = "scroll", !c) { var o = document.getElementById("rxp-overlay-" + I); o.style.overflowX = "scroll", o.style.overflowY = "scroll" } } else !c && n && (t.style.marginLeft = parseInt(A.replace("px", ""), 10) / 2 * -1 + "px"); !c && n && setTimeout(function () { document.getElementById("rxp-frame-close-" + I).style.marginLeft = parseInt(A.replace("px", ""), 10) / 2 - 7 + "px" }, 200) } } else { C && g ? g.close() : d.close(); var r = e.data, a = document.createElement("form"); a.setAttribute("method", "POST"), a.setAttribute("action", s), a.appendChild(h.createFormHiddenInput("hppResponse", r)), document.body.appendChild(a), a.submit() } } } }, r = { getInstance: function (e) { var t, A; return i || (h.checkDevicesOrientation(), E && window.addEventListener && window.addEventListener("orientationchange", function () { h.checkDevicesOrientation() }, !1), i = { lightbox: function () { if (C) g = h.openWindow(A); else { t = h.createOverlay(); var e = h.createIFrame(t, A); e.spinner, e.iFrame, e.closeButton } }, close: function () { h.closeModal() }, setToken: function (e) { A = e } }), i.setToken(e), i }, init: function (e, t, A) { var i = r.getInstance(A); document.getElementById(e).addEventListener ? document.getElementById(e).addEventListener("click", i.lightbox, !0) : document.getElementById(e).attachEvent("onclick", i.lightbox), window.addEventListener ? window.addEventListener("message", h.receiveMessage(i, t), !1) : window.attachEvent("message", h.receiveMessage(i, t)) } }, a = { getInstance: function (e) { var t, A; return n || (n = { embedded: function () { var e = h.createForm(document, A); t && (t.contentWindow.document.body ? t.contentWindow.document.body.appendChild(e) : t.contentWindow.document.appendChild(e), e.submit(), t.style.display = "inherit") }, close: function () { t.style.display = "none" }, setToken: function (e) { A = e }, setIframe: function (e) { t = document.getElementById(e) }, getIframe: function () { return t } }), n.setToken(e), n }, init: function (e, t, A, i) { var n = a.getInstance(i); n.setIframe(t), document.getElementById(e).addEventListener ? document.getElementById(e).addEventListener("click", n.embedded, !0) : document.getElementById(e).attachEvent("onclick", n.embedded), window.addEventListener ? window.addEventListener("message", h.receiveMessage(n, A, !0), !1) : window.attachEvent("message", h.receiveMessage(n, A, !0)) } }, s = { getInstance: function (e) { var t; return A || (h.checkDevicesOrientation(), E && window.addEventListener && window.addEventListener("orientationchange", function () { h.checkDevicesOrientation() }, !1), A = { redirect: function () { var e = h.createForm(document, t, !0); document.body.append(e), e.submit() }, setToken: function (e) { t = e } }), A.setToken(e), A }, init: function (e, t, A) { var i = s.getInstance(A); d = t, document.getElementById(e).addEventListener ? document.getElementById(e).addEventListener("click", i.redirect, !0) : document.getElementById(e).attachEvent("onclick", i.redirect), window.addEventListener ? window.addEventListener("message", h.receiveMessage(i, t), !1) : window.attachEvent("message", h.receiveMessage(i, t)) } }; return { init: r.init, lightbox: { init: r.init }, embedded: { init: a.init }, redirect: { init: s.init }, setHppUrl: function (e) { l = e }, _internal: h } }(), RealexRemote = function () { "use strict"; var r = function (e) { if (!/^\d{4}$/.test(e)) return !1; var t = parseInt(e.substring(0, 2), 10); parseInt(e.substring(2, 4), 10); return !(t < 1 || 12 < t) }; return { validateCardNumber: function (e) { if (!/^\d{12,19}$/.test(e)) return !1; for (var t = 0, A = 0, i = 0, n = !1, o = e.length - 1; 0 <= o; o--)A = parseInt(e.substring(o, o + 1), 10), n ? 9 < (i = 2 * A) && (i -= 9) : i = A, t += i, n = !n; return 0 == t % 10 }, validateCardHolderName: function (e) { return !!e && !!e.trim() && !!/^[\u0020-\u007E\u00A0-\u00FF]{1,100}$/.test(e) }, validateCvn: function (e) { return !!/^\d{3}$/.test(e) }, validateAmexCvn: function (e) { return !!/^\d{4}$/.test(e) }, validateExpiryDateFormat: r, validateExpiryDateNotInPast: function (e) { if (!r(e)) return !1; var t = parseInt(e.substring(0, 2), 10), A = parseInt(e.substring(2, 4), 10), i = new Date, n = i.getMonth() + 1, o = i.getFullYear(); return !(A < o % 100 || A === o % 100 && t < n) } } }();
var portal;
(function (portal) {
    var general;
    (function (general) {
        var forgotpassword;
        (function (forgotpassword) {
            "use strict";
            function InitializeForgotPassword($container) {
                new ForgotPassword($container);
            }
            forgotpassword.InitializeForgotPassword = InitializeForgotPassword;
            var ForgotPassword = (function () {
                function ForgotPassword($container) {
                    var _this = this;
                    this.$container = $container;
                    this.$forgottenPasswordButton = this.$container.find(".ui-btn-forgotten-password");
                    this.$userName = this.$container.GetControl("Username");
                    this.model = starrez.model.ForgotPasswordModel(this.$container);
                    this.$container.on("keydown", function (e) {
                        if (e.keyCode === starrez.keyboard.EnterCode) {
                            starrez.library.utils.SafeStopPropagation(e);
                            _this.$forgottenPasswordButton.trigger("click");
                        }
                    });
                    this.$forgottenPasswordButton.SRClick(function () {
                        if (starrez.library.stringhelper.IsUndefinedOrEmpty(_this.$userName.SRVal())) {
                            portal.page.CurrentPage.SetErrorMessage(_this.model.UsernameRequiredErrorMessage);
                            return;
                        }
                        var call = new starrez.service.register.ForgottenPassword({
                            username: _this.$userName.SRVal(),
                            portalPageID: portal.page.CurrentPage.PageID
                        });
                        call.Post().done(function (result) {
                            if (result.Success) {
                                portal.page.CurrentPage.SetSuccessMessage(result.PasswordChangeRequestConfirmationMessage);
                                _this.$forgottenPasswordButton.SRHide();
                                _this.$container.off("keydown");
                                _this.$container.on("keydown", function (e) {
                                    // Block page submit on enter.  Do nothing.
                                    if (e.keyCode === starrez.keyboard.EnterCode) {
                                        starrez.library.utils.SafeStopPropagation(e);
                                    }
                                });
                            }
                            else {
                                portal.page.CurrentPage.SetErrorMessage(result.PasswordChangeRequestErrorMessage);
                            }
                        });
                    });
                }
                return ForgotPassword;
            })();
        })(forgotpassword = general.forgotpassword || (general.forgotpassword = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var register;
        (function (register) {
            "use strict";
            var editorDataName = "Editor";
            function InitializeLoginWidget($container) {
                var widget = starrez.model.WidgetModelBaseModel($container);
                $container.data(editorDataName, new LoginWidget($container, widget.PortalPageWidgetID));
            }
            register.InitializeLoginWidget = InitializeLoginWidget;
            var LoginWidget = (function () {
                function LoginWidget($container, portalPageWidgetID) {
                    this.$container = $container;
                    this.portalPageWidgetID = portalPageWidgetID;
                    this.$userName = this.$container.GetControl("Username");
                    this.$password = this.$container.GetControl("Password");
                    this.$rememberLogin = this.$container.GetControl("RememberLogin");
                    this.model = starrez.model.LoginWidgetModel(this.$container);
                    this.AttachEvents();
                    if (this.$userName.SRVal() === "") {
                        this.$userName.SRFocus();
                    }
                    else {
                        this.$password.SRFocus();
                    }
                }
                LoginWidget.prototype.AttachEvents = function () {
                    var _this = this;
                    var $loginButton = this.$container.find(".ui-btn-login");
                    var returnUrl = $loginButton.data("url");
                    $loginButton.SRClick(function () {
                        var studentFacingErrors = [];
                        if (starrez.library.stringhelper.IsUndefinedOrEmpty(_this.$userName.SRVal())) {
                            studentFacingErrors.push(_this.model.UsernameRequiredErrorMessage);
                        }
                        if (starrez.library.stringhelper.IsUndefinedOrEmpty(_this.$password.SRVal())) {
                            studentFacingErrors.push(_this.model.PasswordRequiredErrorMessage);
                        }
                        if (studentFacingErrors.length > 0) {
                            portal.page.CurrentPage.SetErrorMessages(studentFacingErrors);
                            return;
                        }
                        var call = new starrez.service.register.Login({
                            pageID: portal.page.CurrentPage.PageID,
                            username: _this.$userName.SRVal(),
                            password: _this.$password.SRVal(),
                            rememberLogin: _this.$rememberLogin.isFound() ? _this.$rememberLogin.SRVal() : false,
                            invalidCredentialsMessage: _this.model.InvalidCredentialsMessage,
                            returnUrl: returnUrl
                        });
                        call.Post().done(function (result) {
                            if (starrez.library.stringhelper.IsUndefinedOrEmpty(result.ErrorMessage)) {
                                window.location.href = result.ReturnUrl;
                            }
                            else {
                                _this.$password.SRVal('');
                                portal.page.CurrentPage.SetErrorMessage(result.ErrorMessage);
                                _this.SetPasswordControlFocus();
                            }
                        });
                    });
                    this.$container.on("keyup", function (e) {
                        if (e.keyCode === starrez.keyboard.EnterCode) {
                            $loginButton.trigger("click");
                        }
                    });
                };
                LoginWidget.prototype.SetPasswordControlFocus = function () {
                    var _this = this;
                    window.setTimeout(function () { _this.$password.SRFocus(); }, 100);
                };
                return LoginWidget;
            })();
        })(register = general.register || (general.register = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var updatecredentials;
        (function (updatecredentials) {
            "use strict";
            function InitialiseFieldListEditor($container) {
                portal.fieldlist.control.InitFieldListManager($container, function (existingFields) { return new starrez.service.register.CreateNewField({
                    existingFields: existingFields
                }); });
            }
            updatecredentials.InitialiseFieldListEditor = InitialiseFieldListEditor;
            function InitialiseMatchManager($container) {
                new MatchManager($container);
            }
            updatecredentials.InitialiseMatchManager = InitialiseMatchManager;
            var MatchManager = (function () {
                function MatchManager($container) {
                    var _this = this;
                    this.$container = $container;
                    var $button = this.$container.find(".ui-submit-credentials");
                    $button.SRClick(function () { return _this.SubmitUpgrade(); });
                    this.hash = $button.data("hash").toString();
                    this.SetupSubmitOnEnter();
                }
                MatchManager.prototype.SetupSubmitOnEnter = function () {
                    var _this = this;
                    this.$container.keydown(function (e) {
                        if (e.keyCode === starrez.keyboard.EnterCode) {
                            _this.SubmitUpgrade();
                            // The browsers have a behaviour where they will automatically submit the form if there is only one
                            // input field on it. This is not what we want to do, so call SafeStopPropagation to block this from happening.
                            // http://stackoverflow.com/questions/1370021/why-does-forms-with-single-input-field-submit-upon-pressing-enter-key-in-input
                            starrez.library.utils.SafeStopPropagation(e);
                        }
                    });
                };
                MatchManager.prototype.SubmitUpgrade = function () {
                    var $allFields = this.$container.find(".ui-field");
                    var dictionary = new starrez.library.collections.KeyValue();
                    // build up the dictionary of values to send to the server
                    this.$container.GetAllControls().each(function (index, ctrl) {
                        var $ctrl = $(ctrl);
                        var key = $ctrl.closest("li").data("field-id").toString();
                        var value = $ctrl.SRVal();
                        dictionary.Add(key, value);
                    });
                    var call = new starrez.service.register.MatchCredentials({
                        hash: this.hash,
                        pageID: portal.page.CurrentPage.PageID,
                        values: dictionary.ToArray()
                    }).Post().done(function (message) {
                        // email sent
                        portal.page.CurrentPage.SetSuccessMessage(message);
                    });
                };
                return MatchManager;
            })();
        })(updatecredentials = general.updatecredentials || (general.updatecredentials = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN

    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function ForgotPasswordModel($sys) {
            return {
                PasswordChangeRequestConfirmationMessage: $sys.data('passwordchangerequestconfirmationmessage'),
                PasswordChangeRequestErrorMessage: $sys.data('passwordchangerequesterrormessage'),
                UsernameRequiredErrorMessage: $sys.data('usernamerequirederrormessage')
            };
        }
        model.ForgotPasswordModel = ForgotPasswordModel;
        function LoginModel($sys) {
            return {};
        }
        model.LoginModel = LoginModel;
        function LoginWidgetModel($sys) {
            return {
                InvalidCredentialsMessage: $sys.data('invalidcredentialsmessage'),
                Password: $sys.data('password'),
                PasswordRequiredErrorMessage: $sys.data('passwordrequirederrormessage'),
                RememberLogin: starrez.library.convert.ToBoolean($sys.data('rememberlogin')),
                Username: $sys.data('username'),
                UsernameRequiredErrorMessage: $sys.data('usernamerequirederrormessage')
            };
        }
        model.LoginWidgetModel = LoginWidgetModel;
        function UpdateCredentialsModel($sys) {
            return {};
        }
        model.UpdateCredentialsModel = UpdateCredentialsModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var register;
        (function (register) {
            "use strict";
            var CreateNewField = (function (_super) {
                __extends(CreateNewField, _super);
                function CreateNewField(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Register";
                    this.Controller = "register";
                    this.Action = "CreateNewField";
                }
                CreateNewField.prototype.CallData = function () {
                    var obj = {
                        existingFields: this.o.existingFields
                    };
                    return obj;
                };
                return CreateNewField;
            })(starrez.library.service.AddInActionCallBase);
            register.CreateNewField = CreateNewField;
            var ForgottenPassword = (function (_super) {
                __extends(ForgottenPassword, _super);
                function ForgottenPassword(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Register";
                    this.Controller = "register";
                    this.Action = "ForgottenPassword";
                }
                ForgottenPassword.prototype.CallData = function () {
                    var obj = {
                        portalPageID: this.o.portalPageID,
                        username: this.o.username
                    };
                    return obj;
                };
                return ForgottenPassword;
            })(starrez.library.service.AddInActionCallBase);
            register.ForgottenPassword = ForgottenPassword;
            var Login = (function (_super) {
                __extends(Login, _super);
                function Login(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Register";
                    this.Controller = "register";
                    this.Action = "Login";
                }
                Login.prototype.CallData = function () {
                    var obj = {
                        invalidCredentialsMessage: this.o.invalidCredentialsMessage,
                        pageID: this.o.pageID,
                        password: this.o.password,
                        rememberLogin: this.o.rememberLogin,
                        returnUrl: this.o.returnUrl,
                        username: this.o.username
                    };
                    return obj;
                };
                return Login;
            })(starrez.library.service.AddInActionCallBase);
            register.Login = Login;
            var MatchCredentials = (function (_super) {
                __extends(MatchCredentials, _super);
                function MatchCredentials(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Register";
                    this.Controller = "register";
                    this.Action = "MatchCredentials";
                }
                MatchCredentials.prototype.CallData = function () {
                    var obj = {
                        values: this.o.values
                    };
                    return obj;
                };
                MatchCredentials.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return MatchCredentials;
            })(starrez.library.service.AddInActionCallBase);
            register.MatchCredentials = MatchCredentials;
        })(register = service.register || (service.register = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

/// <reference path="../../../../WebCommon/TypeScriptTypes/lib.d.ts" />
var portal;
(function (portal) {
    var general;
    (function (general) {
        var bookedresources;
        (function (bookedresources) {
            "use strict";
            function InitBookedResourcesPage($container) {
                new ManageResourcesModel($container);
            }
            bookedresources.InitBookedResourcesPage = InitBookedResourcesPage;
        })(bookedresources = general.bookedresources || (general.bookedresources = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));
var ManageResourcesModel = (function () {
    function ManageResourcesModel($container) {
        this.$container = $container;
        this.pageID = portal.page.CurrentPage.PageID;
        this.model = starrez.model.BookedResourcesModel($container);
        portal.actionpanel.control.AutoAdjustActionPanelHeights($container);
        this.AttachEvents();
    }
    ManageResourcesModel.prototype.AttachEvents = function () {
        var _this = this;
        this.$container.on("click", ".ui-cancel-resource", function (e) {
            var $currentTarget = $(e.currentTarget);
            var $button = $currentTarget.closest(".ui-cancel-resource");
            var $actionPanel = $currentTarget.closest(".ui-action-panel");
            portal.ConfirmAction(_this.model.CancelResourceConfirmation, "Manage Resources").done(function () {
                var call = new starrez.service.resources.CancelResourceRequest({
                    pageID: _this.pageID,
                    resourceBookingID: Number($actionPanel.data("resourcebookingid")),
                    hash: $button.data("hash")
                });
                call.Post().done(function (result) {
                    // Remove the cancelled resource from the list
                    var $actionPanel = $currentTarget.closest(".ui-action-panel");
                    $actionPanel.remove();
                });
            });
        });
    };
    return ManageResourcesModel;
})();

/// <reference path="../../../../WebCommon/TypeScriptTypes/lib.d.ts" />
var portal;
(function (portal) {
    var general;
    (function (general) {
        var requestresource;
        (function (requestresource) {
            "use strict";
            function InitResourceSelectionPage($container) {
                new ResourceSelectionModel($container);
            }
            requestresource.InitResourceSelectionPage = InitResourceSelectionPage;
            var ResourceSelectionModel = (function () {
                function ResourceSelectionModel($container) {
                    this.$container = $container;
                    this.LoadResults();
                    this.AttachEvents();
                    this.model = starrez.model.RequestResourceModel($container);
                }
                ResourceSelectionModel.prototype.LoadResults = function () {
                    var _this = this;
                    this.pageID = portal.page.CurrentPage.PageID;
                    this.$resultsContainer = this.$container.find(".ui-results");
                    this.$noResultsContainer = this.$container.find(".ui-no-results");
                    this.$filtersContainer = this.$container.find(".ui-filters");
                    this.filters = {
                        LocationIDs: this.$filtersContainer.GetControl("RoomLocationID").SRVal(),
                        LocationAreaIDs: this.$filtersContainer.GetControl("RoomLocationAreaID").SRVal(),
                        ResourceTypeIDs: this.$filtersContainer.GetControl("ResourceTypeID").SRVal(),
                        SearchString: this.$filtersContainer.GetControl("ResourceName").SRVal()
                    };
                    new starrez.service.resources.GetFilterResults({
                        pageID: this.pageID,
                        filters: this.filters,
                        dateStart: this.$container.GetControl("DateStart").SRVal(),
                        dateEnd: this.$container.GetControl("DateEnd").SRVal()
                    }).Post().done(function (result) {
                        _this.$resultsContainer.html($.toHTML(result.ResultsHtml));
                        portal.actionpanel.control.AutoAdjustActionPanelHeights(_this.$container);
                    });
                };
                ResourceSelectionModel.prototype.SetupAssignResourceAction = function () {
                    var _this = this;
                    this.$container.on("click", ".ui-add-item-to-cart", function (e) {
                        var $currentTarget = $(e.currentTarget);
                        var $button = $currentTarget.closest(".ui-add-item-to-cart");
                        var $itemResult = $currentTarget.closest(".ui-card-result");
                        portal.ConfirmAction(_this.model.ConfirmAssignResourceMessage, "Request Resource").done(function () {
                            var call = new starrez.service.resources.RequestResource({
                                resourceID: Number($itemResult.data("resourceid")),
                                pageID: _this.pageID,
                                dateStart: _this.$container.GetControl("DateStart").SRVal(),
                                dateEnd: _this.$container.GetControl("DateEnd").SRVal(),
                                hash: $button.data("hash")
                            });
                            call.Post().done(function (result) {
                                // Navigate to the page which shows the booked resource
                                location.href = _this.model.BookedResourcesPageUrl;
                            });
                        });
                    });
                };
                ResourceSelectionModel.prototype.AttachEvents = function () {
                    var _this = this;
                    var $searchField = this.$filtersContainer.GetControl("ResourceName");
                    this.$filtersContainer.GetAllControls().find("select").change(function (e) {
                        _this.LoadResults();
                    });
                    this.$container.GetControl("DateStart").change(function (e) {
                        _this.LoadResults();
                    });
                    this.$container.GetControl("DateEnd").change(function (e) {
                        _this.LoadResults();
                    });
                    new starrez.library.ui.KeyboardSearchListener($searchField, function (searchTerm) {
                        _this.LoadResults();
                    });
                    this.SetupAssignResourceAction();
                    portal.mobile.SetupExpandAndCollapse(this.$container);
                };
                return ResourceSelectionModel;
            })();
            ;
        })(requestresource = general.requestresource || (general.requestresource = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function BookedResourcesModel($sys) {
            return {
                CancelResourceConfirmation: $sys.data('cancelresourceconfirmation')
            };
        }
        model.BookedResourcesModel = BookedResourcesModel;
        function RequestResourceModel($sys) {
            return {
                BookedResourcesPageUrl: $sys.data('bookedresourcespageurl'),
                ConfirmAssignResourceMessage: $sys.data('confirmassignresourcemessage'),
                ResourceTypeID: ($sys.data('resourcetypeid') === '') ? [] : ($sys.data('resourcetypeid')).toString().split(',').map(function (e) { return Number(e); }),
                RoomLocationAreaID: ($sys.data('roomlocationareaid') === '') ? [] : ($sys.data('roomlocationareaid')).toString().split(',').map(function (e) { return Number(e); }),
                RoomLocationID: ($sys.data('roomlocationid') === '') ? [] : ($sys.data('roomlocationid')).toString().split(',').map(function (e) { return Number(e); })
            };
        }
        model.RequestResourceModel = RequestResourceModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var resources;
        (function (resources) {
            "use strict";
            var CancelResourceRequest = (function (_super) {
                __extends(CancelResourceRequest, _super);
                function CancelResourceRequest(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Resources";
                    this.Controller = "resources";
                    this.Action = "CancelResourceRequest";
                }
                CancelResourceRequest.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                CancelResourceRequest.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID,
                        resourceBookingID: this.o.resourceBookingID
                    };
                    return obj;
                };
                return CancelResourceRequest;
            })(starrez.library.service.AddInActionCallBase);
            resources.CancelResourceRequest = CancelResourceRequest;
            var GetFilterResults = (function (_super) {
                __extends(GetFilterResults, _super);
                function GetFilterResults(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Resources";
                    this.Controller = "resources";
                    this.Action = "GetFilterResults";
                }
                GetFilterResults.prototype.CallData = function () {
                    var obj = {
                        dateEnd: this.o.dateEnd,
                        dateStart: this.o.dateStart,
                        filters: this.o.filters,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return GetFilterResults;
            })(starrez.library.service.AddInActionCallBase);
            resources.GetFilterResults = GetFilterResults;
            var RequestResource = (function (_super) {
                __extends(RequestResource, _super);
                function RequestResource(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Resources";
                    this.Controller = "resources";
                    this.Action = "RequestResource";
                }
                RequestResource.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                RequestResource.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        dateEnd: this.o.dateEnd,
                        dateStart: this.o.dateStart,
                        pageID: this.o.pageID,
                        resourceID: this.o.resourceID
                    };
                    return obj;
                };
                return RequestResource;
            })(starrez.library.service.AddInActionCallBase);
            resources.RequestResource = RequestResource;
        })(resources = service.resources || (service.resources = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var roommaintenance;
        (function (roommaintenance) {
            "use strict";
            function InitialiseJobTable($container) {
                new JobList($container);
            }
            roommaintenance.InitialiseJobTable = InitialiseJobTable;
            function InitialiseJobDetail($container) {
                new JobDetail($container);
            }
            roommaintenance.InitialiseJobDetail = InitialiseJobDetail;
            var JobList = (function () {
                function JobList($container) {
                    var _this = this;
                    this.$container = $container;
                    this.$jobTypeControl = this.$container.GetControl(JobList.JobTypePropertyName);
                    this.$tableDiv = $('.ui-jobs-table-div');
                    this.pageID = Number($container.data('portalpageid'));
                    var model = starrez.model.MaintenanceModel($container);
                    this.$jobTypeControl.change(function (e) {
                        _this.GetJobs();
                    });
                    this.GetJobs();
                    var $addJobButton = this.$container.find('.ui-btn-add-job');
                    $addJobButton.SRClick(function () {
                        _this.roomSpaceMaintenanceHash = model.NewJobUrlHash;
                        _this.NavigateToDetailPage(-1);
                    });
                    this.$container.SRClickDelegate("roommaintenance", ".ui-viewedit-job", function (e) {
                        var $row = $(e.currentTarget).closest('tr');
                        _this.roomSpaceMaintenanceHash = $row.data("hash").toString();
                        _this.NavigateToDetailPage($row.data('roomspacemaintenance'));
                    });
                }
                ;
                JobList.prototype.GetJobs = function () {
                    var _this = this;
                    var call = new starrez.service.roommaintenance.GetMaintenaceJobs({
                        pageID: this.pageID,
                        jobType: this.Get(JobList.JobTypePropertyName)
                    });
                    call.Get().done(function (result) {
                        _this.$tableDiv.html(result);
                    });
                };
                JobList.prototype.NavigateToDetailPage = function (roomSpaceMaintenanceID) {
                    new starrez.service.roommaintenance.GetJobDetailUrl({
                        pageID: this.pageID,
                        roomSpaceMaintenanceID: roomSpaceMaintenanceID,
                        hash: this.roomSpaceMaintenanceHash
                    }).Post().done(function (url) {
                        location.href = url;
                    });
                };
                JobList.prototype.Get = function (controlName) {
                    return this.$container.GetControl(controlName).SRVal();
                };
                JobList.JobTypePropertyName = 'JobType';
                return JobList;
            })();
            var JobDetail = (function () {
                function JobDetail($container) {
                    var _this = this;
                    this.$container = $container;
                    this.$detailContainer = $container;
                    this.$roomTypeControl = this.$container.GetControl(JobDetail.RoomTypePropertyName);
                    this.$tableDiv = $('.ui-rooms-table-div');
                    this.$roomSpaceMaintenanceCategoryIDControl = this.$container.GetControl(JobDetail.RoomSpaceMaintenanceCategoryIDPropertyName);
                    this.$roomSpaceMaintenanceItemIDControl = this.$container.GetControl(JobDetail.RoomSpaceMaintenanceItemIDPropertyName);
                    var model = starrez.model.MaintenanceJobDetailModel($container);
                    this.roomSpaceMaintenanceID = model.RoomSpaceMaintenanceID;
                    this.roomSpaceID = model.RoomSpaceID;
                    this.isNew = model.IsNew;
                    this.pageID = Number($container.data('portalpageid'));
                    this.$roomTypeControl.change(function (e) {
                        _this.GetRooms();
                        _this.roomSpaceID = -1;
                    });
                    this.GetRooms();
                    this.$roomSpaceMaintenanceCategoryIDControl.change(function (e) {
                        var call = new starrez.service.roommaintenance.GetMaintenanceItems({
                            pageID: _this.pageID,
                            categoryID: _this.Get(JobDetail.RoomSpaceMaintenanceCategoryIDPropertyName),
                            roomSpaceMaintenanceID: model.RoomSpaceMaintenanceID
                        });
                        call.Get().done(function (json) {
                            starrez.library.controls.dropdown.FillDropDown(json, _this.$roomSpaceMaintenanceItemIDControl, "Value", "Text", "", false);
                        });
                    });
                    var $saveButton = portal.PageElements.$actions.find('.ui-btn-save');
                    $saveButton.SRClick(function () {
                        var jobDetail = _this.GetJobDetail();
                        if (portal.validation.ValidateForm($container, true)) {
                            var call = new starrez.service.roommaintenance.SaveJob({
                                jobDetail: jobDetail
                            });
                            return call.Post().done(function (json) {
                                portal.page.CurrentPage.SubmitPage();
                            });
                        }
                    });
                    var $closeButton = portal.PageElements.$actions.find('.ui-btn-close-job');
                    $closeButton.SRClick(function () {
                        var jobDetail = _this.GetJobDetail();
                        var call = new starrez.service.roommaintenance.CloseJob({
                            jobDetail: jobDetail
                        });
                        return call.Post().done(function (json) {
                            portal.page.CurrentPage.SubmitPage();
                        });
                    });
                }
                JobDetail.prototype.GetJobDetail = function () {
                    var jobDetail = {
                        RoomSpaceID: this.roomSpaceID,
                        RoomSpaceMaintenanceID: this.roomSpaceMaintenanceID,
                        Cause: this.Get(JobDetail.CausePropertyName),
                        Comments: this.Get(JobDetail.CommentsPropertyName),
                        Description: this.Get(JobDetail.DescriptionPropertyName),
                        OccupantPresent: this.Get(JobDetail.OccupantPresentPropertyName),
                        JobStatus: this.Get(JobDetail.StatusPropertyName),
                        RoomSpaceMaintenanceCategoryID: this.Get(JobDetail.RoomSpaceMaintenanceCategoryIDPropertyName),
                        RoomSpaceMaintenanceItemID: this.Get(JobDetail.RoomSpaceMaintenanceItemIDPropertyName),
                        RepairDescription: this.Get(JobDetail.RepairDescriptionPropertyName),
                        IsNew: this.isNew,
                        PortalPageID: this.pageID
                    };
                    return jobDetail;
                };
                JobDetail.prototype.GetRooms = function () {
                    var _this = this;
                    var call = new starrez.service.roommaintenance.GetRooms({
                        pageID: this.pageID,
                        roomSpaceID: this.roomSpaceID,
                        roomSpaceMaintenanceID: this.roomSpaceMaintenanceID,
                        roomType: this.Get(JobDetail.RoomTypePropertyName)
                    });
                    call.Get().done(function (result) {
                        _this.$tableDiv.html(result);
                        var tableManagers = starrez.tablesetup.CreateTableManager(_this.$container.find('.ui-active-table'), _this.$container.find('.ui-rooms-table-div'), {
                            AttachRowClickEvent: _this.isNew,
                            OnRowClick: function ($tr, $data, e, sender) {
                                if ($tr.isSelected()) {
                                    _this.roomSpaceID = $tr.data('roomspace');
                                }
                                else {
                                    _this.roomSpaceID = -1;
                                }
                            }
                        });
                        _this.tableManager = tableManagers[0];
                        _this.AttachFocusEvents();
                    });
                };
                JobDetail.prototype.Get = function (controlName) {
                    return this.$container.GetControl(controlName).SRVal();
                };
                JobDetail.prototype.AttachFocusEvents = function () {
                    var _this = this;
                    this.$container.find('.ui-rooms-table-div').on("focusin", function (e) {
                        _this.tableManager.DisplayFocus(true);
                    });
                    this.$container.find('.ui-rooms-table-div').on("focusout", function (e) {
                        _this.tableManager.DisplayFocus(false);
                    });
                };
                JobDetail.CausePropertyName = 'Cause';
                JobDetail.CommentsPropertyName = 'Comments';
                JobDetail.DateReportedPropertyName = 'DateReported';
                JobDetail.DescriptionPropertyName = 'Description';
                JobDetail.OccupantPresentPropertyName = 'OccupantPresent';
                JobDetail.StatusPropertyName = 'JobStatus';
                JobDetail.RoomTypePropertyName = 'RoomType';
                JobDetail.RoomSpaceMaintenanceCategoryIDPropertyName = 'RoomSpaceMaintenanceCategoryID';
                JobDetail.RoomSpaceMaintenanceItemIDPropertyName = 'RoomSpaceMaintenanceItemID';
                JobDetail.RepairDescriptionPropertyName = 'RepairDescription';
                return JobDetail;
            })();
        })(roommaintenance = general.roommaintenance || (general.roommaintenance = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function MaintenanceModel($sys) {
            return {
                NewJobUrlHash: $sys.data('newjoburlhash')
            };
        }
        model.MaintenanceModel = MaintenanceModel;
        function MaintenanceJobDetailModel($sys) {
            return {
                IsNew: starrez.library.convert.ToBoolean($sys.data('isnew')),
                RoomSpaceID: Number($sys.data('roomspaceid')),
                RoomSpaceMaintenanceID: Number($sys.data('roomspacemaintenanceid'))
            };
        }
        model.MaintenanceJobDetailModel = MaintenanceJobDetailModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var roommaintenance;
        (function (roommaintenance) {
            "use strict";
            var CloseJob = (function (_super) {
                __extends(CloseJob, _super);
                function CloseJob(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomMaintenance";
                    this.Controller = "roommaintenance";
                    this.Action = "CloseJob";
                }
                CloseJob.prototype.CallData = function () {
                    var obj = {
                        jobDetail: this.o.jobDetail
                    };
                    return obj;
                };
                return CloseJob;
            })(starrez.library.service.AddInActionCallBase);
            roommaintenance.CloseJob = CloseJob;
            var GetJobDetailUrl = (function (_super) {
                __extends(GetJobDetailUrl, _super);
                function GetJobDetailUrl(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomMaintenance";
                    this.Controller = "roommaintenance";
                    this.Action = "GetJobDetailUrl";
                }
                GetJobDetailUrl.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                GetJobDetailUrl.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID,
                        roomSpaceMaintenanceID: this.o.roomSpaceMaintenanceID
                    };
                    return obj;
                };
                return GetJobDetailUrl;
            })(starrez.library.service.AddInActionCallBase);
            roommaintenance.GetJobDetailUrl = GetJobDetailUrl;
            var GetMaintenaceJobs = (function (_super) {
                __extends(GetMaintenaceJobs, _super);
                function GetMaintenaceJobs(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomMaintenance";
                    this.Controller = "roommaintenance";
                    this.Action = "GetMaintenaceJobs";
                }
                GetMaintenaceJobs.prototype.CallData = function () {
                    var obj = {
                        jobType: this.o.jobType,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return GetMaintenaceJobs;
            })(starrez.library.service.AddInActionCallBase);
            roommaintenance.GetMaintenaceJobs = GetMaintenaceJobs;
            var GetMaintenanceItems = (function (_super) {
                __extends(GetMaintenanceItems, _super);
                function GetMaintenanceItems(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomMaintenance";
                    this.Controller = "roommaintenance";
                    this.Action = "GetMaintenanceItems";
                }
                GetMaintenanceItems.prototype.CallData = function () {
                    var obj = {
                        categoryID: this.o.categoryID,
                        pageID: this.o.pageID,
                        roomSpaceMaintenanceID: this.o.roomSpaceMaintenanceID
                    };
                    return obj;
                };
                return GetMaintenanceItems;
            })(starrez.library.service.AddInActionCallBase);
            roommaintenance.GetMaintenanceItems = GetMaintenanceItems;
            var GetRooms = (function (_super) {
                __extends(GetRooms, _super);
                function GetRooms(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomMaintenance";
                    this.Controller = "roommaintenance";
                    this.Action = "GetRooms";
                }
                GetRooms.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID,
                        roomSpaceID: this.o.roomSpaceID,
                        roomSpaceMaintenanceID: this.o.roomSpaceMaintenanceID,
                        roomType: this.o.roomType
                    };
                    return obj;
                };
                return GetRooms;
            })(starrez.library.service.AddInActionCallBase);
            roommaintenance.GetRooms = GetRooms;
            var SaveJob = (function (_super) {
                __extends(SaveJob, _super);
                function SaveJob(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomMaintenance";
                    this.Controller = "roommaintenance";
                    this.Action = "SaveJob";
                }
                SaveJob.prototype.CallData = function () {
                    var obj = {
                        jobDetail: this.o.jobDetail
                    };
                    return obj;
                };
                return SaveJob;
            })(starrez.library.service.AddInActionCallBase);
            roommaintenance.SaveJob = SaveJob;
        })(roommaintenance = service.roommaintenance || (service.roommaintenance = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var roommates;
        (function (roommates) {
            var groupsearch;
            (function (groupsearch) {
                "use strict";
                function Initialise($container) {
                    groupsearch.Model = new RoommateGroupSearch($container);
                }
                groupsearch.Initialise = Initialise;
                var RoommateGroupSearch = (function () {
                    function RoommateGroupSearch($container) {
                        this.$container = $container;
                        this.isSearching = false;
                        this.isDirty = false;
                        this.model = starrez.model.RoommateGroupSearchModel($container);
                        this.$filtersContainer = this.$container.find(".ui-filters");
                        this.$resultsContainer = this.$container.find(".ui-results");
                        this.$filterIcon = this.$filtersContainer.find(".ui-filter-icon");
                        this.$filterBody = this.$filtersContainer.find(".ui-filter-body");
                        this.$includeUnlimitedSizeGroup = this.$container.GetControl("IncludeUnlimitedSizeGroup");
                        this.$minGroupSize = this.$filtersContainer.GetControl("MinGroupSize");
                        this.$maxGroupSize = this.$filtersContainer.GetControl("MaxGroupSize");
                        this.$groupName = this.$filtersContainer.GetControl("GroupName");
                        this.$entryNameWeb = this.$filtersContainer.GetControl("EntryNameWeb");
                        this.$profileItemFilters = this.$filtersContainer.GetControl("ProfileItemID").toArray();
                        this.Initialise();
                    }
                    RoommateGroupSearch.prototype.Initialise = function () {
                        this.AttachEvents();
                        if (this.model.CurrentPageNumber == 0) {
                            this.model.CurrentPageNumber = 1;
                        }
                        this.LoadResults(this.model.CurrentPageNumber);
                    };
                    RoommateGroupSearch.prototype.JoinGroupConfirmationDone = function (e) {
                        var _this = this;
                        var $joinGroup = $(e.currentTarget);
                        var $result = $joinGroup.closest(".ui-card-result");
                        var roommateGroupID = Number($result.data("roommategroupid"));
                        new starrez.service.roommategroupsearch.JoinGroup({
                            hash: $joinGroup.data("hash"),
                            pageID: portal.page.CurrentPage.PageID,
                            roommateGroupID: roommateGroupID
                        }).Post().done(function () {
                            location.href = _this.model.ParentPageUrl;
                        });
                    };
                    RoommateGroupSearch.prototype.AttachEvents = function () {
                        var _this = this;
                        this.$filtersContainer.find(".ui-select-list").change(function (e) {
                            _this.LoadResults(1);
                        });
                        //Only do the search on max group textbox' change, because when the leave the min's textbox,
                        //most probably they haven't set the max yet and don't want to do the search yet
                        this.$minGroupSize.change(function () {
                            _this.LoadResults(1);
                        });
                        this.$maxGroupSize.change(function () {
                            _this.LoadResults(1);
                        });
                        this.$filtersContainer.keydown(function (e) {
                            if (e.keyCode === starrez.keyboard.EnterCode) {
                                // The browsers have a behaviour where they will automatically submit the form if there is only one
                                // input field on it. This is not what we want to do, so call SafeStopPropagation to block this from happening.
                                // http://stackoverflow.com/questions/1370021/why-does-forms-with-single-input-field-submit-upon-pressing-enter-key-in-input
                                starrez.library.utils.SafeStopPropagation(e);
                                _this.LoadResults(1);
                            }
                        });
                        this.$includeUnlimitedSizeGroup.change(function () {
                            _this.LoadResults(1);
                        });
                        this.$groupName.change(function () {
                            _this.LoadResults(1);
                        });
                        this.$entryNameWeb.change(function () {
                            _this.LoadResults(1);
                        });
                        portal.mobile.SetupExpandAndCollapse(this.$filtersContainer);
                        this.$resultsContainer.on("click", ".ui-join-group", function (e) {
                            var $joinGroup = $(e.currentTarget);
                            if ($joinGroup.isEnabled()) {
                                if (_this.model.ShowGroupSwitchConfirmation) {
                                    portal.ConfirmAction(_this.model.GroupSwitchConfirmationMessage, _this.model.GroupSwitchConfirmationTitle).done(function () {
                                        _this.JoinGroupConfirmationDone(e);
                                    });
                                }
                                else {
                                    _this.JoinGroupConfirmationDone(e);
                                }
                            }
                        });
                        this.$resultsContainer.on("click", ".ui-merge-group", function (e) {
                            var $joinGroup = $(e.currentTarget);
                            var $result = $joinGroup.closest(".ui-card-result");
                            var roommateGroupID = Number($result.data("roommategroupid"));
                            new starrez.service.roommategroupsearch.MergeGroup({
                                hash: $joinGroup.data("hash"),
                                pageID: portal.page.CurrentPage.PageID,
                                roommateGroupID: roommateGroupID
                            }).Post().done(function () {
                                location.href = _this.model.ParentPageUrl;
                            });
                        });
                    };
                    RoommateGroupSearch.prototype.GetRoomSearchFilters = function () {
                        this.model.MinGroupSize = this.$minGroupSize.SRVal();
                        this.model.MaxGroupSize = this.$maxGroupSize.SRVal();
                        this.model.IncludeUnlimitedSizeGroup = this.$includeUnlimitedSizeGroup.SRVal();
                        this.model.GroupName = this.$groupName.SRVal();
                        this.model.EntryNameWeb = this.$entryNameWeb.SRVal();
                        var profileItems = [];
                        this.$profileItemFilters.forEach(function (filter, index) {
                            var $filter = $(filter);
                            var value = $filter.SRVal();
                            if (starrez.library.utils.IsNotNullUndefined(value)) {
                                profileItems.push(value);
                            }
                        });
                        return {
                            MinGroupSize: this.model.MinGroupSize,
                            MaxGroupSize: this.model.MaxGroupSize,
                            ProfileItemID: profileItems,
                            IncludeUnlimitedSizeGroup: this.model.IncludeUnlimitedSizeGroup,
                            GroupName: this.model.GroupName,
                            EntryNameWeb: this.model.EntryNameWeb
                        };
                    };
                    RoommateGroupSearch.prototype.LoadResults = function (currentPageNumber) {
                        var _this = this;
                        this.currentPageNumber = currentPageNumber;
                        if (this.isSearching) {
                            // Prevent multiple searches from happening at once
                            this.isDirty = true;
                            return;
                        }
                        this.isSearching = true;
                        this.isDirty = false;
                        new starrez.service.roommategroupsearch.GetFilterResults({
                            pageID: portal.page.CurrentPage.PageID,
                            filters: this.GetRoomSearchFilters(),
                            currentPageNumber: this.currentPageNumber
                        }).Request({
                            ActionVerb: starrez.library.service.RequestType.Post,
                            ShowLoading: false,
                            LoadingFunc: function (loading) {
                                if (loading) {
                                    _this.$resultsContainer.addClass("loading");
                                }
                                else {
                                    _this.$resultsContainer.removeClass("loading");
                                }
                            }
                        }).done(function (result) {
                            _this.isSearching = false;
                            if (_this.isDirty) {
                                _this.LoadResults(_this.currentPageNumber);
                                return;
                            }
                            _this.$resultsContainer.html($.toHTML(result));
                            portal.paging.AttachPagingClickEvent(_this, _this.$resultsContainer, _this.LoadResults);
                        });
                    };
                    return RoommateGroupSearch;
                })();
            })(groupsearch = roommates.groupsearch || (roommates.groupsearch = {}));
        })(roommates = general.roommates || (general.roommates = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var roommates;
        (function (roommates) {
            var join;
            (function (join) {
                "use strict";
                function InitRoomJoinPage($container) {
                    new RoommateGroupJoinModel($container);
                }
                join.InitRoomJoinPage = InitRoomJoinPage;
                var RoommateGroupJoinModel = (function () {
                    function RoommateGroupJoinModel($container) {
                        this.$container = $container;
                        this.model = starrez.model.RoommateGroupJoinModel($container);
                        portal.page.CurrentPage.AddCustomValidation(this);
                    }
                    RoommateGroupJoinModel.prototype.Validate = function () {
                        var deferred = $.Deferred();
                        if (!this.model.ShowGroupSwitchConfirmation) {
                            return deferred.resolve();
                        }
                        return portal.ConfirmAction(this.model.GroupSwitchConfirmationMessage, this.model.GroupSwitchConfirmationTitle);
                    };
                    return RoommateGroupJoinModel;
                })();
            })(join = roommates.join || (roommates.join = {}));
        })(roommates = general.roommates || (general.roommates = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var portal;
(function (portal) {
    var general;
    (function (general) {
        var roommates;
        (function (roommates) {
            var main;
            (function (main) {
                "use strict";
                function InitialiseRoommateGroupManager($container) {
                    new RoommateGroupManager($container);
                }
                main.InitialiseRoommateGroupManager = InitialiseRoommateGroupManager;
                function InitialiseRoommateGroupList($container) {
                    new RoommateGroupListManager($container);
                }
                main.InitialiseRoommateGroupList = InitialiseRoommateGroupList;
                var RoommateListManager = (function () {
                    function RoommateListManager($container) {
                        var _this = this;
                        this.$container = $container;
                        this.$container.find(".ui-btn-send-message").SRClick(function (e) { return _this.GoToPage(e); });
                        this.$container.find(".ui-btn-view-profile").SRClick(function (e) { return _this.GoToPage(e); });
                    }
                    RoommateListManager.prototype.GoToPage = function (e) {
                        this.NavigatingToRelatedPage();
                        location.href = $(e.currentTarget).data("url");
                    };
                    RoommateListManager.prototype.NavigatingToRelatedPage = function () {
                    };
                    return RoommateListManager;
                })();
                main.RoommateListManager = RoommateListManager;
                var RoommateGroupManager = (function () {
                    function RoommateGroupManager($container) {
                        var _this = this;
                        this.$container = $container;
                        this.model = starrez.model.RoommateGroupManageModel($container);
                        this.$container.find(".ui-leave-group").SRClick(function (e) { return _this.LeaveGroup(e); });
                        this.$container.find(".ui-verify-group").SRClick(function (e) { return _this.VerifyGroup(e); });
                        this.$container.find(".ui-delete-group").SRClick(function (e) { return _this.DeleteGroup(e); });
                        this.$container.find(".ui-delete-invitation").SRClick(function (e) { return _this.CancelInvitation(e); });
                        this.$container.find(".ui-accept-request").SRClick(function (e) { return _this.AcceptRequest(e); });
                        this.$container.find(".ui-decline-request").SRClick(function (e) { return _this.DeclineRequest(e); });
                        this.$container.find(".ui-cancel-request").SRClick(function (e) { return _this.CancelRequest(e); });
                        this.$container.find(".ui-accept-merge-request").SRClick(function (e) { return _this.AcceptMergeRequest(e); });
                        this.$container.find(".ui-decline-merge-request").SRClick(function (e) { return _this.DeclineMergeRequest(e); });
                        this.$container.find(".ui-cancel-merge-request").SRClick(function (e) { return _this.CancelMergeRequest(e); });
                    }
                    RoommateGroupManager.prototype.LeaveGroup = function (e) {
                        portal.ConfirmAction(this.model.LeaveGroupConfirmationMessage, "Leave Group").done(function () {
                            var $button = $(e.currentTarget);
                            var hash = $button.data("hash").toString();
                            var entryApplicationID = Number($button.data("applicationid"));
                            return new starrez.service.roommates.DeleteRoommate({
                                hash: hash,
                                pageID: portal.page.CurrentPage.PageID,
                                entryApplicationID: entryApplicationID
                            }).Post().done(function () {
                                location.reload();
                            });
                        });
                    };
                    RoommateGroupManager.prototype.VerifyGroup = function (e) {
                        new starrez.service.roommates.VerifyGroup({
                            pageID: portal.page.CurrentPage.PageID,
                            groupID: this.model.RoommateGroupID,
                            hash: $(e.currentTarget).data("hash").toString()
                        }).Post().done(function () {
                            location.reload();
                        });
                    };
                    RoommateGroupManager.prototype.CancelInvitation = function (e) {
                        var $currentTarget = $(e.currentTarget);
                        var $invitationactionPanel = $currentTarget.closest(".ui-action-panel");
                        portal.ConfirmAction(this.model.CancelInvitationConfirmationMessage, this.model.CancelInvitationConfirmationMessageTitle).done(function () {
                            new starrez.service.roommates.CancelInvitation({
                                entryInvitationID: Number($invitationactionPanel.data("entryinvitationid")),
                                pageID: portal.page.CurrentPage.PageID,
                                hash: $currentTarget.data("hash")
                            }).Post().done(function () {
                                location.reload();
                            });
                        });
                    };
                    RoommateGroupManager.prototype.DeleteGroup = function (e) {
                        var _this = this;
                        portal.ConfirmAction(this.model.DeleteGroupConfirmationMessage, "Delete Group").done(function () {
                            var $button = $(e.currentTarget);
                            new starrez.service.roommates.DeleteGroup({
                                pageID: portal.page.CurrentPage.PageID,
                                groupID: _this.model.RoommateGroupID,
                                hash: $button.data("hash").toString()
                            }).Post().done(function () {
                                location.reload();
                            });
                        });
                    };
                    RoommateGroupManager.prototype.AcceptRequestConfirmationDone = function (e) {
                        var $currentTarget = $(e.currentTarget);
                        var $requestActionPanel = $currentTarget.closest(".ui-action-panel");
                        new starrez.service.roommates.AcceptRequest({
                            roommateGroupRequestID: Number($requestActionPanel.data("roommategrouprequestid")),
                            isMember: starrez.library.convert.ToBoolean($requestActionPanel.data("ismember")),
                            pageID: portal.page.CurrentPage.PageID,
                            hash: $currentTarget.data("hash")
                        }).Post().done(function () {
                            location.reload();
                        });
                    };
                    RoommateGroupManager.prototype.AcceptRequest = function (e) {
                        var _this = this;
                        var $currentTarget = $(e.currentTarget);
                        var $requestActionPanel = $currentTarget.closest(".ui-action-panel");
                        if (this.model.ShowGroupSwitchConfirmation && !starrez.library.convert.ToBoolean($requestActionPanel.data("ismember"))) {
                            portal.ConfirmAction(this.model.GroupSwitchConfirmationMessageTS, this.model.GroupSwitchConfirmationTitleTS).done(function () {
                                _this.AcceptRequestConfirmationDone(e);
                            });
                        }
                        else {
                            this.AcceptRequestConfirmationDone(e);
                        }
                    };
                    RoommateGroupManager.prototype.DeclineRequest = function (e) {
                        var $currentTarget = $(e.currentTarget);
                        var $requestActionPanel = $currentTarget.closest(".ui-action-panel");
                        new starrez.service.roommates.DeclineRequest({
                            roommateGroupRequestID: Number($requestActionPanel.data("roommategrouprequestid")),
                            isMember: starrez.library.convert.ToBoolean($requestActionPanel.data("ismember")),
                            pageID: portal.page.CurrentPage.PageID,
                            hash: $currentTarget.data("hash")
                        }).Post().done(function () {
                            location.reload();
                        });
                    };
                    RoommateGroupManager.prototype.CancelRequest = function (e) {
                        var $currentTarget = $(e.currentTarget);
                        var $requestActionPanel = $currentTarget.closest(".ui-action-panel");
                        new starrez.service.roommates.CancelRequest({
                            roommateGroupRequestID: Number($requestActionPanel.data("roommategrouprequestid")),
                            isMember: starrez.library.convert.ToBoolean($requestActionPanel.data("ismember")),
                            pageID: portal.page.CurrentPage.PageID,
                            hash: $currentTarget.data("hash")
                        }).Post().done(function () {
                            location.reload();
                        });
                    };
                    RoommateGroupManager.prototype.AcceptMergeRequest = function (e) {
                        var $currentTarget = $(e.currentTarget);
                        var $requestActionPanel = $currentTarget.closest(".ui-action-panel");
                        new starrez.service.roommates.AcceptMergeRequest({
                            requesterRoommateGroupID: Number($requestActionPanel.data("requesterroommategroupid")),
                            roommateGroupRequestID: Number($requestActionPanel.data("roommategrouprequestid")),
                            pageID: portal.page.CurrentPage.PageID,
                            hash: $currentTarget.data("hash")
                        }).Post().done(function () {
                            location.reload();
                        });
                    };
                    RoommateGroupManager.prototype.DeclineMergeRequest = function (e) {
                        var $currentTarget = $(e.currentTarget);
                        var $requestActionPanel = $currentTarget.closest(".ui-action-panel");
                        new starrez.service.roommates.DeclineMergeRequest({
                            requesterRoommateGroupID: Number($requestActionPanel.data("requesterroommategroupid")),
                            roommateGroupRequestID: Number($requestActionPanel.data("roommategrouprequestid")),
                            pageID: portal.page.CurrentPage.PageID,
                            hash: $currentTarget.data("hash")
                        }).Post().done(function () {
                            location.reload();
                        });
                    };
                    RoommateGroupManager.prototype.CancelMergeRequest = function (e) {
                        var $currentTarget = $(e.currentTarget);
                        var $requestActionPanel = $currentTarget.closest(".ui-action-panel");
                        new starrez.service.roommates.CancelMergeRequest({
                            requesterRoommateGroupID: Number($requestActionPanel.data("requesterroommategroupid")),
                            roommateGroupRequestID: Number($requestActionPanel.data("roommategrouprequestid")),
                            pageID: portal.page.CurrentPage.PageID,
                            hash: $currentTarget.data("hash")
                        }).Post().done(function () {
                            location.reload();
                        });
                    };
                    return RoommateGroupManager;
                })();
                var RoommateGroupListManager = (function (_super) {
                    __extends(RoommateGroupListManager, _super);
                    function RoommateGroupListManager($container) {
                        var _this = this;
                        _super.call(this, $container);
                        this.$container = $container;
                        this.model = starrez.model.RoommateGroupManageModel($container);
                        this.$container.find(".ui-delete-roommate").SRClick(function (e) { return _this.DeleteRoommate(e); });
                        this.$container.find(".ui-make-leader").SRClick(function (e) { return _this.MakeLeader(e); });
                        this.$container.find(".ui-move-up").SRClick(function (e) { return _this.ChangeRoommateOrder(e, true); });
                        this.$container.find(".ui-move-down").SRClick(function (e) { return _this.ChangeRoommateOrder(e, false); });
                    }
                    RoommateGroupListManager.prototype.DeleteRoommate = function (e) {
                        var _this = this;
                        var $button = $(e.currentTarget);
                        var $actionPanel = $button.closest(".ui-action-panel");
                        var message = this.SubstituteRoommateName(this.model.RemoveRoommateConfirmationMessage, $actionPanel);
                        portal.ConfirmAction(message, "Remove Roommate").done(function () {
                            var hash = $button.data("hash").toString();
                            var entryApplicationID = _this.GetEntryApplicationID($actionPanel);
                            new starrez.service.roommates.DeleteRoommate({
                                hash: hash,
                                pageID: portal.page.CurrentPage.PageID,
                                entryApplicationID: entryApplicationID
                            }).Post().done(function () {
                                location.reload();
                            });
                        });
                    };
                    RoommateGroupListManager.prototype.MakeLeader = function (e) {
                        var _this = this;
                        var $button = $(e.currentTarget);
                        var $actionPanel = $button.closest(".ui-action-panel");
                        var message = this.SubstituteRoommateName(this.model.MakeGroupLeaderConfirmationMessage, $actionPanel);
                        portal.ConfirmAction(message, "Make Leader").done(function () {
                            var hash = $button.data("hash").toString();
                            var roommateApplicationID = _this.GetEntryApplicationID($actionPanel);
                            new starrez.service.roommates.MakeLeader({
                                pageID: portal.page.CurrentPage.PageID,
                                newLeaderApplicationID: roommateApplicationID,
                                groupID: _this.model.RoommateGroupID,
                                hash: hash
                            }).Post().done(function () {
                                location.reload();
                            });
                        });
                    };
                    RoommateGroupListManager.prototype.ChangeRoommateOrder = function (e, moveUp) {
                        var $actionPanel = $(e.currentTarget).closest(".ui-action-panel");
                        var hashName = moveUp ? "moveuphash" : "movedownhash";
                        new starrez.service.roommates.ChangeRoommateOrder({
                            roommateApplicationID: this.GetEntryApplicationID($actionPanel),
                            groupID: this.model.RoommateGroupID,
                            moveUp: moveUp,
                            hash: $actionPanel.data(hashName).toString()
                        }).Post().done(function () {
                            if (moveUp) {
                                $actionPanel.insertBefore($actionPanel.prev());
                            }
                            else {
                                $actionPanel.insertAfter($actionPanel.next());
                            }
                        });
                    };
                    RoommateGroupListManager.prototype.GetEntryApplicationID = function ($actionPanel) {
                        return Number($actionPanel.data("entryapplicationid"));
                    };
                    RoommateGroupListManager.prototype.SubstituteRoommateName = function (message, $actionPanel) {
                        return message.replace("{RoommateName}", $actionPanel.find(".ui-title").text());
                    };
                    return RoommateGroupListManager;
                })(RoommateListManager);
            })(main = roommates.main || (roommates.main = {}));
        })(roommates = general.roommates || (general.roommates = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var portal;
(function (portal) {
    var general;
    (function (general) {
        var roommates;
        (function (roommates) {
            var search;
            (function (search) {
                "use strict";
                var StorageKeyPrefix = "Roommates.";
                var SearchManagerName = "SearchManager";
                function InitialiseFieldListEditor($container) {
                    portal.fieldlist.control.InitFieldListManager($container, function (existingFields) { return new starrez.service.roommatesearch.CreateNewField({
                        existingFields: existingFields
                    }); });
                }
                search.InitialiseFieldListEditor = InitialiseFieldListEditor;
                function InitialiseDetailsSearchManager($container) {
                    $container.data(SearchManagerName, new DetailsSearchManager($container));
                }
                search.InitialiseDetailsSearchManager = InitialiseDetailsSearchManager;
                function InitialiseProfilesSearchManager($container) {
                    $container.data(SearchManagerName, new ProfilesSearchManager($container));
                }
                search.InitialiseProfilesSearchManager = InitialiseProfilesSearchManager;
                function InitialiseResultsManager($container) {
                    new SearchResultsManaager($container);
                }
                search.InitialiseResultsManager = InitialiseResultsManager;
                var SearchResultsManaager = (function (_super) {
                    __extends(SearchResultsManaager, _super);
                    function SearchResultsManaager($container) {
                        var _this = this;
                        _super.call(this, $container);
                        this.$container = $container;
                        this.model = starrez.model.PotentialRoommatesModel(this.$container);
                        this.$container.find(".ui-btn-invite").SRClick(function (e) { return _this.Invite(e); });
                        this.$container.find(".ui-btn-join").SRClick(function (e) { return _this.JoinGroup(e); });
                        this.$container.find(".ui-btn-merge").SRClick(function (e) { return _this.MergeGroup(e); });
                    }
                    SearchResultsManaager.prototype.Invite = function (e) {
                        var $button = $(e.currentTarget);
                        var hash = $button.data("hash").toString();
                        var $actionPanel = $button.closest(".ui-action-panel");
                        var entryApplicationID = Number($actionPanel.data("entryapplicationid"));
                        new starrez.service.roommatesearch.InviteToGroup({
                            pageID: portal.page.CurrentPage.PageID,
                            groupID: this.model.RoommateGroupID,
                            entryApplicationID: entryApplicationID,
                            hash: hash
                        }).Post().done(function (url) {
                            location.href = url;
                        });
                    };
                    SearchResultsManaager.prototype.JoinGroupConfirmationDone = function (e) {
                        var $button = $(e.currentTarget);
                        var hash = $button.data("hash").toString();
                        var $actionPanel = $button.closest(".ui-action-panel");
                        var entryApplicationID = Number($actionPanel.data("entryapplicationid"));
                        var roommateGroupID = Number($actionPanel.data("roommategroupid"));
                        new starrez.service.roommatesearch.JoinGroup({
                            pageID: portal.page.CurrentPage.PageID,
                            groupID: roommateGroupID,
                            entryApplicationID: entryApplicationID,
                            hash: hash
                        }).Post().done(function (url) {
                            location.href = url;
                        });
                    };
                    SearchResultsManaager.prototype.JoinGroup = function (e) {
                        var _this = this;
                        var $button = $(e.currentTarget);
                        var hash = $button.data("hash").toString();
                        var $actionPanel = $button.closest(".ui-action-panel");
                        var roommateGroupID = Number($actionPanel.data("roommategroupid"));
                        if (this.model.ShowGroupSwitchConfirmation) {
                            portal.ConfirmAction(this.model.GroupSwitchConfirmationMessage, this.model.GroupSwitchConfirmationTitle).done(function () {
                                _this.JoinGroupConfirmationDone(e);
                            });
                        }
                        else {
                            this.JoinGroupConfirmationDone(e);
                        }
                    };
                    SearchResultsManaager.prototype.MergeGroup = function (e) {
                        var $button = $(e.currentTarget);
                        var hash = $button.data("hash").toString();
                        var $actionPanel = $button.closest(".ui-action-panel");
                        var entryApplicationID = Number($actionPanel.data("entryapplicationid"));
                        new starrez.service.roommatesearch.MergeGroup({
                            pageID: portal.page.CurrentPage.PageID,
                            groupID: this.model.RoommateGroupID,
                            entryApplicationID: entryApplicationID,
                            hash: hash
                        }).Post().done(function (url) {
                            location.href = url;
                        });
                    };
                    SearchResultsManaager.prototype.NavigatingToRelatedPage = function () {
                        var searchManager = this.$container.closest(".ui-roommate-search").data(SearchManagerName);
                        if (starrez.library.utils.IsNotNullUndefined(searchManager)) {
                            searchManager.SaveFilters();
                        }
                    };
                    return SearchResultsManaager;
                })(portal.general.roommates.main.RoommateListManager);
                var SearchManager = (function () {
                    function SearchManager($container) {
                        var _this = this;
                        this.$container = $container;
                        this.$searchResults = this.$container.find(".ui-search-results");
                        this.$hideUnactionableResults = this.$container.GetControl("HideUnactionableResults");
                        this.$container.find(".ui-btn-search").SRClick(function () { return _this.Search(); });
                        this.model = starrez.model.RoommateSearchBaseModel(this.$container);
                        if (this.FillFilters()) {
                            this.Search();
                        }
                        this.$container.find(".ui-field").keydown(function (e) {
                            if (e.keyCode === starrez.keyboard.EnterCode) {
                                _this.Search();
                                // The browsers have a behaviour where they will automatically submit the form if there is only one
                                // input field on it. This is not what we want to do, so call SafeStopPropagation to block this from happening.
                                // http://stackoverflow.com/questions/1370021/why-does-forms-with-single-input-field-submit-upon-pressing-enter-key-in-input
                                starrez.library.utils.SafeStopPropagation(e);
                            }
                        });
                    }
                    SearchManager.prototype.Search = function () {
                        var _this = this;
                        var filters = this.GetSearchFilters();
                        if (filters.length > 0) {
                            portal.page.CurrentPage.ClearMessages();
                            this.GetSearchRequest(filters).Post().done(function (results) {
                                _this.$searchResults.html($.toHTML(results));
                                $.ScrollToWithAnimation(_this.$searchResults);
                            });
                        }
                        else {
                            portal.page.CurrentPage.SetErrorMessage(this.model.NoSearchCriteriaErrorMessage);
                        }
                    };
                    SearchManager.prototype.GetSearchFilters = function () {
                        var _this = this;
                        return this.$container.find(".ui-field").GetAllControls().map(function (index, ctrl) { return _this.GetPopulatedFilter($(ctrl)); }).toArray();
                    };
                    SearchManager.prototype.SaveFilters = function () {
                        var obj = new starrez.library.collections.KeyValue();
                        obj.AddRange(this.GetSearchFilters());
                        localStorage.setItem(this.GetStorageKey(), JSON.stringify(obj.ToObjectProperty()));
                    };
                    SearchManager.prototype.FillFilters = function () {
                        var _this = this;
                        var filters = JSON.parse(localStorage.getItem(this.GetStorageKey()));
                        var hadFilters = false;
                        if (starrez.library.utils.IsNotNullUndefined(filters)) {
                            this.$container.find(".ui-field").GetAllControls().each(function (index, ctrl) {
                                var $ctrl = $(ctrl);
                                var value = filters[_this.GetControlKey($ctrl)];
                                if (starrez.library.utils.IsNotNullUndefined(value)) {
                                    $ctrl.SRVal(value);
                                    hadFilters = true;
                                }
                            });
                            this.ClearSavedFilter();
                        }
                        return hadFilters;
                    };
                    SearchManager.prototype.ClearSavedFilter = function () {
                        localStorage.removeItem(this.GetStorageKey());
                    };
                    SearchManager.prototype.GetStorageKey = function () {
                        return StorageKeyPrefix + this.GetStorageKeySuffix();
                    };
                    return SearchManager;
                })();
                var DetailsSearchManager = (function (_super) {
                    __extends(DetailsSearchManager, _super);
                    function DetailsSearchManager() {
                        _super.apply(this, arguments);
                    }
                    DetailsSearchManager.prototype.GetStorageKeySuffix = function () {
                        return "Details";
                    };
                    DetailsSearchManager.prototype.GetControlKey = function ($ctrl) {
                        return $ctrl.closest("li").data("field-id").toString();
                    };
                    DetailsSearchManager.prototype.GetPopulatedFilter = function ($ctrl) {
                        var value = $ctrl.SRVal();
                        if (!starrez.library.stringhelper.IsUndefinedOrEmpty(value)) {
                            return {
                                Key: this.GetControlKey($ctrl),
                                Value: value
                            };
                        }
                        return null;
                    };
                    DetailsSearchManager.prototype.GetSearchRequest = function (filters) {
                        return new starrez.service.roommatesearch.SearchByDetails({
                            pageID: portal.page.CurrentPage.PageID,
                            searchTerms: filters,
                            hideUnactionableResults: this.$hideUnactionableResults.isFound() ? this.$hideUnactionableResults.SRVal() : true,
                            hash: this.model.SearchHash
                        });
                    };
                    return DetailsSearchManager;
                })(SearchManager);
                var ProfilesSearchManager = (function (_super) {
                    __extends(ProfilesSearchManager, _super);
                    function ProfilesSearchManager() {
                        _super.apply(this, arguments);
                    }
                    ProfilesSearchManager.prototype.GetStorageKeySuffix = function () {
                        return "Profiles";
                    };
                    ProfilesSearchManager.prototype.GetControlKey = function ($ctrl) {
                        var profileItemID = Number($ctrl.closest("li").data("item-id"));
                        var selectedOption = Number($ctrl.SRVal());
                        var isMandatory = isNaN(profileItemID);
                        return (isMandatory ? selectedOption : profileItemID).toString();
                    };
                    ProfilesSearchManager.prototype.GetPopulatedFilter = function ($ctrl) {
                        var profileItemID = Number($ctrl.closest("li").data("item-id"));
                        var selectedOption = Number($ctrl.SRVal());
                        var isMandatory = isNaN(profileItemID);
                        if (!isNaN(selectedOption) && selectedOption != -1) {
                            return {
                                Key: (isMandatory ? selectedOption : profileItemID).toString(),
                                Value: isMandatory ? NaN : selectedOption
                            };
                        }
                    };
                    ProfilesSearchManager.prototype.GetSearchRequest = function (filters) {
                        return new starrez.service.roommatesearch.SearchByProfiles({
                            pageID: portal.page.CurrentPage.PageID,
                            searchProfiles: filters,
                            hideUnactionableResults: this.$hideUnactionableResults.isFound() ? this.$hideUnactionableResults.SRVal() : true,
                            hash: this.model.SearchHash
                        });
                    };
                    return ProfilesSearchManager;
                })(SearchManager);
            })(search = roommates.search || (roommates.search = {}));
        })(roommates = general.roommates || (general.roommates = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function PotentialRoommatesModel($sys) {
            return {
                EntryApplicationID: Number($sys.data('entryapplicationid')),
                GroupSwitchConfirmationMessage: $sys.data('groupswitchconfirmationmessage'),
                GroupSwitchConfirmationTitle: $sys.data('groupswitchconfirmationtitle'),
                RoommateGroupID: Number($sys.data('roommategroupid')),
                ShowGroupSwitchConfirmation: starrez.library.convert.ToBoolean($sys.data('showgroupswitchconfirmation'))
            };
        }
        model.PotentialRoommatesModel = PotentialRoommatesModel;
        function RoommateGroupJoinModel($sys) {
            return {
                GroupSwitchConfirmationMessage: $sys.data('groupswitchconfirmationmessage'),
                GroupSwitchConfirmationTitle: $sys.data('groupswitchconfirmationtitle'),
                ShowGroupSwitchConfirmation: starrez.library.convert.ToBoolean($sys.data('showgroupswitchconfirmation'))
            };
        }
        model.RoommateGroupJoinModel = RoommateGroupJoinModel;
        function RoommateGroupManageModel($sys) {
            return {
                CancelInvitationConfirmationMessage: $sys.data('cancelinvitationconfirmationmessage'),
                CancelInvitationConfirmationMessageTitle: $sys.data('cancelinvitationconfirmationmessagetitle'),
                DeleteGroupConfirmationMessage: $sys.data('deletegroupconfirmationmessage'),
                GroupSwitchConfirmationMessageTS: $sys.data('groupswitchconfirmationmessagets'),
                GroupSwitchConfirmationTitleTS: $sys.data('groupswitchconfirmationtitlets'),
                LeaveGroupConfirmationMessage: $sys.data('leavegroupconfirmationmessage'),
                MakeGroupLeaderConfirmationMessage: $sys.data('makegroupleaderconfirmationmessage'),
                RemoveRoommateConfirmationMessage: $sys.data('removeroommateconfirmationmessage'),
                RoommateGroupID: Number($sys.data('roommategroupid')),
                ShowGroupSwitchConfirmation: starrez.library.convert.ToBoolean($sys.data('showgroupswitchconfirmation'))
            };
        }
        model.RoommateGroupManageModel = RoommateGroupManageModel;
        function RoommateGroupSearchModel($sys) {
            return {
                CurrentPageNumber: Number($sys.data('currentpagenumber')),
                EntryNameWeb: $sys.data('entrynameweb'),
                GroupName: $sys.data('groupname'),
                GroupSwitchConfirmationMessage: $sys.data('groupswitchconfirmationmessage'),
                GroupSwitchConfirmationTitle: $sys.data('groupswitchconfirmationtitle'),
                IncludeUnlimitedSizeGroup: starrez.library.convert.ToBoolean($sys.data('includeunlimitedsizegroup')),
                MaxGroupSize: Number($sys.data('maxgroupsize')),
                MinGroupSize: Number($sys.data('mingroupsize')),
                ParentPageUrl: $sys.data('parentpageurl'),
                ProfileItemID: ($sys.data('profileitemid') === '') ? [] : ($sys.data('profileitemid')).toString().split(',').map(function (e) { return Number(e); }),
                ShowGroupSwitchConfirmation: starrez.library.convert.ToBoolean($sys.data('showgroupswitchconfirmation'))
            };
        }
        model.RoommateGroupSearchModel = RoommateGroupSearchModel;
        function RoommateSearchBaseModel($sys) {
            return {
                NoSearchCriteriaErrorMessage: $sys.data('nosearchcriteriaerrormessage'),
                SearchHash: $sys.data('searchhash')
            };
        }
        model.RoommateSearchBaseModel = RoommateSearchBaseModel;
        function RoommateSearchByDetailsModel($sys) {
            return {};
        }
        model.RoommateSearchByDetailsModel = RoommateSearchByDetailsModel;
        function RoommateSearchByProfilesModel($sys) {
            return {};
        }
        model.RoommateSearchByProfilesModel = RoommateSearchByProfilesModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var roommategroupsearch;
        (function (roommategroupsearch) {
            "use strict";
            var GetFilterResults = (function (_super) {
                __extends(GetFilterResults, _super);
                function GetFilterResults(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommategroupsearch";
                    this.Action = "GetFilterResults";
                }
                GetFilterResults.prototype.CallData = function () {
                    var obj = {
                        currentPageNumber: this.o.currentPageNumber,
                        filters: this.o.filters,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return GetFilterResults;
            })(starrez.library.service.AddInActionCallBase);
            roommategroupsearch.GetFilterResults = GetFilterResults;
            var JoinGroup = (function (_super) {
                __extends(JoinGroup, _super);
                function JoinGroup(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommategroupsearch";
                    this.Action = "JoinGroup";
                }
                JoinGroup.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                JoinGroup.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID,
                        roommateGroupID: this.o.roommateGroupID
                    };
                    return obj;
                };
                return JoinGroup;
            })(starrez.library.service.AddInActionCallBase);
            roommategroupsearch.JoinGroup = JoinGroup;
            var MergeGroup = (function (_super) {
                __extends(MergeGroup, _super);
                function MergeGroup(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommategroupsearch";
                    this.Action = "MergeGroup";
                }
                MergeGroup.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                MergeGroup.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID,
                        roommateGroupID: this.o.roommateGroupID
                    };
                    return obj;
                };
                return MergeGroup;
            })(starrez.library.service.AddInActionCallBase);
            roommategroupsearch.MergeGroup = MergeGroup;
        })(roommategroupsearch = service.roommategroupsearch || (service.roommategroupsearch = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var roommates;
        (function (roommates) {
            "use strict";
            var AcceptMergeRequest = (function (_super) {
                __extends(AcceptMergeRequest, _super);
                function AcceptMergeRequest(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommates";
                    this.Action = "AcceptMergeRequest";
                }
                AcceptMergeRequest.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                AcceptMergeRequest.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID,
                        requesterRoommateGroupID: this.o.requesterRoommateGroupID,
                        roommateGroupRequestID: this.o.roommateGroupRequestID
                    };
                    return obj;
                };
                return AcceptMergeRequest;
            })(starrez.library.service.AddInActionCallBase);
            roommates.AcceptMergeRequest = AcceptMergeRequest;
            var AcceptRequest = (function (_super) {
                __extends(AcceptRequest, _super);
                function AcceptRequest(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommates";
                    this.Action = "AcceptRequest";
                }
                AcceptRequest.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                AcceptRequest.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        isMember: this.o.isMember,
                        pageID: this.o.pageID,
                        roommateGroupRequestID: this.o.roommateGroupRequestID
                    };
                    return obj;
                };
                return AcceptRequest;
            })(starrez.library.service.AddInActionCallBase);
            roommates.AcceptRequest = AcceptRequest;
            var CancelInvitation = (function (_super) {
                __extends(CancelInvitation, _super);
                function CancelInvitation(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommates";
                    this.Action = "CancelInvitation";
                }
                CancelInvitation.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                CancelInvitation.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        entryInvitationID: this.o.entryInvitationID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return CancelInvitation;
            })(starrez.library.service.AddInActionCallBase);
            roommates.CancelInvitation = CancelInvitation;
            var CancelMergeRequest = (function (_super) {
                __extends(CancelMergeRequest, _super);
                function CancelMergeRequest(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommates";
                    this.Action = "CancelMergeRequest";
                }
                CancelMergeRequest.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                CancelMergeRequest.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID,
                        requesterRoommateGroupID: this.o.requesterRoommateGroupID,
                        roommateGroupRequestID: this.o.roommateGroupRequestID
                    };
                    return obj;
                };
                return CancelMergeRequest;
            })(starrez.library.service.AddInActionCallBase);
            roommates.CancelMergeRequest = CancelMergeRequest;
            var CancelRequest = (function (_super) {
                __extends(CancelRequest, _super);
                function CancelRequest(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommates";
                    this.Action = "CancelRequest";
                }
                CancelRequest.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                CancelRequest.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        isMember: this.o.isMember,
                        pageID: this.o.pageID,
                        roommateGroupRequestID: this.o.roommateGroupRequestID
                    };
                    return obj;
                };
                return CancelRequest;
            })(starrez.library.service.AddInActionCallBase);
            roommates.CancelRequest = CancelRequest;
            var ChangeRoommateOrder = (function (_super) {
                __extends(ChangeRoommateOrder, _super);
                function ChangeRoommateOrder(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommates";
                    this.Action = "ChangeRoommateOrder";
                }
                ChangeRoommateOrder.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                ChangeRoommateOrder.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        groupID: this.o.groupID,
                        moveUp: this.o.moveUp,
                        roommateApplicationID: this.o.roommateApplicationID
                    };
                    return obj;
                };
                return ChangeRoommateOrder;
            })(starrez.library.service.AddInActionCallBase);
            roommates.ChangeRoommateOrder = ChangeRoommateOrder;
            var DeclineMergeRequest = (function (_super) {
                __extends(DeclineMergeRequest, _super);
                function DeclineMergeRequest(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommates";
                    this.Action = "DeclineMergeRequest";
                }
                DeclineMergeRequest.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                DeclineMergeRequest.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID,
                        requesterRoommateGroupID: this.o.requesterRoommateGroupID,
                        roommateGroupRequestID: this.o.roommateGroupRequestID
                    };
                    return obj;
                };
                return DeclineMergeRequest;
            })(starrez.library.service.AddInActionCallBase);
            roommates.DeclineMergeRequest = DeclineMergeRequest;
            var DeclineRequest = (function (_super) {
                __extends(DeclineRequest, _super);
                function DeclineRequest(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommates";
                    this.Action = "DeclineRequest";
                }
                DeclineRequest.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                DeclineRequest.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        isMember: this.o.isMember,
                        pageID: this.o.pageID,
                        roommateGroupRequestID: this.o.roommateGroupRequestID
                    };
                    return obj;
                };
                return DeclineRequest;
            })(starrez.library.service.AddInActionCallBase);
            roommates.DeclineRequest = DeclineRequest;
            var DeleteGroup = (function (_super) {
                __extends(DeleteGroup, _super);
                function DeleteGroup(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommates";
                    this.Action = "DeleteGroup";
                }
                DeleteGroup.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                DeleteGroup.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        groupID: this.o.groupID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return DeleteGroup;
            })(starrez.library.service.AddInActionCallBase);
            roommates.DeleteGroup = DeleteGroup;
            var DeleteRoommate = (function (_super) {
                __extends(DeleteRoommate, _super);
                function DeleteRoommate(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommates";
                    this.Action = "DeleteRoommate";
                }
                DeleteRoommate.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                DeleteRoommate.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        entryApplicationID: this.o.entryApplicationID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return DeleteRoommate;
            })(starrez.library.service.AddInActionCallBase);
            roommates.DeleteRoommate = DeleteRoommate;
            var MakeLeader = (function (_super) {
                __extends(MakeLeader, _super);
                function MakeLeader(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommates";
                    this.Action = "MakeLeader";
                }
                MakeLeader.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                MakeLeader.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        groupID: this.o.groupID,
                        newLeaderApplicationID: this.o.newLeaderApplicationID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return MakeLeader;
            })(starrez.library.service.AddInActionCallBase);
            roommates.MakeLeader = MakeLeader;
            var VerifyGroup = (function (_super) {
                __extends(VerifyGroup, _super);
                function VerifyGroup(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommates";
                    this.Action = "VerifyGroup";
                }
                VerifyGroup.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                VerifyGroup.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        groupID: this.o.groupID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return VerifyGroup;
            })(starrez.library.service.AddInActionCallBase);
            roommates.VerifyGroup = VerifyGroup;
        })(roommates = service.roommates || (service.roommates = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var roommatesearch;
        (function (roommatesearch) {
            "use strict";
            var CreateNewField = (function (_super) {
                __extends(CreateNewField, _super);
                function CreateNewField(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommatesearch";
                    this.Action = "CreateNewField";
                }
                CreateNewField.prototype.CallData = function () {
                    var obj = {
                        existingFields: this.o.existingFields
                    };
                    return obj;
                };
                return CreateNewField;
            })(starrez.library.service.AddInActionCallBase);
            roommatesearch.CreateNewField = CreateNewField;
            var InviteToGroup = (function (_super) {
                __extends(InviteToGroup, _super);
                function InviteToGroup(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommatesearch";
                    this.Action = "InviteToGroup";
                }
                InviteToGroup.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                InviteToGroup.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        entryApplicationID: this.o.entryApplicationID,
                        groupID: this.o.groupID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return InviteToGroup;
            })(starrez.library.service.AddInActionCallBase);
            roommatesearch.InviteToGroup = InviteToGroup;
            var JoinGroup = (function (_super) {
                __extends(JoinGroup, _super);
                function JoinGroup(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommatesearch";
                    this.Action = "JoinGroup";
                }
                JoinGroup.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                JoinGroup.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        entryApplicationID: this.o.entryApplicationID,
                        groupID: this.o.groupID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return JoinGroup;
            })(starrez.library.service.AddInActionCallBase);
            roommatesearch.JoinGroup = JoinGroup;
            var MergeGroup = (function (_super) {
                __extends(MergeGroup, _super);
                function MergeGroup(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommatesearch";
                    this.Action = "MergeGroup";
                }
                MergeGroup.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                MergeGroup.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        entryApplicationID: this.o.entryApplicationID,
                        groupID: this.o.groupID,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return MergeGroup;
            })(starrez.library.service.AddInActionCallBase);
            roommatesearch.MergeGroup = MergeGroup;
            var SearchByDetails = (function (_super) {
                __extends(SearchByDetails, _super);
                function SearchByDetails(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommatesearch";
                    this.Action = "SearchByDetails";
                }
                SearchByDetails.prototype.CallData = function () {
                    var obj = {
                        hideUnactionableResults: this.o.hideUnactionableResults,
                        searchTerms: this.o.searchTerms
                    };
                    return obj;
                };
                SearchByDetails.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return SearchByDetails;
            })(starrez.library.service.AddInActionCallBase);
            roommatesearch.SearchByDetails = SearchByDetails;
            var SearchByProfiles = (function (_super) {
                __extends(SearchByProfiles, _super);
                function SearchByProfiles(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "Roommates";
                    this.Controller = "roommatesearch";
                    this.Action = "SearchByProfiles";
                }
                SearchByProfiles.prototype.CallData = function () {
                    var obj = {
                        hideUnactionableResults: this.o.hideUnactionableResults,
                        searchProfiles: this.o.searchProfiles
                    };
                    return obj;
                };
                SearchByProfiles.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return SearchByProfiles;
            })(starrez.library.service.AddInActionCallBase);
            roommatesearch.SearchByProfiles = SearchByProfiles;
        })(roommatesearch = service.roommatesearch || (service.roommatesearch = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var roompreferences;
    (function (roompreferences) {
        "use strict";
        function InitRoomPreferencesPage($container) {
            new RoomPreferencesModel($container);
        }
        roompreferences.InitRoomPreferencesPage = InitRoomPreferencesPage;
        var RoomPreferencesModel = (function () {
            function RoomPreferencesModel($container) {
                var _this = this;
                this.$container = $container;
                this.preferencesTable = starrez.tablesetup.CreateTableManager(this.$container.find(".ui-room-preferences-table table"), $('body'))[0];
                this.roomPreferencesModel = starrez.model.RoomPreferencesBaseModel($container);
                this.$tbody = this.preferencesTable.$table.find('tbody');
                this.$addButton = this.$container.find('.ui-add-room-preference');
                this.$saveButton = $('body').find('.ui-submit-page-content');
                this.$preferenceMessage = this.$container.find('.ui-preference-message');
                this.$newRowTemplate = this.$tbody.find('tr').first();
                this.pageID = portal.page.CurrentPage.PageID;
                this.availableLocations = this.roomPreferencesModel.AvailableLocations;
                this.availablePreferences = this.roomPreferencesModel.AvailablePreferences;
                this.AttachDeleteEvents();
                this.AttachAddEvents();
                this.AttachDropDownEvents();
                this.RefilterLocationDropDowns();
                this.RefilterPreferenceDropDowns();
                this.UpdateAddAndSave();
                portal.page.CurrentPage.FetchAdditionalData = function () { return _this.GetData(); };
                portal.page.CurrentPage.AddCustomValidation(this);
            }
            RoomPreferencesModel.prototype.AttachAddEvents = function () {
                var _this = this;
                this.$addButton.SRClick(function () {
                    _this.AddNewPreferenceRow();
                });
            };
            RoomPreferencesModel.prototype.AttachDeleteEvents = function () {
                var _this = this;
                this.preferencesTable.$table.SRClickDelegate('delete', '.ui-btn-delete', function (e) {
                    $(e.currentTarget).closest('tr').remove();
                    _this.RefilterLocationDropDowns();
                    _this.RefilterPreferenceDropDowns();
                    _this.UpdateRowOrder();
                    _this.UpdateAddAndSave();
                    _this.ShowRemainingPreferencesMessage();
                });
            };
            RoomPreferencesModel.prototype.AttachDropDownEvents = function () {
                var _this = this;
                this.preferencesTable.$table.on('change', '.ui-location-dropdown', function (e) {
                    var $preferenceDropDown = $(e.currentTarget).closest('tr').find('.ui-preference-dropdown').GetControl('PreferenceDropdown');
                    starrez.library.controls.dropdown.Clear($preferenceDropDown);
                    _this.RefilterLocationDropDowns();
                    _this.RefilterPreferenceDropDowns();
                    _this.UpdateAddAndSave();
                    var $locationDropDown = $(e.currentTarget).GetControl('LocationDropdown');
                    var locationValue = $locationDropDown.SRVal();
                    var locationText = $locationDropDown.SRCaption();
                    if (locationValue == "-1") {
                        _this.ClearMessage();
                        return;
                    }
                    var selectedLocations = _this.GetLocationValues();
                    var selectionCount = selectedLocations.filter(function (item) { return item === locationValue; }).length;
                    if (selectionCount < _this.roomPreferencesModel.MaxPreferencesPerLocation) {
                        var message = _this.roomPreferencesModel.RemainingPreferencesForLocationMessage;
                        message = message.replace("{location}", locationText).replace("{number}", starrez.library.convert.ToString(_this.roomPreferencesModel.MaxPreferencesPerLocation - selectionCount));
                        _this.ShowMessage(message);
                    }
                    else {
                        var message = _this.roomPreferencesModel.MaximumNumberOfPreferencesReachedForLocationErrorMessage;
                        message = message.replace("{location}", locationText);
                        _this.ShowMessage(message);
                    }
                });
                this.preferencesTable.$table.on('change', '.ui-preference-dropdown', function (e) {
                    var $preferenceDropDown = $(e.currentTarget).GetControl('PreferenceDropdown');
                    var $locationDropDown = $(e.currentTarget).closest('tr').find('.ui-location-dropdown').GetControl('LocationDropdown');
                    var preferenceValue = $preferenceDropDown.SRVal();
                    var locationValue = $locationDropDown.SRVal();
                    _this.RefilterPreferenceDropDowns();
                    _this.UpdateAddAndSave();
                    var studentFacingErrors = [];
                    if (locationValue === "-1") {
                        studentFacingErrors.push(_this.roomPreferencesModel.LocationNotSelectedErrorMessage);
                    }
                    if (preferenceValue === "-1") {
                        studentFacingErrors.push(_this.roomPreferencesModel.PreferenceNotSelectedErrorMessage);
                    }
                    if (studentFacingErrors.length > 0) {
                        portal.page.CurrentPage.SetErrorMessages(studentFacingErrors);
                        return false;
                    }
                    _this.ClearMessage();
                });
            };
            RoomPreferencesModel.prototype.AddNewPreferenceRow = function () {
                if (this.MaximumPreferencesReached()) {
                    this.ShowMessage(this.roomPreferencesModel.MaximumNumberOfPreferencesReachedErrorMessage);
                    return;
                }
                if (!this.$tbody.isFound()) {
                    this.preferencesTable.$table.append('<tbody></tbody>');
                    this.$tbody = this.preferencesTable.$table.find('tbody');
                }
                this.$tbody.append(this.$newRowTemplate.clone());
                this.RefilterLocationDropDowns();
                this.RefilterPreferenceDropDowns();
                this.UpdateRowOrder();
                this.UpdateAddAndSave();
                this.ShowRemainingPreferencesMessage();
            };
            RoomPreferencesModel.prototype.GetPreferenceIDs = function () {
                var preferenceIDs = [];
                var $tableRows = this.$tbody.find('tr');
                $tableRows.each(function (index, element) {
                    var $preferenceDropDown = $(element).find('.ui-preference-dropdown').GetControl('PreferenceDropdown');
                    var preferenceValue = $preferenceDropDown.SRVal();
                    preferenceIDs.push(preferenceValue);
                });
                return preferenceIDs;
            };
            RoomPreferencesModel.prototype.GetLocationValues = function () {
                var $tableRows = this.$tbody.find('tr');
                var locationValues = [];
                $tableRows.each(function (index, element) {
                    var $locationDropDown = $(element).find('.ui-location-dropdown').GetControl('LocationDropdown');
                    var locationValue = $locationDropDown.SRVal();
                    locationValues.push(locationValue);
                });
                return locationValues;
            };
            RoomPreferencesModel.prototype.GetLocations = function () {
                var $tableRows = this.$tbody.find('tr');
                var locationValues = [];
                $tableRows.each(function (index, element) {
                    locationValues.push($(element).data('location-value'));
                });
                return locationValues;
            };
            RoomPreferencesModel.prototype.UpdateAddAndSave = function () {
                if (this.MaximumPreferencesReached()) {
                    this.$addButton.prop("title", this.roomPreferencesModel.AddButtonHoverMessage);
                    this.$addButton.Disable();
                }
                else {
                    this.$addButton.prop("title", "");
                    this.$addButton.Enable();
                }
                this.isValid = !this.UnfinishedSelectionExists() && this.MinimumPreferencesReached();
                if (this.isValid) {
                    this.$saveButton.prop("title", "");
                    this.$saveButton.Enable();
                }
                else {
                    this.$saveButton.prop("title", this.roomPreferencesModel.SaveButtonHoverMessage);
                    this.$saveButton.Disable();
                }
            };
            RoomPreferencesModel.prototype.UpdateRowOrder = function () {
                var $rowOrders = this.$tbody.find('.ui-order-column');
                var preferenceNumber = 1;
                $rowOrders.each(function (index, element) {
                    $(element).text(preferenceNumber);
                    preferenceNumber++;
                });
            };
            RoomPreferencesModel.prototype.ShowMessage = function (message) {
                this.$preferenceMessage.find('div').text(message);
                this.$preferenceMessage.show();
            };
            RoomPreferencesModel.prototype.ClearMessage = function () {
                this.$preferenceMessage.hide();
            };
            RoomPreferencesModel.prototype.ShowRemainingPreferencesMessage = function () {
                var selectionCount = this.GetPreferenceIDs().length;
                var message = this.roomPreferencesModel.RemainingPreferencesMessage;
                message = message.replace("{number}", starrez.library.convert.ToString(this.roomPreferencesModel.MaximumNumberOfPreferences - selectionCount));
                this.ShowMessage(message);
            };
            RoomPreferencesModel.prototype.RefilterLocationDropDowns = function () {
                var _this = this;
                if (this.roomPreferencesModel.SelectPreferencesWithoutLocations)
                    return;
                var selectedLocations = this.GetLocationValues();
                var $tableRows = this.$tbody.find('tr');
                $tableRows.each(function (index, element) {
                    var $locationDropDown = $(element).find('.ui-location-dropdown').GetControl('LocationDropdown');
                    var selectedLocation = $locationDropDown.SRVal();
                    var filteredLocations = _this.availableLocations.filter(function (item) { return (item.Value === "-1" || item.Value === selectedLocation || selectedLocations.filter(function (value) { return value === item.Value; }).length < _this.roomPreferencesModel.MaxPreferencesPerLocation); });
                    starrez.library.controls.dropdown.FillDropDown(filteredLocations, $locationDropDown, "Value", "Text", selectedLocation, true);
                });
            };
            RoomPreferencesModel.prototype.RefilterPreferenceDropDowns = function () {
                var _this = this;
                var selectedPreferences = this.GetPreferenceIDs();
                var $tableRows = this.$tbody.find('tr');
                $tableRows.each(function (index, element) {
                    var $preferenceDropDown = $(element).find('.ui-preference-dropdown').GetControl('PreferenceDropdown');
                    var selectedPreference = $preferenceDropDown.SRVal();
                    var filteredPreferences;
                    if (_this.roomPreferencesModel.SelectPreferencesWithoutLocations) {
                        filteredPreferences = _this.availablePreferences.filter(function (item) { return (item.Value === "-1" || item.Value === selectedPreference || selectedPreferences.indexOf(item.Value) < 0); });
                    }
                    else {
                        var $locationDropDown = $(element).find('.ui-location-dropdown').GetControl('LocationDropdown');
                        var selectedLocation = $locationDropDown.SRVal();
                        filteredPreferences = _this.availablePreferences.filter(function (item) { return (item.LocationValue === selectedLocation && (item.Value === "-1" || item.Value === selectedPreference || selectedPreferences.indexOf(item.Value) < 0)); });
                    }
                    starrez.library.controls.dropdown.FillDropDown(filteredPreferences, $preferenceDropDown, "Value", "Text", selectedPreference, true);
                });
            };
            RoomPreferencesModel.prototype.UnfinishedSelectionExists = function () {
                var _this = this;
                var unfinishedSelectionExists = false;
                this.$tbody.find('tr').each(function (index, element) {
                    if (!_this.roomPreferencesModel.SelectPreferencesWithoutLocations) {
                        var $locationDropDown = $(element).find('.ui-location-dropdown').GetControl('LocationDropdown');
                        var locationValue = $locationDropDown.SRVal();
                        unfinishedSelectionExists = locationValue === "-1";
                        if (unfinishedSelectionExists)
                            return false;
                    }
                    var $preferenceDropDown = $(element).find('.ui-preference-dropdown').GetControl('PreferenceDropdown');
                    var preferenceValue = $preferenceDropDown.SRVal();
                    unfinishedSelectionExists = preferenceValue === "-1";
                    return !unfinishedSelectionExists;
                });
                return unfinishedSelectionExists;
            };
            RoomPreferencesModel.prototype.MinimumPreferencesReached = function () {
                if (this.roomPreferencesModel.MinimumNumberOfPreferences < 1)
                    return true;
                return this.preferencesTable.Rows().length >= this.roomPreferencesModel.MinimumNumberOfPreferences;
            };
            RoomPreferencesModel.prototype.MaximumPreferencesReached = function () {
                if (this.roomPreferencesModel.MaximumNumberOfPreferences < 1)
                    return false;
                return this.preferencesTable.Rows().length >= this.roomPreferencesModel.MaximumNumberOfPreferences;
            };
            RoomPreferencesModel.prototype.Validate = function () {
                var deferred = $.Deferred();
                if (this.isValid) {
                    deferred.resolve();
                }
                else {
                    deferred.reject();
                }
                return deferred.promise();
            };
            RoomPreferencesModel.prototype.GetData = function () {
                var data = this.GetPreferenceIDs();
                return {
                    SelectedPreferences: data
                };
            };
            return RoomPreferencesModel;
        })();
    })(roompreferences = portal.roompreferences || (portal.roompreferences = {}));
})(portal || (portal = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function LocationModelModel($sys) {
            return {
                Text: $sys.data('text'),
                Value: $sys.data('value')
            };
        }
        model.LocationModelModel = LocationModelModel;
        function PreferenceModelModel($sys) {
            return {
                LocationValue: $sys.data('locationvalue'),
                Text: $sys.data('text'),
                Value: $sys.data('value')
            };
        }
        model.PreferenceModelModel = PreferenceModelModel;
        function RoomPreferencesBaseModel($sys) {
            return {
                AddButtonHoverMessage: $sys.data('addbuttonhovermessage'),
                AvailableLocations: $sys.data('availablelocations'),
                AvailablePreferences: $sys.data('availablepreferences'),
                LocationNotSelectedErrorMessage: $sys.data('locationnotselectederrormessage'),
                MaximumNumberOfPreferences: Number($sys.data('maximumnumberofpreferences')),
                MaximumNumberOfPreferencesReachedErrorMessage: $sys.data('maximumnumberofpreferencesreachederrormessage'),
                MaximumNumberOfPreferencesReachedForLocationErrorMessage: $sys.data('maximumnumberofpreferencesreachedforlocationerrormessage'),
                MaxPreferencesPerLocation: Number($sys.data('maxpreferencesperlocation')),
                MinimumNumberOfPreferences: Number($sys.data('minimumnumberofpreferences')),
                MinimumPreferencesErrorMessage: $sys.data('minimumpreferenceserrormessage'),
                PreferenceNotSelectedErrorMessage: $sys.data('preferencenotselectederrormessage'),
                RemainingPreferencesForLocationMessage: $sys.data('remainingpreferencesforlocationmessage'),
                RemainingPreferencesMessage: $sys.data('remainingpreferencesmessage'),
                SaveButtonHoverMessage: $sys.data('savebuttonhovermessage'),
                SelectPreferencesWithoutLocations: starrez.library.convert.ToBoolean($sys.data('selectpreferenceswithoutlocations'))
            };
        }
        model.RoomPreferencesBaseModel = RoomPreferencesBaseModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var roomsearch;
    (function (roomsearch) {
        var assignbed;
        (function (assignbed) {
            "use strict";
            function Initialise($container) {
                new AssignBedStep($container);
            }
            assignbed.Initialise = Initialise;
            var AssignBedStep = (function () {
                function AssignBedStep($container) {
                    this.$container = $container;
                    this.roomPictures = {};
                    this.assignments = {};
                    this.newInvitations = {};
                    this.roomspaceSelectionClass = ".ui-roomspace-selection";
                    this.model = starrez.model.AssignBedStepModel($container);
                    this.baseModel = starrez.model.RoomSearchStepBaseModel($container);
                    this.$continueButton = portal.PageElements.$actions.find(".ui-btn-continue");
                    this.Initialise();
                }
                AssignBedStep.prototype.Initialise = function () {
                    var _this = this;
                    if (this.model.AutoComplete) {
                        portal.page.CurrentPage.SubmitPage();
                    }
                    this.$myRoomContainer = this.$container.find(".ui-my-room-container");
                    this.$roommatesContainer = this.$container.find(".ui-roommates-container");
                    this.$newInvitationsContainer = this.$container.find(".ui-new-invitations-container");
                    // Find roomspace dropdowns and repopulate them when we're coming back from the confirmation page
                    this.$roomspaceSelectors = this.$container.find(this.roomspaceSelectionClass);
                    this.$roomspaceSelection = this.$roomspaceSelectors.GetControl("RoomSpaceID");
                    this.$invitationNameText = this.$container.GetControl("Invitation_Name");
                    this.$invitationEmailText = this.$container.GetControl("Invitation_Email");
                    this.$invitationNameText.each(function (index, elem) { _this.UpdateNewInvitationText($(elem)); });
                    this.$invitationEmailText.each(function (index, elem) { _this.UpdateNewInvitationText($(elem)); });
                    this.$myPictureContainer = this.$container.find(".ui-my-bed-picture");
                    this.$myPicturePlaceholder = this.$myPictureContainer.find(".ui-my-bed-picture-placeholder");
                    this.$myActualPicture = this.$myPictureContainer.find(".ui-my-bed-actual-picture");
                    for (var i = 0; i < this.model.RoomImageUrls.length; i++) {
                        var unparsedUrl = this.model.RoomImageUrls[i];
                        var urlWithKey = unparsedUrl.split("|", 2);
                        this.roomPictures[urlWithKey[0]] = urlWithKey[1];
                    }
                    for (var i = 0; i < this.$roomspaceSelectors.length; i++) {
                        var $bedAssigneeControl = $(this.$roomspaceSelectors[i]);
                        var entryID = $bedAssigneeControl.data("entryid");
                        var entryInvitationID = $bedAssigneeControl.data("entryinvitationid");
                        // replicate uniqueID from RoommateInfo.GetRoommateInfoUniqueID()
                        var uniqueID = entryID;
                        if (!starrez.library.stringhelper.IsUndefinedOrEmpty(entryInvitationID)) {
                            uniqueID += "_" + entryInvitationID;
                        }
                        var $bedDropdown = $bedAssigneeControl.GetControl("RoomSpaceID");
                        var assignedBeds = this.model.AssignedBeds;
                        for (var x = 0; x < assignedBeds.length; x++) {
                            var ids = assignedBeds[x].split("|");
                            var assignedEntryID = ids[0];
                            var assignedRoomSpaceID = Number(ids[1]);
                            if (starrez.library.stringhelper.Equals(uniqueID, assignedEntryID, false)) {
                                $bedDropdown.SRVal(assignedRoomSpaceID);
                                this.AssignBed($bedDropdown, $bedAssigneeControl);
                            }
                        }
                    }
                    portal.actionpanel.control.AutoAdjustActionPanelHeights(this.$roommatesContainer);
                    portal.actionpanel.control.AutoAdjustActionPanelHeights(this.$newInvitationsContainer);
                    this.AttachEvents();
                    portal.roomsearch.AttachResetButton();
                };
                AssignBedStep.prototype.HandleNewInvitationTextChange = function (e) {
                    var $currentText = $(e.currentTarget);
                    this.UpdateNewInvitationText($currentText);
                };
                AssignBedStep.prototype.UpdateNewInvitationText = function ($currentText) {
                    var value = $currentText.SRVal();
                    var $selectedRoomSpace = $currentText.closest(this.roomspaceSelectionClass);
                    var $invalidNotificationContainer = $selectedRoomSpace.find(".ui-invalid-invitation-notification");
                    var currentAssigneeID = $selectedRoomSpace.data("bedassignmentid");
                    var $nameNotification = $invalidNotificationContainer.find(".ui-invalid-invitation-name");
                    var $emailNotification = $invalidNotificationContainer.find(".ui-invalid-invitation-email");
                    if (starrez.library.utils.IsNullOrUndefined(this.newInvitations[currentAssigneeID])) {
                        this.newInvitations[currentAssigneeID] = { InvitationName: null, InvitationEmail: null };
                    }
                    if (starrez.library.stringhelper.Equals("Invitation_Name", $currentText.SRName(), true)) {
                        this.newInvitations[currentAssigneeID].InvitationName = value;
                    }
                    if (starrez.library.stringhelper.Equals("Invitation_Email", $currentText.SRName(), true)) {
                        this.newInvitations[currentAssigneeID].InvitationEmail = value;
                    }
                    var isValid = true;
                    var oneFieldIsValid = false;
                    if (starrez.library.stringhelper.IsUndefinedOrEmpty(this.newInvitations[currentAssigneeID].InvitationName)) {
                        isValid = false;
                        $nameNotification.show();
                    }
                    else {
                        $nameNotification.hide();
                        oneFieldIsValid = true;
                    }
                    if (!this.IsEmailValid(this.newInvitations[currentAssigneeID].InvitationEmail)) {
                        isValid = false;
                        $emailNotification.show();
                    }
                    else {
                        $emailNotification.hide();
                        oneFieldIsValid = true;
                    }
                    var $dropdown = $selectedRoomSpace.GetControl("RoomSpaceID");
                    if (isValid) {
                        $invalidNotificationContainer.hide();
                    }
                    else {
                        $invalidNotificationContainer.show();
                    }
                    //Enable the dropdown as soon as one of the fields are populated
                    if (oneFieldIsValid) {
                        $dropdown.Enable();
                    }
                    else {
                        $dropdown.Disable();
                        $dropdown.SRVal(null);
                    }
                    //Remove the height style, then recalculate new height
                    $currentText.closest(".ui-action-panel-card .ui-contents").outerHeight("initial");
                    portal.actionpanel.control.AutoAdjustActionPanelHeights(this.$newInvitationsContainer);
                };
                AssignBedStep.prototype.IsEmailValid = function (email) {
                    //Regex copied from EmailAddress.cs
                    var emailPattern = /^[\w!#$%&'*\-/=?\^_`{|}~]+(([\w!#$%&'*\+\-/=?^_`{|}~]*)|(\.[^.]))*@((\[(\d{1,3}\.){3}\d{1,3}\])|(([\w\-]+\.)+[a-zA-Z]{2,}))$/;
                    return (!starrez.library.stringhelper.IsUndefinedOrEmpty(email) && emailPattern.test(email));
                };
                AssignBedStep.prototype.AssignBed = function ($bedDropdown, $bedAssigneeControl) {
                    var currentAssigneeID = $bedAssigneeControl.data("bedassignmentid");
                    var takenByMessage = $bedAssigneeControl.data("takenbymessage");
                    var isCurrentUser = starrez.library.convert.ToBoolean($bedAssigneeControl.data("iscurrentuser"));
                    var selectedRoomSpaceID = $bedDropdown.SRVal();
                    var previouslySelectingSomething = starrez.library.utils.IsNotNullUndefined(this.assignments[currentAssigneeID]);
                    var currentlySelectingSomething = starrez.library.utils.IsNotNullUndefined(selectedRoomSpaceID);
                    if (previouslySelectingSomething || currentlySelectingSomething) {
                        var $otherDropdowns = this.$roomspaceSelection.not($bedDropdown);
                        if (previouslySelectingSomething) {
                            //Mark the one they've selected before (if it's not please select) as enabled and remove the extra label
                            var $optionToEnable = $otherDropdowns.find("option[value=" + this.assignments[currentAssigneeID] + "]");
                            $optionToEnable.Enable();
                            $optionToEnable.find(".ui-roomspace-taken").remove();
                        }
                        if (currentlySelectingSomething) {
                            //Mark the one they just selected as disabled, and put label saying "Taken By Bob" or something like that
                            var $optionToDisable = $otherDropdowns.find("option[value=" + selectedRoomSpaceID + "]");
                            $optionToDisable.Disable();
                            if (starrez.library.utils.IsNotNullUndefined(this.newInvitations[currentAssigneeID])) {
                                //For new invitations, we have to do basic text replacing here, because name & email won't be available until user type in this page
                                takenByMessage = this.model.TakenByNewInvitationMessage;
                                takenByMessage = takenByMessage.replace(/{Name}/g, this.newInvitations[currentAssigneeID].InvitationName);
                                takenByMessage = takenByMessage.replace(/{Email}/g, this.newInvitations[currentAssigneeID].InvitationEmail);
                            }
                            $optionToDisable.append("<span class=\"ui-roomspace-taken\">" + takenByMessage + "</span>");
                        }
                    }
                    this.assignments[currentAssigneeID] = selectedRoomSpaceID;
                    //Change the room image based on what room the current user is selecting
                    if (isCurrentUser) {
                        if (currentlySelectingSomething && !starrez.library.stringhelper.IsUndefinedOrEmpty(this.roomPictures[selectedRoomSpaceID])) {
                            this.$myPicturePlaceholder.hide();
                            this.$myActualPicture.css("background-image", "url('" + this.roomPictures[selectedRoomSpaceID] + "')");
                            this.$myActualPicture.show();
                        }
                        else {
                            this.$myPicturePlaceholder.show();
                            this.$myActualPicture.hide();
                        }
                    }
                };
                AssignBedStep.prototype.AttachEvents = function () {
                    var _this = this;
                    this.$roomspaceSelection.change(function (e) {
                        var $bedDropdown = $(e.currentTarget);
                        var $bedAssigneeControl = $bedDropdown.closest(_this.roomspaceSelectionClass);
                        _this.AssignBed($bedDropdown, $bedAssigneeControl);
                    });
                    this.$invitationNameText.change(function (e) {
                        _this.HandleNewInvitationTextChange(e);
                    });
                    this.$invitationEmailText.change(function (e) {
                        _this.HandleNewInvitationTextChange(e);
                    });
                    this.$continueButton.SRClick(function () {
                        var call = new starrez.service.roomsearch.AssignBeds({
                            pageID: _this.model.RoomSelectionPageID,
                            roomBaseIDs: _this.model.RoomBaseIDs,
                            assignments: _this.assignments,
                            newInvitations: _this.newInvitations,
                            checkInDate: _this.baseModel.DateStart,
                            checkOutDate: _this.baseModel.DateEnd,
                            hash: _this.$continueButton.data("hash")
                        });
                        call.Post().done(function (result) {
                            portal.page.CurrentPage.SubmitPage();
                        });
                    });
                };
                return AssignBedStep;
            })();
        })(assignbed = roomsearch.assignbed || (roomsearch.assignbed = {}));
    })(roomsearch = portal.roomsearch || (portal.roomsearch = {}));
})(portal || (portal = {}));

var portal;
(function (portal) {
    var roomsearch;
    (function (roomsearch) {
        var confirmation;
        (function (confirmation) {
            "use strict";
            function Initialise($container) {
                portal.roomsearch.AttachResetButton();
                portal.PageElements.$actions.find(".ui-btn-continue").SRClick(function () {
                    portal.page.CurrentPage.SubmitPage();
                });
            }
            confirmation.Initialise = Initialise;
        })(confirmation = roomsearch.confirmation || (roomsearch.confirmation = {}));
    })(roomsearch = portal.roomsearch || (portal.roomsearch = {}));
})(portal || (portal = {}));

var portal;
(function (portal) {
    var roomsearch;
    (function (roomsearch) {
        var initial;
        (function (initial) {
            "use strict";
            (function (InitialFilterOption) {
                InitialFilterOption[InitialFilterOption["RoomType"] = 0] = "RoomType";
                InitialFilterOption[InitialFilterOption["RoomLocationArea"] = 1] = "RoomLocationArea";
                InitialFilterOption[InitialFilterOption["RoomLocation"] = 2] = "RoomLocation";
                InitialFilterOption[InitialFilterOption["DatesAndRates"] = 3] = "DatesAndRates";
            })(initial.InitialFilterOption || (initial.InitialFilterOption = {}));
            var InitialFilterOption = initial.InitialFilterOption;
            function Initialise($container) {
                new InitialFilterStep($container);
            }
            initial.Initialise = Initialise;
            var InitialFilterStep = (function () {
                function InitialFilterStep($container) {
                    this.$container = $container;
                    this.model = starrez.model.InitialFilterStepModel($container);
                    this.baseModel = starrez.model.RoomSearchStepBaseModel($container);
                    this.$dateStart = this.$container.GetControl("DateStart");
                    this.$dateEnd = this.$container.GetControl("DateEnd");
                    this.$resultsContainer = this.$container.find(".ui-initial-filter-step-results-container");
                    this.Initialise();
                }
                InitialFilterStep.prototype.ReloadResults = function () {
                    var _this = this;
                    new starrez.service.roomsearch.GetInitialFilterStepResults({
                        pageID: this.model.RoomSelectionPageID,
                        dateStart: this.baseModel.DateStart,
                        dateEnd: this.baseModel.DateEnd,
                        classificationID: this.model.ClassificationID,
                        termID: this.model.TermID,
                        groupID: this.model.GroupID
                    }).Post().done(function (html) {
                        _this.$resultsContainer.html($.toHTML(html));
                        _this.AttachEvents();
                    });
                };
                InitialFilterStep.prototype.Initialise = function () {
                    var _this = this;
                    this.$dateStart.change(function () {
                        _this.baseModel.DateStart = _this.$dateStart.SRVal();
                        _this.ReloadResults();
                    });
                    this.$dateEnd.change(function () {
                        _this.baseModel.DateEnd = _this.$dateEnd.SRVal();
                        _this.ReloadResults();
                    });
                    this.AttachEvents();
                };
                InitialFilterStep.prototype.AttachEvents = function () {
                    var _this = this;
                    if (this.model.InitialFilterOption === InitialFilterOption[InitialFilterOption.DatesAndRates]) {
                        var $slider = this.$container.find(".ui-rates");
                        var updateDetails = function () {
                            _this.lowerRoomRateValue = $slider.slider("values", 0);
                            _this.upperRoomRateValue = $slider.slider("values", 1);
                            var rateText = _this.model.CurrencySymbol + _this.lowerRoomRateValue + " - " + _this.model.CurrencySymbol + _this.upperRoomRateValue;
                            _this.$container.find(".ui-rates-value").text(rateText);
                        };
                        $slider.slider({
                            range: true,
                            min: this.model.MinimumRoomRateFilterValue,
                            max: this.model.MaximumRoomRateFilterValue,
                            values: [this.model.MinimumRoomRateFilterValue, this.model.MaximumRoomRateFilterValue],
                            stop: function (event, ui) {
                                updateDetails();
                            }
                        });
                        this.$container.find(".ui-select-action").SRClick(function () {
                            _this.UpdateModuleContextAndContinue();
                        });
                        updateDetails();
                    }
                    this.$container.find(".ui-action-panel .ui-select-action").SRClick(function (e) {
                        var $actionPanel = $(e.currentTarget).closest(".ui-action-panel");
                        _this.objectID = Number($actionPanel.data("id"));
                        _this.UpdateModuleContextAndContinue();
                    });
                    this.$container.find(".ui-async-flipper-container").each(function (index, element) {
                        var manager = new portal.asyncflipper.control.AsyncFlipperManager($(element));
                        manager.OnClick().done(function ($asyncContainer) {
                            new starrez.service.roomsearch.GetTermCardContent({
                                tableID: Number($asyncContainer.attr("id")),
                                pageID: portal.page.CurrentPage.PageID
                            }).Request({
                                ActionVerb: starrez.library.service.RequestType.Post,
                                ShowLoading: false
                            }).done(function (html) {
                                manager.AddFlipSideContent(html);
                            });
                        });
                    });
                    portal.actionpanel.control.AutoAdjustActionPanelHeights(this.$container);
                };
                InitialFilterStep.prototype.UpdateModuleContextAndContinue = function () {
                    var filters = {
                        DateStart: this.baseModel.DateStart,
                        DateEnd: this.baseModel.DateEnd,
                        LowerRoomRateValue: this.lowerRoomRateValue,
                        UpperRoomRateValue: this.upperRoomRateValue,
                        RoomTypeID: null,
                        ProfileItemID: null,
                        RoomBaseIDs: null,
                        RoomLocationAreaID: null,
                        RoomLocationFloorSuiteID: null,
                        RoomLocationID: null,
                        UseRoommateClassifications: null
                    };
                    filters[this.model.RoomSelectionPropertyName] = [this.objectID];
                    portal.roomsearch.UpdateModuleContextWithFiltersAndCurrentPageNumber(filters, 1).done(function () {
                        portal.page.CurrentPage.SubmitPage();
                    });
                };
                return InitialFilterStep;
            })();
        })(initial = roomsearch.initial || (roomsearch.initial = {}));
    })(roomsearch = portal.roomsearch || (portal.roomsearch = {}));
})(portal || (portal = {}));

/// <reference path="../../../../WebCommon/TypeScriptTypes/lib.d.ts" />
var portal;
(function (portal) {
    var roomsearch;
    (function (roomsearch) {
        "use strict";
        function UpdateModuleContextWithFiltersAndCurrentPageNumber(filter, currentPageNumber) {
            return new starrez.service.roomsearch.UpdateProcessContext({
                processID: portal.page.CurrentPage.ProcessID,
                filters: filter,
                currentPageNumber: currentPageNumber
            }).Post();
        }
        roomsearch.UpdateModuleContextWithFiltersAndCurrentPageNumber = UpdateModuleContextWithFiltersAndCurrentPageNumber;
        function AttachResetButton() {
            var $reset = portal.PageElements.$actions.find(".ui-restart-roomsearch");
            var roomSelectionPageID = Number($reset.data("roomselectionpageid"));
            var termID = Number($reset.data("termid"));
            var classificationID = Number($reset.data("classificationid"));
            var groupID = Number($reset.data("groupid"));
            $reset.SRClick(function () {
                // confirm they actually want to do this
                portal.ConfirmAction($reset.data("message"), $reset.data("title")).done(function () {
                    // wipe their cart
                    new starrez.service.roomsearch.Restart({
                        pageID: roomSelectionPageID,
                        processID: portal.page.CurrentPage.ProcessID,
                        termID: termID,
                        classificationID: classificationID,
                        groupID: groupID
                    }).Post().done(function (url) {
                        // go to the start of room search
                        if (!starrez.library.stringhelper.IsUndefinedOrEmpty(url)) {
                            location.href = url;
                        }
                    });
                });
            });
        }
        roomsearch.AttachResetButton = AttachResetButton;
        function InitRoomSearchRenewal($container) {
            new RoomSearchRenewal($container);
        }
        roomsearch.InitRoomSearchRenewal = InitRoomSearchRenewal;
        var RoomSearchRenewal = (function () {
            function RoomSearchRenewal($container) {
                this.AttachEvents($container);
            }
            RoomSearchRenewal.prototype.AttachEvents = function (container) {
                container.find('.ui-renew-roombutton').each(function (index, element) {
                    var $renewButton = $(element);
                    $renewButton.SRClick(function () {
                        new starrez.service.roomsearch.RenewRoom({
                            pageID: portal.page.CurrentPage.PageID,
                            hash: $renewButton.data("hash")
                        }).Post().done(function (url) {
                            location.href = url;
                        });
                    });
                });
            };
            return RoomSearchRenewal;
        })();
        ;
    })(roomsearch = portal.roomsearch || (portal.roomsearch = {}));
})(portal || (portal = {}));

var portal;
(function (portal) {
    var roomsearch;
    (function (roomsearch) {
        var main;
        (function (main) {
            "use strict";
            function Initialise($container) {
                main.Model = new MainFilterStep($container);
            }
            main.Initialise = Initialise;
            (function (AddingRoomOption) {
                AddingRoomOption[AddingRoomOption["Multiple"] = 0] = "Multiple";
                AddingRoomOption[AddingRoomOption["Single"] = 1] = "Single";
                AddingRoomOption[AddingRoomOption["None"] = 2] = "None";
            })(main.AddingRoomOption || (main.AddingRoomOption = {}));
            var AddingRoomOption = main.AddingRoomOption;
            ;
            (function (FilterType) {
                FilterType[FilterType["RoomTypeID"] = 0] = "RoomTypeID";
                FilterType[FilterType["RoomLocationAreaID"] = 1] = "RoomLocationAreaID";
                FilterType[FilterType["RoomLocationID"] = 2] = "RoomLocationID";
                FilterType[FilterType["RoomLocationFloorSuiteID"] = 3] = "RoomLocationFloorSuiteID";
                FilterType[FilterType["ProfileItemID"] = 4] = "ProfileItemID";
                FilterType[FilterType["None"] = 5] = "None";
            })(main.FilterType || (main.FilterType = {}));
            var FilterType = main.FilterType;
            //This class is being used when we don't want to show filters with no results in Room List
            var FilterModel = (function () {
                function FilterModel(FilterName, $FilterControl, filterTsLink, filterType) {
                    this.FilterName = FilterName;
                    this.$FilterControl = $FilterControl;
                    this.filterTsLink = filterTsLink;
                    this.filterType = filterType;
                }
                FilterModel.prototype.GetFilterTsLink = function () {
                    return this.filterTsLink;
                };
                FilterModel.prototype.GetFilterType = function () {
                    return this.filterType;
                };
                FilterModel.prototype.GetVisibleFilterItems = function (filterData, filterType, filterModels) {
                    if (starrez.library.utils.IsNullOrUndefined(filterData)) {
                        return [];
                    }
                    var filterItems = filterData.FilterItems;
                    if (this.IsArrayEmpty(filterItems)) {
                        return [];
                    }
                    var visibleFilterIDs = [];
                    for (var i = 0; i < filterData.FilterItems.length; i++) {
                        var filterItem = filterData.FilterItems[i];
                        var skip = false;
                        for (var filterModelIndex = 0; filterModelIndex < filterModels.length; filterModelIndex++) {
                            var filterModel = filterModels[filterModelIndex];
                            if (filterType != filterModel.filterType && !this.IsArrayEmpty(filterModel.SelectedFilterIDs)) {
                                if (filterModel.SelectedFilterIDs.indexOf(filterItem.IDs[filterModel.filterType]) === -1) {
                                    skip = true;
                                    break;
                                }
                            }
                        }
                        if (!skip) {
                            visibleFilterIDs.push(filterItem.IDs[filterType]);
                        }
                    }
                    return this.GetUniqueArray(visibleFilterIDs);
                };
                FilterModel.prototype.IsArrayEmpty = function (array) {
                    return starrez.library.utils.IsNullOrUndefined(array) || array.length === 0;
                };
                FilterModel.prototype.GetUniqueArray = function (array) {
                    return array.filter(function (value, index, self) {
                        return self.indexOf(value) === index;
                    });
                };
                return FilterModel;
            })();
            var MainFilterStep = (function () {
                function MainFilterStep($container) {
                    this.$container = $container;
                    this.isSliderInitialised = false;
                    this.isSearching = false;
                    this.isDirty = false;
                    this.suggestionGroupsNumber = 0;
                    this.suggestionGroupsLoaded = 0;
                    this.hasSuggestions = false;
                    this.roomSearchGuid = null;
                    this.filterModels = [];
                    this.model = starrez.model.MainFilterStepModel($container);
                    this.filterData = this.model.FilterData;
                    this.baseModel = starrez.model.RoomSearchStepBaseModel($container);
                    this.$filtersContainer = this.$container.find(".ui-filters");
                    this.$resultsContainer = this.$container.find(".ui-results");
                    this.$continueButtonContainer = this.$container.find(".ui-btn-continue-container");
                    this.$continueButton = this.$continueButtonContainer.find(".ui-btn-continue");
                    this.$filterIcon = this.$filtersContainer.find(".ui-filter-icon");
                    this.$filterBody = this.$filtersContainer.find(".ui-filter-body");
                    this.$dateStart = this.$container.GetControl("DateStart");
                    this.$dateEnd = this.$container.GetControl("DateEnd");
                    this.InitialiseUpdatableFilters();
                    this.Initialise();
                    portal.roomsearch.AttachResetButton();
                }
                MainFilterStep.prototype.InitialiseUpdatableFilters = function () {
                    var _this = this;
                    this.$histoGram = this.$filtersContainer.find(".ui-roomrate-graph");
                    this.$useRoommateClassifications = this.$container.GetControl("UseRoommateClassifications");
                    //Populate filter models. The index is based on FilterType
                    this.filterModels[FilterType.RoomTypeID] = new FilterModel("RoomTypeID", this.$filtersContainer.GetControl("RoomTypeID"), ".ui-room-selection-type-filter", FilterType.RoomTypeID);
                    this.filterModels[FilterType.RoomLocationAreaID] = new FilterModel("RoomLocationAreaID", this.$filtersContainer.GetControl("RoomLocationAreaID"), ".ui-room-selection-area-filter", FilterType.RoomLocationAreaID);
                    this.filterModels[FilterType.RoomLocationID] = new FilterModel("RoomLocationID", this.$filtersContainer.GetControl("RoomLocationID"), ".ui-room-selection-location-filter", FilterType.RoomLocationID);
                    this.filterModels[FilterType.RoomLocationFloorSuiteID] = new FilterModel("RoomLocationFloorSuiteID", this.$filtersContainer.GetControl("RoomLocationFloorSuiteID"), ".ui-room-selection-floorsuite-filter", FilterType.RoomLocationFloorSuiteID);
                    this.filterModels[FilterType.ProfileItemID] = new FilterModel("ProfileItemID", this.$filtersContainer.GetControl("ProfileItemID"), ".ui-room-selection-profile-filter", FilterType.ProfileItemID);
                    this.$roomRateSlider = this.$filtersContainer.find(".ui-roomrate-slider");
                    this.InitSlider(this.model.MinimumRoomRateFilterValue, this.model.MaximumRoomRateFilterValue);
                    this.AttachFilterEvents();
                    this.$useRoommateClassifications.change(function () {
                        _this.model.UseRoommateClassifications = _this.$useRoommateClassifications.SRVal();
                        _this.UpdateFilters().done(function () {
                            _this.HideFilters(FilterType.None);
                            _this.LoadResults(1);
                        });
                    });
                    this.HideFilters(FilterType.None);
                };
                MainFilterStep.prototype.Initialise = function () {
                    this.AttachEvents();
                    if (this.model.CurrentPageNumber == 0) {
                        this.model.CurrentPageNumber = 1;
                    }
                    this.LoadResults(this.model.CurrentPageNumber);
                };
                MainFilterStep.prototype.GetFilterVal = function (filterType) {
                    var $filterControl = this.filterModels[filterType].$FilterControl;
                    if ($filterControl.isFound()) {
                        var value = $filterControl.SRVal();
                        if (starrez.library.utils.IsNotNullUndefined(value)) {
                            return starrez.library.convert.ToNumberArray(value);
                        }
                    }
                    return [];
                };
                // Slider number 0 is the lower value, 1 is the upper value
                MainFilterStep.prototype.GetRoomRateValue = function (slider) {
                    if (this.$roomRateSlider.isFound()) {
                        return this.$roomRateSlider.slider("values", slider);
                    }
                    return null;
                };
                MainFilterStep.prototype.AttachEvents = function () {
                    var _this = this;
                    this.$dateStart.change(function () {
                        _this.baseModel.DateStart = _this.$dateStart.SRVal();
                        _this.UpdateFilters().done(function () {
                            _this.HideFilters(FilterType.None);
                            _this.LoadResults(1);
                        });
                    });
                    this.$dateEnd.change(function () {
                        _this.baseModel.DateEnd = _this.$dateEnd.SRVal();
                        _this.UpdateFilters().done(function () {
                            _this.HideFilters(FilterType.None);
                            _this.LoadResults(1);
                        });
                    });
                    this.$resultsContainer.on("click", ".ui-add-room-to-cart", function (e) {
                        var $addRoomToCart = $(e.currentTarget);
                        var $result = $addRoomToCart.closest(".ui-card-result");
                        var isRoomBase = false;
                        var roomBaseID;
                        var roomTypeID;
                        var roomLocationID;
                        if (starrez.library.utils.IsNotNullUndefined($result.data("roombaseid"))) {
                            roomBaseID = Number($result.data("roombaseid"));
                            isRoomBase = true;
                        }
                        else {
                            roomTypeID = Number($result.data("roomtypeid"));
                            roomLocationID = Number($result.data("roomlocationid"));
                        }
                        _this.model.RoomRateID = Number($result.data("roomrateid"));
                        var multiSelect = AddingRoomOption[_this.model.ActualAddingRoomToCartOption] === AddingRoomOption.Multiple;
                        if (isRoomBase) {
                            if (!multiSelect) {
                                new starrez.service.roomsearch
                                    .ValidateNumberOfRoomSpacesForSingleRoom({ pageID: _this.model.RoomSelectionPageID, roomBaseID: roomBaseID })
                                    .Post()
                                    .done(function () { _this.AddRoomToCart(roomBaseID, $addRoomToCart); });
                            }
                            else {
                                _this.AddRoomToCart(roomBaseID, $addRoomToCart);
                            }
                        }
                        else {
                            _this.AddRoomTypeLocationToCart(roomTypeID, roomLocationID, $addRoomToCart);
                        }
                    });
                    this.$resultsContainer.on("click", ".ui-remove-room-from-cart", function (e) {
                        var $removeFromCart = $(e.currentTarget);
                        var $result = $removeFromCart.closest(".ui-card-result");
                        _this.removeFromCartHash = $removeFromCart.data("hash");
                        var roomBaseID = Number($result.data("roombaseid"));
                        var index = _this.model.RoomBaseIDs.indexOf(roomBaseID);
                        if (index !== -1) {
                            var call = new starrez.service.roomsearch.RemoveRoomFromCart({
                                hash: _this.removeFromCartHash,
                                processID: portal.page.CurrentPage.ProcessID,
                                roomBaseID: roomBaseID,
                                pageID: _this.model.RoomSelectionPageID
                            });
                            call.Post().done(function (result) {
                                for (var i = 0; i < result.UpdatedRoomBaseIDs.length; i++) {
                                    var roomIndex = _this.model.RoomBaseIDs.indexOf(result.UpdatedRoomBaseIDs[i]);
                                    if (roomIndex >= 0) {
                                        _this.model.RoomBaseIDs.splice(roomIndex, 1);
                                    }
                                }
                                _this.SetResultsAddRemoveButton(result.UpdatedRoomBaseIDs, false);
                                portal.navigation.NavigationBar.UpdateShoppingCart();
                                _this.SetSuggestedRoomAddRemoveButton(result.UpdatedRoomBaseIDs, false);
                            });
                        }
                    });
                    portal.mobile.SetupExpandAndCollapse(this.$filtersContainer);
                    this.$continueButton.SRClick(function () {
                        if (!_this.model.CanAddRoomsToCart) {
                            portal.page.CurrentPage.SubmitPage();
                        }
                        else if (_this.model.RoomBaseIDs.length > 0) {
                            new starrez.service.roomsearch.ValidateNumberOfRoomSpacesSelected({ pageID: _this.model.RoomSelectionPageID })
                                .Post()
                                .done(function () {
                                _this.UpdateModuleContextAndContinue();
                            });
                        }
                        else {
                            portal.page.CurrentPage.SetErrorMessage(_this.model.MustSelectRoomMessage);
                            return;
                        }
                    });
                    this.$resultsContainer.on("click", ".ui-show-room-total-amount-link", function (e) {
                        var $calculateTotalLink = $(e.currentTarget);
                        var $result = $calculateTotalLink.closest(".ui-card-result");
                        var call = new starrez.service.roomsearch.CalculateTotalRoomPrice({
                            checkInDate: _this.baseModel.DateStart,
                            checkOutDate: _this.baseModel.DateEnd,
                            pageID: _this.model.RoomSelectionPageID,
                            roomBaseID: Number($result.data("roombaseid")),
                            roomRateID: Number($result.data("roomrateid")),
                            hash: $calculateTotalLink.data("hash")
                        });
                        call.Post().done(function (result) {
                            $calculateTotalLink.remove();
                            var $calcTotalLabel = $result.find(".ui-room-total-amount");
                            $calcTotalLabel.attr("aria-hidden", "false");
                            $calcTotalLabel.show();
                            $calcTotalLabel.html(result);
                        });
                    });
                    this.$resultsContainer.on("click", ".ui-show-type-location-total-amount-link", function (e) {
                        var $calculateTotalLink = $(e.currentTarget);
                        var $result = $calculateTotalLink.closest(".ui-card-result");
                        var call = new starrez.service.roomsearch.CalculateTotalRoomTypeLocationPrice({
                            checkInDate: _this.baseModel.DateStart,
                            checkOutDate: _this.baseModel.DateEnd,
                            pageID: _this.model.RoomSelectionPageID,
                            roomRateID: Number($result.data("roomrateid")),
                            roomLocationID: Number($result.data("roomlocationid")),
                            roomTypeID: Number($result.data("roomtypeid")),
                            hash: $calculateTotalLink.data("hash")
                        });
                        call.Post().done(function (result) {
                            $calculateTotalLink.remove();
                            var $calcTotalLabel = $result.find(".ui-room-total-amount");
                            $calcTotalLabel.attr("aria-hidden", "false");
                            $calcTotalLabel.show();
                            $calcTotalLabel.html(result);
                        });
                    });
                };
                MainFilterStep.prototype.AttachFilterEvents = function () {
                    var _this = this;
                    this.$filtersContainer.GetAllControls().find("select").change(function (e) {
                        var $ctrl = $(e.currentTarget).closest(".ui-multiple-select-list");
                        var ctrlFieldName = $ctrl.data("fieldname").toString();
                        _this.HideFilters(FilterType[ctrlFieldName]);
                        _this.LoadResults(1);
                    });
                };
                //When dates, useRoommateClassifications, or rate filters changed,
                //the possible values for room types, areas, locations, floorsuites, and profile items will also change.
                //Hence, the filter controls and filter data will need to be updated.
                MainFilterStep.prototype.UpdateFilters = function () {
                    var _this = this;
                    var def = $.Deferred();
                    // Save current rate value
                    this.model.LowerRoomRateValue = this.GetRoomRateValue(0);
                    this.model.UpperRoomRateValue = this.GetRoomRateValue(1);
                    if (this.model.ShowFiltersWithoutRooms) {
                        def.resolve(true);
                    }
                    else {
                        new starrez.service.roomsearch.UpdateFilterData({
                            pageID: this.model.RoomSelectionPageID,
                            filters: this.GetRoomSearchFilters(),
                            termID: this.model.TermID,
                            classificationID: this.model.ClassificationID,
                            groupID: this.model.GroupID
                        }).Request({
                            ActionVerb: starrez.library.service.RequestType.Post,
                            ShowLoading: false
                        }).done(function (result) {
                            _this.$filterBody.html(result.FilterViewHtml);
                            _this.filterData = result.FilterData;
                            _this.InitialiseUpdatableFilters();
                            def.resolve(true);
                        });
                    }
                    return def.promise();
                };
                MainFilterStep.prototype.AddRoomToCart = function (roomBaseID, $addButton) {
                    var _this = this;
                    var $result = $addButton.closest(".ui-card-result");
                    if (this.model.RoomBaseIDs.indexOf(roomBaseID) === -1) {
                        var call;
                        if (starrez.library.utils.IsNotNullUndefined(this.model.GroupID)) {
                            call = new starrez.service.roomsearch.AddRoomToCartForGroup({
                                hash: $addButton.data("hash"),
                                pageID: this.model.RoomSelectionPageID,
                                roomBaseID: roomBaseID,
                                roomRateID: Number($result.data("roomrateid")),
                                groupID: this.model.GroupID,
                                checkInDate: this.baseModel.DateStart,
                                checkOutDate: this.baseModel.DateEnd
                            });
                        }
                        else if (starrez.library.utils.IsNullOrUndefined(this.model.TermID)) {
                            call = new starrez.service.roomsearch.AddRoomToCart({
                                hash: $addButton.data("hash"),
                                pageID: this.model.RoomSelectionPageID,
                                roomBaseID: roomBaseID,
                                roomRateID: Number($result.data("roomrateid")),
                                checkInDate: this.baseModel.DateStart,
                                checkOutDate: this.baseModel.DateEnd
                            });
                        }
                        else {
                            call = new starrez.service.roomsearch.AddRoomToCartForTerm({
                                hash: $addButton.data("hash"),
                                pageID: this.model.RoomSelectionPageID,
                                roomBaseID: roomBaseID,
                                roomRateID: Number($result.data("roomrateid")),
                                termID: this.model.TermID,
                                checkInDate: this.baseModel.DateStart,
                                checkOutDate: this.baseModel.DateEnd
                            });
                        }
                        call.Post().done(function (result) {
                            // Save the fact that room was successfully added to cart,
                            // so that when the filters are changed and the same room appears in the search results,
                            // it shows the Remove button instead of the Add button
                            _this.model.RoomBaseIDs.push.apply(_this.model.RoomBaseIDs, result.UpdatedRoomBaseIDs);
                            if (AddingRoomOption[_this.model.ActualAddingRoomToCartOption] === AddingRoomOption.Multiple) {
                                _this.SetResultsAddRemoveButton(result.UpdatedRoomBaseIDs, true);
                                portal.navigation.NavigationBar.UpdateShoppingCart();
                                _this.SetSuggestedRoomAddRemoveButton(result.UpdatedRoomBaseIDs, true);
                            }
                            else {
                                _this.UpdateModuleContextAndContinue();
                            }
                        });
                    }
                };
                MainFilterStep.prototype.AddRoomTypeLocationToCart = function (roomTypeID, roomLocationID, $addButton) {
                    var _this = this;
                    var $result = $addButton.closest(".ui-card-result");
                    var call;
                    if (starrez.library.utils.IsNotNullUndefined(this.model.GroupID)) {
                        call = new starrez.service.roomsearch.AddRoomTypeLocationToCartForGroup({
                            hash: $addButton.data("hash"),
                            pageID: this.model.RoomSelectionPageID,
                            roomTypeID: roomTypeID,
                            roomLocationID: roomLocationID,
                            roomRateID: Number($result.data("roomrateid")),
                            groupID: this.model.GroupID,
                            checkInDate: this.baseModel.DateStart,
                            checkOutDate: this.baseModel.DateEnd
                        });
                    }
                    else if (starrez.library.utils.IsNullOrUndefined(this.model.TermID)) {
                        call = new starrez.service.roomsearch.AddRoomTypeLocationToCart({
                            hash: $addButton.data("hash"),
                            pageID: this.model.RoomSelectionPageID,
                            roomTypeID: roomTypeID,
                            roomLocationID: roomLocationID,
                            roomRateID: Number($result.data("roomrateid")),
                            checkInDate: this.baseModel.DateStart,
                            checkOutDate: this.baseModel.DateEnd
                        });
                    }
                    else {
                        call = new starrez.service.roomsearch.AddRoomTypeLocationToCartForTerm({
                            hash: $addButton.data("hash"),
                            pageID: this.model.RoomSelectionPageID,
                            roomTypeID: roomTypeID,
                            roomLocationID: roomLocationID,
                            roomRateID: Number($result.data("roomrateid")),
                            termID: this.model.TermID,
                            checkInDate: this.baseModel.DateStart,
                            checkOutDate: this.baseModel.DateEnd
                        });
                    }
                    call.Post().done(function (result) {
                        _this.UpdateModuleContextAndContinue();
                    });
                };
                // Toggles add/remove buttons for a suggested room that could potentially
                // be shown under multiple suggestion groups.
                MainFilterStep.prototype.SetSuggestedRoomAddRemoveButton = function (roomBaseIDs, isRoomInCart) {
                    this.SetAddRemoveButton(roomBaseIDs, isRoomInCart, this.$suggestionContainer);
                };
                MainFilterStep.prototype.SetResultsAddRemoveButton = function (roomBaseIDs, isRoomInCart) {
                    this.SetAddRemoveButton(roomBaseIDs, isRoomInCart, this.$resultsContainer);
                };
                MainFilterStep.prototype.SetAddRemoveButton = function (roomBaseIDs, isRoomInCart, $container) {
                    if (starrez.library.utils.IsNotNullUndefined($container)) {
                        $container.find(".ui-card-result").each(function (index, room) {
                            var $room = $(room);
                            if (roomBaseIDs.indexOf(Number($room.data("roombaseid"))) >= 0) {
                                if (isRoomInCart) {
                                    $room.find(".ui-remove-room-from-cart").show();
                                    $room.find(".ui-add-room-to-cart").hide();
                                }
                                else {
                                    $room.find(".ui-remove-room-from-cart").hide();
                                    $room.find(".ui-add-room-to-cart").show();
                                }
                            }
                        });
                    }
                };
                MainFilterStep.prototype.UpdateModuleContextAndContinue = function () {
                    portal.roomsearch.UpdateModuleContextWithFiltersAndCurrentPageNumber(this.GetRoomSearchFilters(), this.currentPageNumber).done(function () {
                        portal.page.CurrentPage.SubmitPage();
                    });
                };
                MainFilterStep.prototype.InitSlider = function (min, max) {
                    var _this = this;
                    min = Math.floor(min);
                    max = Math.ceil(max);
                    var currentLowerValue = this.model.LowerRoomRateValue;
                    var currentUpperValue = this.model.UpperRoomRateValue;
                    if (!starrez.library.utils.IsNotNullUndefined(currentLowerValue)) {
                        currentLowerValue = this.model.MinimumRoomRateFilterValue;
                    }
                    if (!starrez.library.utils.IsNotNullUndefined(currentUpperValue) || currentUpperValue === 0) {
                        currentUpperValue = this.model.MaximumRoomRateFilterValue;
                    }
                    if (min === max) {
                        max = max + 1;
                    }
                    this.$roomRateSlider.slider({
                        range: true,
                        min: min,
                        max: max,
                        values: [currentLowerValue, currentUpperValue],
                        stop: function (event, ui) {
                            _this.UpdateSliderDataAndText();
                            _this.UpdateFilters().done(function () {
                                _this.HideFilters(FilterType.None);
                                _this.LoadResults(1);
                            });
                        }
                    });
                    this.UpdateSliderDataAndText();
                    this.isSliderInitialised = true;
                };
                MainFilterStep.prototype.UpdateSliderDataAndText = function () {
                    var rateText = this.model.CurrencySymbol + this.$roomRateSlider.slider("values", 0) + " - " + this.model.CurrencySymbol + this.$roomRateSlider.slider("values", 1);
                    this.$filtersContainer.find(".ui-roomrate-slider-value").text(rateText);
                };
                MainFilterStep.prototype.BuildHistogram = function (values, min, max) {
                    var _this = this;
                    starrez.library.controls.BuildHistogram(this.$histoGram, this.model.CurrencySymbol, values, min, max, function ($ctnl) {
                        var lowerVal = $ctnl.data("lower");
                        var upperVal = $ctnl.data("upper");
                        _this.$roomRateSlider.slider("values", 0, lowerVal);
                        _this.$roomRateSlider.slider("values", 1, upperVal + 1);
                        _this.LoadResults(1);
                        _this.UpdateSliderDataAndText();
                    });
                };
                MainFilterStep.prototype.HideFilters = function (ctrlFieldName) {
                    if (this.model.ShowFiltersWithoutRooms) {
                        return;
                    }
                    for (var filterType = 0; filterType < this.filterModels.length; filterType++) {
                        this.filterModels[filterType].SelectedFilterIDs = this.GetFilterVal(filterType);
                    }
                    if (starrez.library.utils.IsNullOrUndefined(ctrlFieldName)) {
                        ctrlFieldName = FilterType.None;
                    }
                    for (var filterType = 0; filterType < this.filterModels.length; filterType++) {
                        var filterModel = this.filterModels[filterType];
                        if (ctrlFieldName != filterType && filterModel.$FilterControl.isFound()) {
                            var visibleIDs = filterModel.GetVisibleFilterItems(this.filterData, filterType, this.filterModels);
                            starrez.library.controls.multipleselect.ShowItems(filterModel.$FilterControl, visibleIDs);
                        }
                    }
                };
                MainFilterStep.prototype.GetRoomSearchFilters = function () {
                    return {
                        DateStart: this.baseModel.DateStart,
                        DateEnd: this.baseModel.DateEnd,
                        RoomTypeID: this.GetFilterVal(FilterType.RoomTypeID),
                        RoomLocationAreaID: this.GetFilterVal(FilterType.RoomLocationAreaID),
                        RoomLocationID: this.GetFilterVal(FilterType.RoomLocationID),
                        RoomBaseIDs: this.model.RoomBaseIDs,
                        ProfileItemID: this.GetFilterVal(FilterType.ProfileItemID),
                        LowerRoomRateValue: this.GetRoomRateValue(0),
                        UpperRoomRateValue: this.GetRoomRateValue(1),
                        RoomLocationFloorSuiteID: this.GetFilterVal(FilterType.RoomLocationFloorSuiteID),
                        UseRoommateClassifications: this.model.UseRoommateClassifications
                    };
                };
                MainFilterStep.prototype.LoadResults = function (currentPageNumber) {
                    var _this = this;
                    //without this model is undefined in thisRef.model.roomSelectionModel.RoomBaseIDs.indexOf(roomBaseID)
                    var thisRef = this;
                    this.currentPageNumber = currentPageNumber;
                    if (this.isSearching) {
                        // Prevent multiple searches from happening at once
                        this.isDirty = true;
                        return;
                    }
                    this.isSearching = true;
                    this.isDirty = false;
                    new starrez.service.roomsearch.GetFilterResults({
                        pageID: this.model.RoomSelectionPageID,
                        filters: this.GetRoomSearchFilters(),
                        processID: portal.page.CurrentPage.ProcessID,
                        currentPageNumber: this.currentPageNumber,
                        termID: this.model.TermID,
                        classificationID: this.model.ClassificationID,
                        groupID: this.model.GroupID
                    }).Request({
                        ActionVerb: starrez.library.service.RequestType.Post,
                        ShowLoading: false,
                        LoadingFunc: function (loading) {
                            if (loading) {
                                _this.$resultsContainer.addClass("loading");
                            }
                            else {
                                _this.$resultsContainer.removeClass("loading");
                            }
                        }
                    }).done(function (result) {
                        _this.isSearching = false;
                        if (_this.isDirty) {
                            _this.LoadResults(_this.currentPageNumber);
                            return;
                        }
                        //In IE, if the user clicks back button, the page won't be reloaded and will be using the last one from the cache (with the outdated information of RoomBaseIDs)
                        //The AJAX call is still calling the server though, so to fix this, we need to sync the RoomBaseIDs with the ones from the server.
                        _this.model.RoomBaseIDs = result.RoomBaseIDs;
                        if (starrez.library.utils.IsNotNullUndefined(_this.model.RoomBaseIDs) && _this.model.RoomBaseIDs.length > 0) {
                            _this.$continueButtonContainer.show();
                        }
                        _this.RenderResults(_this.$resultsContainer, result.ResultsHtml, thisRef);
                        portal.paging.AttachPagingClickEvent(_this, _this.$resultsContainer, _this.LoadResults);
                        if (result.RoomSearchSuggestions != null && result.RoomSearchSuggestions.length > 0) {
                            _this.$roomSearchLoading = _this.$resultsContainer.find(".ui-room-search-loading");
                            _this.SuggestRooms(result);
                        }
                        _this.BuildHistogram(result.Rates, _this.model.MinimumRoomRateFilterValue, _this.model.MaximumRoomRateFilterValue);
                    });
                };
                MainFilterStep.prototype.SuggestRooms = function (result) {
                    var _this = this;
                    this.suggestionGroupsNumber = result.RoomSearchSuggestions.length;
                    this.suggestionGroupsLoaded = 0;
                    this.hasSuggestions = false;
                    this.roomSearchGuid = result.RoomSearchGuid;
                    this.$suggestionContainer = this.$resultsContainer.find(".ui-room-suggestions");
                    this.$roomSearchLoading.show();
                    for (var i = 0; i < this.suggestionGroupsNumber; i++) {
                        new starrez.service.roomsearch.GetSuggestions({
                            pageID: this.model.RoomSelectionPageID,
                            processID: portal.page.CurrentPage.ProcessID,
                            suggestions: result.RoomSearchSuggestions[i],
                            roomSearchGuid: result.RoomSearchGuid,
                            termID: this.model.TermID,
                            classificationID: this.model.ClassificationID,
                            groupID: this.model.GroupID
                        }).Request({
                            ActionVerb: starrez.library.service.RequestType.Post,
                            ShowLoading: false
                        }).done(function (suggestions) {
                            if (suggestions.RoomSearchGuid !== _this.roomSearchGuid) {
                                //This seems like an outdated request, so just ignore
                                return;
                            }
                            _this.suggestionGroupsLoaded++;
                            if (suggestions.HasResults) {
                                _this.hasSuggestions = true;
                                _this.AddSuggestionGroup(suggestions.Index, suggestions.ResultsHtml);
                            }
                            if (_this.suggestionGroupsLoaded === _this.suggestionGroupsNumber) {
                                _this.$roomSearchLoading.hide();
                                if (!_this.hasSuggestions) {
                                    _this.$resultsContainer.find(".ui-no-suggestions-available").show();
                                }
                            }
                        });
                    }
                };
                MainFilterStep.prototype.AddSuggestionGroup = function (index, content) {
                    var $suggestionResultsContainer = $("<div>");
                    $suggestionResultsContainer.addClass("ui-suggestion-group");
                    $suggestionResultsContainer.attr("data-index", index);
                    var $otherResultsContainers = this.$suggestionContainer.children();
                    if ($otherResultsContainers.length == 0) {
                        this.$suggestionContainer.append($suggestionResultsContainer);
                    }
                    else {
                        var inserted = false;
                        for (var j = 0; j < $otherResultsContainers.length; j++) {
                            var $otherResultsContainer = $($otherResultsContainers[j]);
                            var otherResultsContainerIndex = Number($otherResultsContainer.data("index"));
                            var thisResultsContainerIndex = Number($suggestionResultsContainer.data("index"));
                            if (otherResultsContainerIndex > thisResultsContainerIndex) {
                                $suggestionResultsContainer.insertBefore($otherResultsContainer);
                                inserted = true;
                                break;
                            }
                        }
                        if (!inserted) {
                            this.$suggestionContainer.append($suggestionResultsContainer);
                        }
                    }
                    this.RenderResults($suggestionResultsContainer, content, this);
                };
                MainFilterStep.prototype.RenderResults = function ($container, content, thisRef) {
                    $container.html($.toHTML(content));
                    // find all cards, check if the roombaseid is in the selected ids and toggle add/remove button accordingly
                    // this is in case rooms are selected and then filters are changed
                    var $cards = $container.find(".ui-add-room-to-cart");
                    $cards.each(function (index, item) {
                        var $item = $(item);
                        var $result = $item.closest(".ui-card-result");
                        var roomBaseID = Number($result.data("roombaseid"));
                        if (!isNaN(roomBaseID) && thisRef.model.RoomBaseIDs.indexOf(roomBaseID) !== -1) {
                            var $removeButton = $item.siblings(".ui-remove-room-from-cart");
                            $item.hide();
                            $removeButton.show();
                        }
                    });
                };
                return MainFilterStep;
            })();
        })(main = roomsearch.main || (roomsearch.main = {}));
    })(roomsearch = portal.roomsearch || (portal.roomsearch = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function AssignBedStepModel($sys) {
            return {
                AssignedBeds: ($sys.data('assignedbeds') === '') ? [] : ($sys.data('assignedbeds')).toString().split(','),
                AutoComplete: starrez.library.convert.ToBoolean($sys.data('autocomplete')),
                RoomBaseIDs: ($sys.data('roombaseids') === '') ? [] : ($sys.data('roombaseids')).toString().split(',').map(function (e) { return Number(e); }),
                RoomImageUrls: ($sys.data('roomimageurls') === '') ? [] : ($sys.data('roomimageurls')).toString().split(','),
                RoomSelectionPageID: Number($sys.data('roomselectionpageid')),
                TakenByNewInvitationMessage: $sys.data('takenbynewinvitationmessage')
            };
        }
        model.AssignBedStepModel = AssignBedStepModel;
        function InitialFilterStepModel($sys) {
            return {
                ClassificationID: $sys.data('classificationid'),
                CurrencySymbol: $sys.data('currencysymbol'),
                GroupID: $sys.data('groupid'),
                InitialFilterOption: $sys.data('initialfilteroption'),
                MaximumRoomRateFilterValue: Number($sys.data('maximumroomratefiltervalue')),
                MinimumRoomRateFilterValue: Number($sys.data('minimumroomratefiltervalue')),
                RoomSelectionPageID: Number($sys.data('roomselectionpageid')),
                RoomSelectionPropertyName: $sys.data('roomselectionpropertyname'),
                TermID: $sys.data('termid')
            };
        }
        model.InitialFilterStepModel = InitialFilterStepModel;
        function MainFilterStepModel($sys) {
            return {
                ActualAddingRoomToCartOption: $sys.data('actualaddingroomtocartoption'),
                CanAddRoomsToCart: starrez.library.convert.ToBoolean($sys.data('canaddroomstocart')),
                ClassificationID: $sys.data('classificationid'),
                CurrencySymbol: $sys.data('currencysymbol'),
                CurrentPageNumber: Number($sys.data('currentpagenumber')),
                FilterData: $sys.data('filterdata'),
                GroupID: $sys.data('groupid'),
                LowerRoomRateValue: Number($sys.data('lowerroomratevalue')),
                MaximumRoomRateFilterValue: Number($sys.data('maximumroomratefiltervalue')),
                MinimumRoomRateFilterValue: Number($sys.data('minimumroomratefiltervalue')),
                MustSelectRoomMessage: $sys.data('mustselectroommessage'),
                RoomBaseIDs: ($sys.data('roombaseids') === '') ? [] : ($sys.data('roombaseids')).toString().split(',').map(function (e) { return Number(e); }),
                RoomRateID: Number($sys.data('roomrateid')),
                RoomSelectionPageID: Number($sys.data('roomselectionpageid')),
                ShowFiltersWithoutRooms: starrez.library.convert.ToBoolean($sys.data('showfilterswithoutrooms')),
                TermID: $sys.data('termid'),
                UpperRoomRateValue: Number($sys.data('upperroomratevalue')),
                UseRoommateClassifications: starrez.library.convert.ToBoolean($sys.data('useroommateclassifications'))
            };
        }
        model.MainFilterStepModel = MainFilterStepModel;
        function RoomSearchStepBaseModel($sys) {
            return {
                DateEnd: moment($sys.data('dateend')).toDate(),
                DateStart: moment($sys.data('datestart')).toDate()
            };
        }
        model.RoomSearchStepBaseModel = RoomSearchStepBaseModel;
        function RoomSelectionModel($sys) {
            return {
                CurrencySymbol: $sys.data('currencysymbol'),
                DateEnd: moment($sys.data('dateend')).toDate(),
                DateStart: moment($sys.data('datestart')).toDate(),
                DifferentUnitsSelectedMessage: $sys.data('differentunitsselectedmessage'),
                LowerRoomRateValue: Number($sys.data('lowerroomratevalue')),
                MaximumRoomRateFilterValue: Number($sys.data('maximumroomratefiltervalue')),
                MinimumRoomRateFilterValue: Number($sys.data('minimumroomratefiltervalue')),
                ProfileItemID: ($sys.data('profileitemid') === '') ? [] : ($sys.data('profileitemid')).toString().split(',').map(function (e) { return Number(e); }),
                RoomBaseIDs: ($sys.data('roombaseids') === '') ? [] : ($sys.data('roombaseids')).toString().split(',').map(function (e) { return Number(e); }),
                RoomLocationAreaID: ($sys.data('roomlocationareaid') === '') ? [] : ($sys.data('roomlocationareaid')).toString().split(',').map(function (e) { return Number(e); }),
                RoomLocationFloorSuiteID: ($sys.data('roomlocationfloorsuiteid') === '') ? [] : ($sys.data('roomlocationfloorsuiteid')).toString().split(',').map(function (e) { return Number(e); }),
                RoomLocationID: ($sys.data('roomlocationid') === '') ? [] : ($sys.data('roomlocationid')).toString().split(',').map(function (e) { return Number(e); }),
                RoomTypeID: ($sys.data('roomtypeid') === '') ? [] : ($sys.data('roomtypeid')).toString().split(',').map(function (e) { return Number(e); }),
                UpperRoomRateValue: Number($sys.data('upperroomratevalue'))
            };
        }
        model.RoomSelectionModel = RoomSelectionModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var roomsearch;
        (function (roomsearch) {
            "use strict";
            var AddRoomToCart = (function (_super) {
                __extends(AddRoomToCart, _super);
                function AddRoomToCart(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "AddRoomToCart";
                }
                AddRoomToCart.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                AddRoomToCart.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        checkInDate: this.o.checkInDate,
                        checkOutDate: this.o.checkOutDate,
                        pageID: this.o.pageID,
                        roomBaseID: this.o.roomBaseID,
                        roomRateID: this.o.roomRateID
                    };
                    return obj;
                };
                return AddRoomToCart;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.AddRoomToCart = AddRoomToCart;
            var AddRoomToCartForGroup = (function (_super) {
                __extends(AddRoomToCartForGroup, _super);
                function AddRoomToCartForGroup(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "AddRoomToCartForGroup";
                }
                AddRoomToCartForGroup.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                AddRoomToCartForGroup.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        checkInDate: this.o.checkInDate,
                        checkOutDate: this.o.checkOutDate,
                        groupID: this.o.groupID,
                        pageID: this.o.pageID,
                        roomBaseID: this.o.roomBaseID,
                        roomRateID: this.o.roomRateID
                    };
                    return obj;
                };
                return AddRoomToCartForGroup;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.AddRoomToCartForGroup = AddRoomToCartForGroup;
            var AddRoomToCartForTerm = (function (_super) {
                __extends(AddRoomToCartForTerm, _super);
                function AddRoomToCartForTerm(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "AddRoomToCartForTerm";
                }
                AddRoomToCartForTerm.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                AddRoomToCartForTerm.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        checkInDate: this.o.checkInDate,
                        checkOutDate: this.o.checkOutDate,
                        pageID: this.o.pageID,
                        roomBaseID: this.o.roomBaseID,
                        roomRateID: this.o.roomRateID,
                        termID: this.o.termID
                    };
                    return obj;
                };
                return AddRoomToCartForTerm;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.AddRoomToCartForTerm = AddRoomToCartForTerm;
            var AddRoomTypeLocationToCart = (function (_super) {
                __extends(AddRoomTypeLocationToCart, _super);
                function AddRoomTypeLocationToCart(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "AddRoomTypeLocationToCart";
                }
                AddRoomTypeLocationToCart.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                AddRoomTypeLocationToCart.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        checkInDate: this.o.checkInDate,
                        checkOutDate: this.o.checkOutDate,
                        pageID: this.o.pageID,
                        roomLocationID: this.o.roomLocationID,
                        roomRateID: this.o.roomRateID,
                        roomTypeID: this.o.roomTypeID
                    };
                    return obj;
                };
                return AddRoomTypeLocationToCart;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.AddRoomTypeLocationToCart = AddRoomTypeLocationToCart;
            var AddRoomTypeLocationToCartForGroup = (function (_super) {
                __extends(AddRoomTypeLocationToCartForGroup, _super);
                function AddRoomTypeLocationToCartForGroup(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "AddRoomTypeLocationToCartForGroup";
                }
                AddRoomTypeLocationToCartForGroup.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                AddRoomTypeLocationToCartForGroup.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        checkInDate: this.o.checkInDate,
                        checkOutDate: this.o.checkOutDate,
                        groupID: this.o.groupID,
                        pageID: this.o.pageID,
                        roomLocationID: this.o.roomLocationID,
                        roomRateID: this.o.roomRateID,
                        roomTypeID: this.o.roomTypeID
                    };
                    return obj;
                };
                return AddRoomTypeLocationToCartForGroup;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.AddRoomTypeLocationToCartForGroup = AddRoomTypeLocationToCartForGroup;
            var AddRoomTypeLocationToCartForTerm = (function (_super) {
                __extends(AddRoomTypeLocationToCartForTerm, _super);
                function AddRoomTypeLocationToCartForTerm(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "AddRoomTypeLocationToCartForTerm";
                }
                AddRoomTypeLocationToCartForTerm.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                AddRoomTypeLocationToCartForTerm.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        checkInDate: this.o.checkInDate,
                        checkOutDate: this.o.checkOutDate,
                        pageID: this.o.pageID,
                        roomLocationID: this.o.roomLocationID,
                        roomRateID: this.o.roomRateID,
                        roomTypeID: this.o.roomTypeID,
                        termID: this.o.termID
                    };
                    return obj;
                };
                return AddRoomTypeLocationToCartForTerm;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.AddRoomTypeLocationToCartForTerm = AddRoomTypeLocationToCartForTerm;
            var AssignBeds = (function (_super) {
                __extends(AssignBeds, _super);
                function AssignBeds(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "AssignBeds";
                }
                AssignBeds.prototype.CallData = function () {
                    var obj = {
                        assignments: this.o.assignments,
                        newInvitations: this.o.newInvitations
                    };
                    return obj;
                };
                AssignBeds.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        checkInDate: this.o.checkInDate,
                        checkOutDate: this.o.checkOutDate,
                        pageID: this.o.pageID,
                        roomBaseIDs: this.o.roomBaseIDs
                    };
                    return obj;
                };
                return AssignBeds;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.AssignBeds = AssignBeds;
            var CalculateTotalRoomPrice = (function (_super) {
                __extends(CalculateTotalRoomPrice, _super);
                function CalculateTotalRoomPrice(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "CalculateTotalRoomPrice";
                }
                CalculateTotalRoomPrice.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                CalculateTotalRoomPrice.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        checkInDate: this.o.checkInDate,
                        checkOutDate: this.o.checkOutDate,
                        pageID: this.o.pageID,
                        roomBaseID: this.o.roomBaseID,
                        roomRateID: this.o.roomRateID
                    };
                    return obj;
                };
                return CalculateTotalRoomPrice;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.CalculateTotalRoomPrice = CalculateTotalRoomPrice;
            var CalculateTotalRoomTypeLocationPrice = (function (_super) {
                __extends(CalculateTotalRoomTypeLocationPrice, _super);
                function CalculateTotalRoomTypeLocationPrice(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "CalculateTotalRoomTypeLocationPrice";
                }
                CalculateTotalRoomTypeLocationPrice.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                CalculateTotalRoomTypeLocationPrice.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        checkInDate: this.o.checkInDate,
                        checkOutDate: this.o.checkOutDate,
                        pageID: this.o.pageID,
                        roomLocationID: this.o.roomLocationID,
                        roomRateID: this.o.roomRateID,
                        roomTypeID: this.o.roomTypeID
                    };
                    return obj;
                };
                return CalculateTotalRoomTypeLocationPrice;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.CalculateTotalRoomTypeLocationPrice = CalculateTotalRoomTypeLocationPrice;
            var GetFilterResults = (function (_super) {
                __extends(GetFilterResults, _super);
                function GetFilterResults(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "GetFilterResults";
                }
                GetFilterResults.prototype.CallData = function () {
                    var obj = {
                        classificationID: this.o.classificationID,
                        currentPageNumber: this.o.currentPageNumber,
                        filters: this.o.filters,
                        groupID: this.o.groupID,
                        pageID: this.o.pageID,
                        processID: this.o.processID,
                        termID: this.o.termID
                    };
                    return obj;
                };
                return GetFilterResults;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.GetFilterResults = GetFilterResults;
            var GetInitialFilterStepResults = (function (_super) {
                __extends(GetInitialFilterStepResults, _super);
                function GetInitialFilterStepResults(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "GetInitialFilterStepResults";
                }
                GetInitialFilterStepResults.prototype.CallData = function () {
                    var obj = {
                        classificationID: this.o.classificationID,
                        dateEnd: this.o.dateEnd,
                        dateStart: this.o.dateStart,
                        groupID: this.o.groupID,
                        pageID: this.o.pageID,
                        termID: this.o.termID
                    };
                    return obj;
                };
                return GetInitialFilterStepResults;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.GetInitialFilterStepResults = GetInitialFilterStepResults;
            var GetSuggestions = (function (_super) {
                __extends(GetSuggestions, _super);
                function GetSuggestions(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "GetSuggestions";
                }
                GetSuggestions.prototype.CallData = function () {
                    var obj = {
                        classificationID: this.o.classificationID,
                        groupID: this.o.groupID,
                        pageID: this.o.pageID,
                        processID: this.o.processID,
                        roomSearchGuid: this.o.roomSearchGuid,
                        suggestions: this.o.suggestions,
                        termID: this.o.termID
                    };
                    return obj;
                };
                return GetSuggestions;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.GetSuggestions = GetSuggestions;
            var GetTermCardContent = (function (_super) {
                __extends(GetTermCardContent, _super);
                function GetTermCardContent(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "GetTermCardContent";
                }
                GetTermCardContent.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID,
                        tableID: this.o.tableID
                    };
                    return obj;
                };
                return GetTermCardContent;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.GetTermCardContent = GetTermCardContent;
            var RemoveRoomFromCart = (function (_super) {
                __extends(RemoveRoomFromCart, _super);
                function RemoveRoomFromCart(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "RemoveRoomFromCart";
                }
                RemoveRoomFromCart.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                RemoveRoomFromCart.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID,
                        processID: this.o.processID,
                        roomBaseID: this.o.roomBaseID
                    };
                    return obj;
                };
                return RemoveRoomFromCart;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.RemoveRoomFromCart = RemoveRoomFromCart;
            var RenewRoom = (function (_super) {
                __extends(RenewRoom, _super);
                function RenewRoom(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "RenewRoom";
                }
                RenewRoom.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                RenewRoom.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return RenewRoom;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.RenewRoom = RenewRoom;
            var Restart = (function (_super) {
                __extends(Restart, _super);
                function Restart(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "Restart";
                }
                Restart.prototype.CallData = function () {
                    var obj = {
                        classificationID: this.o.classificationID,
                        groupID: this.o.groupID,
                        pageID: this.o.pageID,
                        processID: this.o.processID,
                        termID: this.o.termID
                    };
                    return obj;
                };
                return Restart;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.Restart = Restart;
            var UpdateFilterData = (function (_super) {
                __extends(UpdateFilterData, _super);
                function UpdateFilterData(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "UpdateFilterData";
                }
                UpdateFilterData.prototype.CallData = function () {
                    var obj = {
                        classificationID: this.o.classificationID,
                        filters: this.o.filters,
                        groupID: this.o.groupID,
                        pageID: this.o.pageID,
                        termID: this.o.termID
                    };
                    return obj;
                };
                return UpdateFilterData;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.UpdateFilterData = UpdateFilterData;
            var UpdateProcessContext = (function (_super) {
                __extends(UpdateProcessContext, _super);
                function UpdateProcessContext(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "UpdateProcessContext";
                }
                UpdateProcessContext.prototype.CallData = function () {
                    var obj = {
                        currentPageNumber: this.o.currentPageNumber,
                        filters: this.o.filters,
                        processID: this.o.processID
                    };
                    return obj;
                };
                return UpdateProcessContext;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.UpdateProcessContext = UpdateProcessContext;
            var ValidateNumberOfRoomSpacesForSingleRoom = (function (_super) {
                __extends(ValidateNumberOfRoomSpacesForSingleRoom, _super);
                function ValidateNumberOfRoomSpacesForSingleRoom(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "ValidateNumberOfRoomSpacesForSingleRoom";
                }
                ValidateNumberOfRoomSpacesForSingleRoom.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID,
                        roomBaseID: this.o.roomBaseID
                    };
                    return obj;
                };
                return ValidateNumberOfRoomSpacesForSingleRoom;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.ValidateNumberOfRoomSpacesForSingleRoom = ValidateNumberOfRoomSpacesForSingleRoom;
            var ValidateNumberOfRoomSpacesSelected = (function (_super) {
                __extends(ValidateNumberOfRoomSpacesSelected, _super);
                function ValidateNumberOfRoomSpacesSelected(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSearch";
                    this.Controller = "roomsearch";
                    this.Action = "ValidateNumberOfRoomSpacesSelected";
                }
                ValidateNumberOfRoomSpacesSelected.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID
                    };
                    return obj;
                };
                return ValidateNumberOfRoomSpacesSelected;
            })(starrez.library.service.AddInActionCallBase);
            roomsearch.ValidateNumberOfRoomSpacesSelected = ValidateNumberOfRoomSpacesSelected;
        })(roomsearch = service.roomsearch || (service.roomsearch = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var roomswap;
        (function (roomswap) {
            var roomswapmanagement;
            (function (roomswapmanagement) {
                "use strict";
                (function (RoomSwapActionType) {
                    RoomSwapActionType[RoomSwapActionType["None"] = 0] = "None";
                    RoomSwapActionType[RoomSwapActionType["sendRoomSwapRequest"] = 1] = "sendRoomSwapRequest";
                    RoomSwapActionType[RoomSwapActionType["cancelRoomSwapRequest"] = 2] = "cancelRoomSwapRequest";
                    RoomSwapActionType[RoomSwapActionType["acceptRoomSwapRequest"] = 3] = "acceptRoomSwapRequest";
                    RoomSwapActionType[RoomSwapActionType["declineRoomSwapRequest"] = 4] = "declineRoomSwapRequest";
                })(roomswapmanagement.RoomSwapActionType || (roomswapmanagement.RoomSwapActionType = {}));
                var RoomSwapActionType = roomswapmanagement.RoomSwapActionType;
                ;
                function Initialise($container) {
                    new ResourceManagement($container);
                }
                roomswapmanagement.Initialise = Initialise;
                var ResourceManagement = (function () {
                    function ResourceManagement($container) {
                        this.$container = $container;
                        this.pageID = portal.page.CurrentPage.PageID;
                        this.model = starrez.model.RoomSwapManagementModel($container);
                        this.AttachEvents();
                        this.$container.find(".ui-preference-icon").tooltip();
                        this.$container.find(".ui-disabled").tooltip();
                        portal.actionpanel.control.AutoAdjustActionPanelHeights(this.$container);
                    }
                    ResourceManagement.prototype.AttachEvents = function () {
                        this.SetupActionRoomSwapRequestEvents();
                    };
                    ResourceManagement.prototype.ActionRoomSwap = function (roomSwapAction, $currentTarget, $button) {
                        var _this = this;
                        var $actionPanel = $currentTarget.closest(".ui-card-result");
                        portal.ConfirmAction($button.data("confirmationtext"), $button.data("confirmationtitle")).done(function () {
                            var call = new starrez.service.roomswap.ActionRoomSwapRequest({
                                roomSpaceSwapRequestID: Number($actionPanel.data("roomspaceswapid")),
                                theirBookingID: Number($actionPanel.data("their_bookingid")),
                                roomSwapActionType: RoomSwapActionType[roomSwapAction],
                                hash: $button.data("hash"),
                                pageID: _this.pageID,
                                myBookingID: _this.model.My_BookingID
                            }).Post().done(function (url) {
                                location.href = url;
                            });
                        });
                    };
                    ResourceManagement.prototype.SetupActionRoomSwapRequestEvents = function () {
                        var _this = this;
                        this.$container.find(".ui-accept-request").SRClick(function (e) {
                            var $currentTarget = $(e.currentTarget);
                            var $button = $currentTarget.closest(".ui-accept-request");
                            _this.ActionRoomSwap(RoomSwapActionType.acceptRoomSwapRequest, $currentTarget, $button);
                        });
                        this.$container.find(".ui-decline-request").SRClick(function (e) {
                            var $currentTarget = $(e.currentTarget);
                            var $button = $currentTarget.closest(".ui-decline-request");
                            _this.ActionRoomSwap(RoomSwapActionType.declineRoomSwapRequest, $currentTarget, $button);
                        });
                        this.$container.find(".ui-cancel-request").SRClick(function (e) {
                            var $currentTarget = $(e.currentTarget);
                            var $button = $currentTarget.closest(".ui-cancel-request");
                            _this.ActionRoomSwap(RoomSwapActionType.cancelRoomSwapRequest, $currentTarget, $button);
                        });
                        this.$container.find(".ui-book-request").SRClick(function (e) {
                            var $currentTarget = $(e.currentTarget);
                            var $button = $currentTarget.closest(".ui-book-request");
                            location.href = $button.data("href");
                        });
                    };
                    return ResourceManagement;
                })();
            })(roomswapmanagement = roomswap.roomswapmanagement || (roomswap.roomswapmanagement = {}));
        })(roomswap = general.roomswap || (general.roomswap = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

/// <reference path="../../../../WebCommon/TypeScriptTypes/lib.d.ts" />
var portal;
(function (portal) {
    var general;
    (function (general) {
        var roomswap;
        (function (roomswap) {
            var roomswapsearch;
            (function (roomswapsearch) {
                "use strict";
                var isDefined = starrez.library.utils.IsNotNullUndefined;
                function InitRoomSwapSearchPage($container) {
                    roomswapsearch.Model = new RoomSwapSearchModel($container);
                }
                roomswapsearch.InitRoomSwapSearchPage = InitRoomSwapSearchPage;
                var MatchTypes;
                (function (MatchTypes) {
                    MatchTypes[MatchTypes["Predefined"] = 0] = "Predefined";
                    MatchTypes[MatchTypes["Custom"] = 1] = "Custom";
                })(MatchTypes || (MatchTypes = {}));
                var Preferences;
                (function (Preferences) {
                    Preferences[Preferences["Mine"] = 0] = "Mine";
                    Preferences[Preferences["Theirs"] = 1] = "Theirs";
                })(Preferences || (Preferences = {}));
                var RoomSwapSearchModel = (function () {
                    function RoomSwapSearchModel($container) {
                        this.$container = $container;
                        this.$resultsContainer = this.$container.find(".ui-room-swap-search-results");
                        this.$locationFilters = $container.find(".ui-location-filters");
                        this.$typeFilters = $container.find(".ui-type-filters");
                        this.$myPreference = $container.GetControl("MyPreference");
                        this.$theirPreference = $container.GetControl("TheirPreference");
                        this.pageID = portal.page.CurrentPage.PageID;
                        this.model = starrez.model.RoomSwapSearchModel($container);
                        if (Number(MatchTypes[this.model.MyRequirementsFilterMatch]) === MatchTypes.Custom) {
                            this.$myPreference.SRVal(MatchTypes[this.model.MyRequirementsFilterMatch]);
                            this.SetGroupValues(this.model.MyRoomLocationIDs, this.model.MyRoomTypeIDs, Preferences.Mine);
                        }
                        if (Number(MatchTypes[this.model.TheirRequirementsFilterMatch]) === MatchTypes.Custom) {
                            this.$theirPreference.SRVal(MatchTypes[this.model.TheirRequirementsFilterMatch]);
                            this.SetGroupValues(this.model.TheirRoomLocationIDs, this.model.TheirRoomTypeIDs, Preferences.Theirs);
                        }
                        this.CheckFilters(this.$myPreference, Preferences.Mine);
                        this.CheckFilters(this.$theirPreference, Preferences.Theirs);
                        if (this.model.CurrentPageNumber <= 0) {
                            this.model.CurrentPageNumber = 1;
                        }
                        this.LoadResults(this.model.CurrentPageNumber);
                        this.AttachEvents();
                    }
                    RoomSwapSearchModel.prototype.ReloadResults = function () {
                        this.LoadResults(1); // load from the first page
                    };
                    RoomSwapSearchModel.prototype.LoadResults = function (currentPageNumber) {
                        var _this = this;
                        this.currentPageNumber = currentPageNumber;
                        var location = this.GetGroupIDArray(this.$locationFilters);
                        var type = this.GetGroupIDArray(this.$typeFilters);
                        var myFilters = this.GetFiltersValue(this.$myPreference, location.Mine, type.Mine);
                        var theirFilters = this.GetFiltersValue(this.$theirPreference, location.Theirs, type.Theirs);
                        new starrez.service.roomswap.GetFilterResults({
                            pageID: this.pageID,
                            pageDetailID: this.model.DetailsPageID,
                            myBookingID: this.model.My_BookingID,
                            myRequirementFilters: myFilters,
                            theirRequirementFilters: theirFilters,
                            currentPageNumber: this.currentPageNumber
                        }).Post().done(function (result) {
                            _this.$resultsContainer.html($.toHTML(result));
                            portal.paging.AttachPagingClickEvent(_this, _this.$resultsContainer, _this.LoadResults);
                            _this.$resultsContainer.find(".ui-preference-icon").tooltip();
                            _this.SetupRequestSwapAction();
                            portal.actionpanel.control.AutoAdjustActionPanelHeights(_this.$container);
                        });
                    };
                    RoomSwapSearchModel.prototype.GetFiltersValue = function ($dropdown, location, type) {
                        return {
                            FilterMatch: $dropdown.SRVal(),
                            LocationIDs: location,
                            RoomTypeIDs: type
                        };
                    };
                    RoomSwapSearchModel.prototype.GetGroupIDArray = function ($group) {
                        var result = {
                            Mine: [],
                            Theirs: []
                        };
                        $group.each(function (item, elem) {
                            var $elem = $(elem);
                            var value = $elem.data("item-id");
                            var isMine = starrez.library.convert.ToBoolean($elem.GetControl("Mine").SRVal());
                            var isTheres = starrez.library.convert.ToBoolean($elem.GetControl("Theirs").SRVal());
                            if (isMine) {
                                result.Mine.push(value);
                            }
                            if (isTheres) {
                                result.Theirs.push(value);
                            }
                        });
                        return result;
                    };
                    RoomSwapSearchModel.prototype.SetGroupValues = function (locationIDs, typeIDs, preferences) {
                        var _this = this;
                        if (isDefined(locationIDs)) {
                            $.each(locationIDs, function (index, item) {
                                _this.$locationFilters
                                    .siblings("[data-item-id='" + item + "']")
                                    .GetControl(Preferences[preferences])
                                    .SRVal(true);
                            });
                        }
                        if (isDefined(typeIDs)) {
                            $.each(typeIDs, function (index, item) {
                                _this.$typeFilters
                                    .siblings("[data-item-id='" + item + "']")
                                    .GetControl(Preferences[preferences])
                                    .SRVal(true);
                            });
                        }
                    };
                    RoomSwapSearchModel.prototype.CheckFilters = function ($dropdown, preferences) {
                        var matchType = Number($dropdown.SRVal());
                        var loopAndEnable = function ($group, enable, controlName) {
                            $group.each(function (i, elem) {
                                var $control = $(elem).GetControl(controlName);
                                if (enable) {
                                    $control.Enable();
                                    $control.find('.ui-checkbox-controls-container').Enable();
                                }
                                else {
                                    $control.Disable();
                                    $control.find('.ui-checkbox-controls-container').Disable();
                                }
                                $control.SRVal(false);
                            });
                        };
                        var enableDisable = false;
                        if (matchType === MatchTypes.Custom) {
                            enableDisable = true;
                        }
                        else {
                            enableDisable = false;
                        }
                        var mineTheirs = "";
                        if (preferences === Preferences.Mine) {
                            mineTheirs = "Mine";
                        }
                        else {
                            mineTheirs = "Theirs";
                        }
                        loopAndEnable(this.$locationFilters, enableDisable, mineTheirs);
                        loopAndEnable(this.$typeFilters, enableDisable, mineTheirs);
                    };
                    RoomSwapSearchModel.prototype.SetupRequestSwapAction = function () {
                        var _this = this;
                        this.$container.find(".ui-request-swap").SRClick(function (e) {
                            var $button = $(e.currentTarget);
                            var $result = $button.closest(".ui-card-result");
                            portal.ConfirmAction($button.data("confirmationtext"), $button.data("confirmationtitle")).done(function () {
                                var call = new starrez.service.roomswap.RequestSwap({
                                    myBookingID: _this.model.My_BookingID,
                                    theirEntryID: Number($result.data("theirentryid")),
                                    theirBookingID: Number($result.data("theirbookingid")),
                                    pageID: _this.pageID,
                                    hash: $button.data("hash")
                                });
                                call.Post().done(function (url) {
                                    location.href = url;
                                });
                            });
                        });
                    };
                    RoomSwapSearchModel.prototype.AttachEvents = function () {
                        var _this = this;
                        this.$locationFilters.GetControl(Preferences[Preferences.Mine]).SRClick(function (e) {
                            _this.ReloadResults();
                        });
                        this.$locationFilters.GetControl(Preferences[Preferences.Theirs]).SRClick(function (e) {
                            _this.ReloadResults();
                        });
                        this.$typeFilters.GetControl(Preferences[Preferences.Mine]).SRClick(function (e) {
                            _this.ReloadResults();
                        });
                        this.$typeFilters.GetControl(Preferences[Preferences.Theirs]).SRClick(function (e) {
                            _this.ReloadResults();
                        });
                        //dropdowns
                        this.$myPreference.change(function (e) {
                            _this.CheckFilters(_this.$myPreference, Preferences.Mine);
                            _this.ReloadResults();
                        });
                        this.$theirPreference.change(function (e) {
                            _this.CheckFilters(_this.$theirPreference, Preferences.Theirs);
                            _this.ReloadResults();
                        });
                        portal.mobile.SetupExpandAndCollapse(this.$container);
                    };
                    return RoomSwapSearchModel;
                })();
                ;
            })(roomswapsearch = roomswap.roomswapsearch || (roomswap.roomswapsearch = {}));
        })(roomswap = general.roomswap || (general.roomswap = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function RoomSwapManagementModel($sys) {
            return {
                My_BookingID: Number($sys.data('my_bookingid'))
            };
        }
        model.RoomSwapManagementModel = RoomSwapManagementModel;
        function RoomSwapSearchModel($sys) {
            return {
                ConfirmRoomSwapRequestText: $sys.data('confirmroomswaprequesttext'),
                ConfirmRoomSwapRequestTitle: $sys.data('confirmroomswaprequesttitle'),
                CurrentPageNumber: Number($sys.data('currentpagenumber')),
                DetailsPageID: Number($sys.data('detailspageid')),
                My_BookingID: Number($sys.data('my_bookingid')),
                MyRequirementsFilterMatch: $sys.data('myrequirementsfiltermatch'),
                MyRoomLocationIDs: ($sys.data('myroomlocationids') === '') ? [] : ($sys.data('myroomlocationids')).toString().split(',').map(function (e) { return Number(e); }),
                MyRoomTypeIDs: ($sys.data('myroomtypeids') === '') ? [] : ($sys.data('myroomtypeids')).toString().split(',').map(function (e) { return Number(e); }),
                TheirRequirementsFilterMatch: $sys.data('theirrequirementsfiltermatch'),
                TheirRoomLocationIDs: ($sys.data('theirroomlocationids') === '') ? [] : ($sys.data('theirroomlocationids')).toString().split(',').map(function (e) { return Number(e); }),
                TheirRoomTypeIDs: ($sys.data('theirroomtypeids') === '') ? [] : ($sys.data('theirroomtypeids')).toString().split(',').map(function (e) { return Number(e); })
            };
        }
        model.RoomSwapSearchModel = RoomSwapSearchModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var roomswap;
        (function (roomswap) {
            "use strict";
            var ActionRoomSwapRequest = (function (_super) {
                __extends(ActionRoomSwapRequest, _super);
                function ActionRoomSwapRequest(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSwap";
                    this.Controller = "roomswap";
                    this.Action = "ActionRoomSwapRequest";
                }
                ActionRoomSwapRequest.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                ActionRoomSwapRequest.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        myBookingID: this.o.myBookingID,
                        pageID: this.o.pageID,
                        roomSpaceSwapRequestID: this.o.roomSpaceSwapRequestID,
                        roomSwapActionType: this.o.roomSwapActionType,
                        theirBookingID: this.o.theirBookingID
                    };
                    return obj;
                };
                return ActionRoomSwapRequest;
            })(starrez.library.service.AddInActionCallBase);
            roomswap.ActionRoomSwapRequest = ActionRoomSwapRequest;
            var GetFilterResults = (function (_super) {
                __extends(GetFilterResults, _super);
                function GetFilterResults(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSwap";
                    this.Controller = "roomswap";
                    this.Action = "GetFilterResults";
                }
                GetFilterResults.prototype.CallData = function () {
                    var obj = {
                        currentPageNumber: this.o.currentPageNumber,
                        myBookingID: this.o.myBookingID,
                        myRequirementFilters: this.o.myRequirementFilters,
                        pageDetailID: this.o.pageDetailID,
                        pageID: this.o.pageID,
                        theirRequirementFilters: this.o.theirRequirementFilters
                    };
                    return obj;
                };
                return GetFilterResults;
            })(starrez.library.service.AddInActionCallBase);
            roomswap.GetFilterResults = GetFilterResults;
            var RequestSwap = (function (_super) {
                __extends(RequestSwap, _super);
                function RequestSwap(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "RoomSwap";
                    this.Controller = "roomswap";
                    this.Action = "RequestSwap";
                }
                RequestSwap.prototype.CallData = function () {
                    var obj = {};
                    return obj;
                };
                RequestSwap.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        myBookingID: this.o.myBookingID,
                        pageID: this.o.pageID,
                        theirBookingID: this.o.theirBookingID,
                        theirEntryID: this.o.theirEntryID
                    };
                    return obj;
                };
                return RequestSwap;
            })(starrez.library.service.AddInActionCallBase);
            roomswap.RequestSwap = RequestSwap;
        })(roomswap = service.roomswap || (service.roomswap = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var products;
        (function (products) {
            "use strict";
            function InitProductDetails($container) {
                new ProductDetailsManager($container);
            }
            products.InitProductDetails = InitProductDetails;
            var ProductDetailsManager = (function () {
                function ProductDetailsManager($container) {
                    var _this = this;
                    this.$container = $container;
                    this.shoppingCartItemID = starrez.model.ProductDetailsModel(this.$container).ShoppingCartItemID;
                    this.$totalAmount = this.$container.find(".ui-quantity-total");
                    this.$qtyControl = this.$container.GetControl("SelectedQuantity");
                    this.getTotalAmountHash = this.$qtyControl.closest("li").data("hash").toString();
                    this.$qtyControl.change(function (e) {
                        var qty = Number(_this.$qtyControl.SRVal());
                        var call = new starrez.service.shoppingcart.GetTotalAmount({
                            pageID: portal.page.CurrentPage.PageID,
                            shoppingCartItemID: _this.shoppingCartItemID,
                            quantity: qty,
                            hash: _this.getTotalAmountHash
                        });
                        call.Post().done(function (amount) {
                            _this.$totalAmount.text(amount);
                        });
                    });
                }
                return ProductDetailsManager;
            })();
            products.ProductDetailsManager = ProductDetailsManager;
        })(products = general.products || (general.products = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var portal;
(function (portal) {
    var shoppingcart;
    (function (shoppingcart) {
        var shoppingcartcheckout;
        (function (shoppingcartcheckout) {
            "use strict";
            function CheckoutInit($container) {
                var cart = new ShoppingCartPageManager($container, starrez.model.ShoppingCartItemListSettingsModel($container));
                cart.Initialize();
            }
            shoppingcartcheckout.CheckoutInit = CheckoutInit;
            var ShoppingCartPageManager = (function () {
                function ShoppingCartPageManager($container, model) {
                    this.$container = $container;
                    this.model = model;
                    this.removedItemsFromCart = false;
                    this.itemDescriptionDataFieldName = "description";
                }
                ShoppingCartPageManager.prototype.Initialize = function () {
                    this.$removeButtons = this.$container.find(".ui-remove-from-cart");
                    var table = this.$container.find(".ui-shopping-cart > .ui-active-table");
                    if (starrez.library.utils.IsNotNullUndefined(table)) {
                        var managers = starrez.tablesetup.CreateTableManager(table, this.$container);
                        if (starrez.library.utils.IsNotNullUndefined(managers) && managers.length > 0) {
                            this.cartTable = managers[0];
                        }
                    }
                    this.AddSubtotalRow();
                    this.AttachBaseEvents();
                    this.AttachEvents();
                    this.CheckEmptyCart();
                };
                ShoppingCartPageManager.prototype.HideHoldTimer = function () {
                    portal.navigation.NavigationBar.HideHoldTimer();
                };
                ShoppingCartPageManager.prototype.AddSubtotalRow = function () {
                    var _this = this;
                    if (starrez.library.utils.IsNullOrUndefined(this.cartTable)) {
                        return;
                    }
                    var $tableFooter = this.cartTable.$table.find("tfoot");
                    if (!$tableFooter.isFound()) {
                        $tableFooter = $("<tfoot>");
                        $tableFooter.addClass("padded");
                        this.cartTable.$table.append($tableFooter);
                    }
                    var $newRow = $("<tr>").appendTo($tableFooter);
                    var totalHeadingDisplayed = false;
                    var $tableHeader = this.cartTable.$table.find("thead");
                    if ($tableHeader.isFound()) {
                        $tableHeader.find("th").each(function (index, element) {
                            if ($(element).hasClass("ui-tax-total-column")) {
                                _this.AddTotalLabel($newRow);
                                totalHeadingDisplayed = true;
                                var tax = _this.GetTotalTax();
                                var subTotalTaxCell = $("<td>").text(tax).addClass("sub-total-tax");
                                $newRow.append(subTotalTaxCell);
                            }
                            else if ($(element).hasClass("ui-amount-column")) {
                                // format the cart sub total amount to show currency
                                if (!totalHeadingDisplayed) {
                                    _this.AddTotalLabel($newRow);
                                }
                                var amount = _this.GetTotalAmount();
                                var subTotalAmountCell = $("<td>").text(amount).addClass("sub-total");
                                $newRow.append(subTotalAmountCell);
                            }
                            else {
                                $newRow.append("<td>");
                            }
                        });
                    }
                };
                ShoppingCartPageManager.prototype.AddTotalLabel = function ($newRow) {
                    $newRow.find("td").last().text("Total:").addClass("sub-total-label");
                };
                ShoppingCartPageManager.prototype.GetRemoveFromCartMessage = function (itemDescription) {
                    return "Do you want to remove '" + itemDescription + "' from your cart?";
                };
                /**
                * updates the sub total cost at the bottom of the table
                * @param $container the div containing the total total cost element
                * @param subTotal the new subtotal of the cart
                */
                ShoppingCartPageManager.prototype.UpdateSubTotal = function (subTotal) {
                    if (!starrez.library.stringhelper.IsUndefinedOrEmpty(subTotal)) {
                        var $subTotal = this.$container.find(".sub-total");
                        $subTotal.text(subTotal);
                        portal.navigation.NavigationBar.UpdateShoppingCart();
                    }
                };
                /**
                * updates the sub total tax at the bottom of the table
                * @param $container the div containing the total total cost element
                * @param subTotalTax the new subtotal tax of the cart
                */
                ShoppingCartPageManager.prototype.UpdateSubTotalTax = function (subTotalTax) {
                    if (!starrez.library.stringhelper.IsUndefinedOrEmpty(subTotalTax)) {
                        var $subTotalTax = this.$container.find(".sub-total-tax");
                        $subTotalTax.text(subTotalTax);
                    }
                };
                /**
                * makes the call to remove an item from the cart then updates the UI
                * @param $container the main container of the page
                * @param $row the row containing the item
                */
                ShoppingCartPageManager.prototype.RemoveItemFromCart = function ($row, hash) {
                    var _this = this;
                    var deferred = $.Deferred();
                    new starrez.service.shoppingcart.RemoveFromCart({
                        hash: hash,
                        tableName: $row.data("tablename"),
                        tableID: $row.data("table")
                    }).Post().done(function (cartSummary) {
                        _this.cartTable.RemoveRows($row);
                        _this.UpdateSubTotal(cartSummary.CartTotalAmount);
                        _this.UpdateSubTotalTax(cartSummary.CartTotalTax);
                        window.location.reload();
                        deferred.resolve();
                    });
                    return deferred.promise();
                };
                ShoppingCartPageManager.prototype.AttachBaseEvents = function () {
                    var _this = this;
                    // remove from cart button click
                    this.$removeButtons.SRClick(function (e) {
                        // if a human clicked it
                        if (e.originalEvent !== undefined) {
                            var itemDescription = $(e.currentTarget).closest("tr").data(_this.itemDescriptionDataFieldName);
                            portal.ConfirmAction(_this.GetRemoveFromCartMessage(itemDescription), "Remove from cart?").done(function () {
                                _this.RemoveItem($(e.currentTarget));
                            });
                        }
                        else {
                            _this.RemoveItem($(e.currentTarget));
                        }
                    });
                };
                ShoppingCartPageManager.prototype.RemoveItem = function ($removeButton) {
                    var _this = this;
                    var $row = $removeButton.closest("tr");
                    var hash = $removeButton.data("hash").toString();
                    this.RemoveItemFromCart($row, hash).done(function () {
                        _this.removedItemsFromCart = true;
                        _this.CheckEmptyCart();
                    });
                };
                ShoppingCartPageManager.prototype.CheckEmptyCart = function () {
                    if (this.IsCartEmpty()) {
                        this.HideCart();
                        this.HideHoldTimer();
                    }
                };
                ShoppingCartPageManager.prototype.AttachEvents = function () {
                    var _this = this;
                    // quantity input change event
                    if (starrez.library.utils.IsNotNullUndefined(this.cartTable)) {
                        if (this.cartTable.HasRows()) {
                            this.cartTable.Rows().GetControl("quantity").change(function (e) {
                                var $quantityInput = $(e.currentTarget);
                                var $row = $quantityInput.closest("tr");
                                var tableName = $row.data("tablename");
                                var tableID = Number($row.data("table"));
                                var hashData = $quantityInput.closest(".ui-qty-dropdown-hash").data("hash").toString();
                                var call = new starrez.service.shoppingcart.UpdateShoppingCartItemQuantity({
                                    hash: hashData,
                                    tableName: tableName,
                                    tableID: tableID,
                                    newQuantity: $quantityInput.SRVal()
                                });
                                call.Post().done(function (cartItem) {
                                    _this.UpdateRow($row, cartItem);
                                    // update the quantity and sub total
                                    _this.UpdateSubTotal(cartItem.CartTotalAmount);
                                    _this.UpdateSubTotalTax(cartItem.CartTotalTax);
                                    $quantityInput.ResetChanged();
                                });
                            });
                        }
                    }
                };
                ShoppingCartPageManager.prototype.UpdateRow = function ($row, cartItem) {
                    $row.find(".ui-amount").text(cartItem.TotalAmount);
                    $row.find(".ui-amount-ex-tax").text(cartItem.TotalAmountExTax);
                    $row.find(".ui-tax").text(cartItem.TaxAmount);
                    $row.find(".ui-tax2").text(cartItem.TaxAmount2);
                    $row.find(".ui-tax3").text(cartItem.TaxAmount3);
                    $row.find(".ui-tax-total").text(cartItem.TaxAmountTotal);
                    $row.data("quantity", cartItem.Quantity);
                };
                ShoppingCartPageManager.prototype.IsCartEmpty = function () {
                    if (starrez.library.utils.IsNullOrUndefined(this.cartTable)) {
                        return true;
                    }
                    return !this.cartTable.HasRows();
                };
                ShoppingCartPageManager.prototype.GetTotalAmount = function () {
                    return this.model.FormattedSubtotalAmount;
                };
                ShoppingCartPageManager.prototype.GetTotalTax = function () {
                    return this.model.FormattedSubtotalTax;
                };
                ShoppingCartPageManager.prototype.HideCart = function () {
                    // hide the cart list
                    if (starrez.library.utils.IsNotNullUndefined(this.cartTable)) {
                        this.cartTable.$table.SRHide();
                    }
                    var model = starrez.model.ShoppingCartItemListSettingsModel(this.$container);
                    if (model.HideContinueButtonWhenNoCartItems) {
                        // remove the submit/paynow button
                        $(".ui-submit-page-content").remove();
                    }
                    // show messsage and remove pay button if no items in cart
                    this.ShowEmptyCartMessage();
                };
                ShoppingCartPageManager.prototype.ShowEmptyCartMessage = function () {
                    var model = starrez.model.ShoppingCartItemListSettingsModel(this.$container);
                    portal.page.CurrentPage.AddErrorMessage(model.EmptyCartText);
                    portal.page.CurrentPage.ScrollToTop();
                };
                return ShoppingCartPageManager;
            })();
            shoppingcartcheckout.ShoppingCartPageManager = ShoppingCartPageManager;
        })(shoppingcartcheckout = shoppingcart.shoppingcartcheckout || (shoppingcart.shoppingcartcheckout = {}));
    })(shoppingcart = portal.shoppingcart || (portal.shoppingcart = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function CartListHelperExtensionsModel($sys) {
            return {};
        }
        model.CartListHelperExtensionsModel = CartListHelperExtensionsModel;
        function ProductDetailsModel($sys) {
            return {
                ShoppingCartItemID: Number($sys.data('shoppingcartitemid'))
            };
        }
        model.ProductDetailsModel = ProductDetailsModel;
        function ShoppingCartCheckoutModel($sys) {
            return {};
        }
        model.ShoppingCartCheckoutModel = ShoppingCartCheckoutModel;
        function ShoppingCartItemListSettingsModel($sys) {
            return {
                EmptyCartText: $sys.data('emptycarttext'),
                FormattedSubtotalAmount: $sys.data('formattedsubtotalamount'),
                FormattedSubtotalTax: $sys.data('formattedsubtotaltax'),
                HideContinueButtonWhenNoCartItems: starrez.library.convert.ToBoolean($sys.data('hidecontinuebuttonwhennocartitems'))
            };
        }
        model.ShoppingCartItemListSettingsModel = ShoppingCartItemListSettingsModel;
        function ShoppingCartReceiptModel($sys) {
            return {
                FormattedPaidAmount: $sys.data('formattedpaidamount')
            };
        }
        model.ShoppingCartReceiptModel = ShoppingCartReceiptModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var shoppingcart;
        (function (shoppingcart) {
            "use strict";
            var GetTotalAmount = (function (_super) {
                __extends(GetTotalAmount, _super);
                function GetTotalAmount(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "ShoppingCart";
                    this.Controller = "shoppingcart";
                    this.Action = "GetTotalAmount";
                }
                GetTotalAmount.prototype.CallData = function () {
                    var obj = {
                        quantity: this.o.quantity
                    };
                    return obj;
                };
                GetTotalAmount.prototype.QueryData = function () {
                    var obj = {
                        hash: this.o.hash,
                        pageID: this.o.pageID,
                        shoppingCartItemID: this.o.shoppingCartItemID
                    };
                    return obj;
                };
                return GetTotalAmount;
            })(starrez.library.service.AddInActionCallBase);
            shoppingcart.GetTotalAmount = GetTotalAmount;
        })(shoppingcart = service.shoppingcart || (service.shoppingcart = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

/// <reference path="../../../../WebCommon/TypeScriptTypes/lib.d.ts" />
var portal;
(function (portal) {
    var termselector;
    (function (termselector) {
        "use strict";
        function Initialise($container) {
            $container.find(".ui-select-action").SRClick(function (e) {
                var $button = $(e.currentTarget);
                var termID = Number($button.closest(".ui-action-panel").data("termid"));
                $container.GetControl("TermID").SRVal(termID);
                portal.page.CurrentPage.SubmitPage();
            });
        }
        termselector.Initialise = Initialise;
    })(termselector = portal.termselector || (portal.termselector = {}));
})(portal || (portal = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var conferencetheme;
        (function (conferencetheme) {
            "use strict";
            function Initialise() {
                new ConferenceTheme();
            }
            conferencetheme.Initialise = Initialise;
            var ConferenceTheme = (function () {
                function ConferenceTheme() {
                    var _this = this;
                    window.addEventListener("load", function () {
                        _this.navbar = new portal.general.conferencetheme.Navbar();
                        $('.ui-back-to-top').on('click', function () {
                            portal.page.CurrentPage.ScrollToTop();
                        });
                        _this.getFirstFocusableElement(document.body).focus();
                    });
                }
                ConferenceTheme.prototype.getFirstFocusableElement = function (element) {
                    var focusable = element.querySelectorAll(ConferenceTheme.focusableElementTypes);
                    return focusable[0];
                };
                ConferenceTheme.focusableElementTypes = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
                return ConferenceTheme;
            })();
        })(conferencetheme = general.conferencetheme || (general.conferencetheme = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var conferencetheme;
        (function (conferencetheme) {
            "use strict";
            var Navbar = (function () {
                function Navbar() {
                    var _this = this;
                    $(".ui-widget-link").on('click', function (event) { return _this.widgetLinkClick(event); });
                    $('.ui-navbar-open').on('click', function () { return _this.navbarOpenClick(); });
                    $('.ui-navbar-close').on('click', function () { return _this.navbarCloseClick(); });
                    $("body").on('click', function () { return _this.bodyClick(); });
                    $('.ui-navbar-dropdown').on('click', function () { return false; }); // don't close the sidebar if the user clicks it
                    var scrollSpyOffset = $('.ui-menu').height() + 40; //a little bit of extra leeway
                    this.scrollspy = new portal.general.conferencetheme.Scrollspy(scrollSpyOffset);
                }
                Navbar.prototype.closeNavbar = function () {
                    var navbar = $(".ui-navbar-dropdown");
                    if (navbar.hasClass("show-dropdown")) {
                        navbar.removeClass("show-dropdown");
                    }
                };
                Navbar.prototype.openNavbar = function () {
                    var navbar = $(".ui-navbar-dropdown");
                    if (!navbar.hasClass("show-dropdown")) {
                        navbar.addClass("show-dropdown");
                    }
                };
                Navbar.prototype.bodyClick = function () {
                    this.closeNavbar();
                    return true;
                };
                Navbar.prototype.navbarOpenClick = function () {
                    this.openNavbar();
                    var navbarItems = $(".ui-mobile-widget-link");
                    if (navbarItems.length > 0) {
                        navbarItems[0].focus();
                    }
                    return false;
                };
                Navbar.prototype.navbarCloseClick = function () {
                    this.closeNavbar();
                    return false;
                };
                Navbar.prototype.widgetLinkClick = function (event) {
                    var target = $(event.currentTarget.dataset['widgetTarget']);
                    var yPosition = target.offset().top;
                    var yOffset = -$(".ui-menu").height();
                    $.ScrollToWithAnimation(yPosition + yOffset);
                    this.closeNavbar();
                    return false;
                };
                return Navbar;
            })();
            conferencetheme.Navbar = Navbar;
        })(conferencetheme = general.conferencetheme || (general.conferencetheme = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var portal;
(function (portal) {
    var general;
    (function (general) {
        var conferencetheme;
        (function (conferencetheme) {
            "use strict";
            var Scrollspy = (function () {
                function Scrollspy(globalOffset) {
                    var _this = this;
                    if (globalOffset === void 0) { globalOffset = 0; }
                    this.globalOffset = globalOffset;
                    var widgetLinks = document.querySelectorAll(".ui-desktop-widget-link");
                    this.targets = [];
                    for (var i = 0; i < widgetLinks.length; i++) {
                        var link = widgetLinks[i];
                        var targetSelector = link.dataset['widgetTarget'];
                        var targetElement = $(targetSelector)[0];
                        var navItem = link.parentElement;
                        var target = new Target(targetElement, navItem);
                        this.targets.push(target);
                    }
                    window.addEventListener("scroll", function (event) { return _this.onScroll(); });
                    this.onScroll();
                }
                Scrollspy.prototype.onScroll = function () {
                    var scrollTop = window.pageYOffset + this.globalOffset;
                    var targetsAboveScroll = this.targets
                        .filter(function (target) { return target.getY() < scrollTop; });
                    if (targetsAboveScroll.length > 0) {
                        var correctTarget = targetsAboveScroll[targetsAboveScroll.length - 1];
                        if (!correctTarget.active) {
                            var correctTargetIndex = this.targets.indexOf(correctTarget);
                            this.select(correctTargetIndex);
                        }
                    }
                    else {
                        var correctTarget = this.targets[0];
                        if (!correctTarget.active) {
                            this.select(0);
                        }
                    }
                };
                Scrollspy.prototype.select = function (index) {
                    this.targets
                        .filter(function (target) { return target.active; })
                        .forEach(function (target) { return target.deactivate(); });
                    this.selectedIndex = index;
                    this.targets[this.selectedIndex].activate();
                };
                return Scrollspy;
            })();
            conferencetheme.Scrollspy = Scrollspy;
            var Target = (function () {
                function Target(element, navItem) {
                    this.element = element;
                    this.navItem = navItem;
                    this.active = false;
                }
                Target.prototype.getY = function () {
                    var rect = this.element.getBoundingClientRect();
                    return rect.top + window.pageYOffset;
                };
                Target.prototype.activate = function () {
                    this.active = true;
                    this.navItem.AddClass("active");
                };
                Target.prototype.deactivate = function () {
                    this.active = false;
                    this.navItem.RemoveClass("active");
                };
                return Target;
            })();
        })(conferencetheme = general.conferencetheme || (general.conferencetheme = {}));
    })(general = portal.general || (portal.general = {}));
})(portal || (portal = {}));

var portal;
(function (portal) {
    var waitlist;
    (function (waitlist) {
        "use strict";
        function InitWaitListSearchPage($container) {
            new WaitListSearch($container);
        }
        waitlist.InitWaitListSearchPage = InitWaitListSearchPage;
        function InitWaitListStatusPage($container) {
            new WaitListStatus($container);
        }
        waitlist.InitWaitListStatusPage = InitWaitListStatusPage;
        var WaitListSearch = (function () {
            function WaitListSearch($container) {
                this.$container = $container;
                this.$waitListResults = $container.find(".ui-waitlist-results");
                this.$roomType = $container.GetControl("RoomTypeIDs");
                this.$roomLocation = $container.GetControl("RoomLocationIDs");
                this.$selectedWaitList = $container.GetControl("Selected_WaitListID");
                this.$selectedWaitListSlot = $container.find(".ui-selected-waitlist-slot");
                this.$comments = $container.GetControl("Selected_WaitListComments");
                this.model = starrez.model.WaitListSearchModel($container);
                this.AttachEvents();
            }
            WaitListSearch.prototype.AttachEvents = function () {
                var _this = this;
                // we find the select element otherwise it triggers two change events
                this.$roomType.find("select").on("change", function () {
                    _this.GetWaitLists();
                });
                this.$roomLocation.find("select").on("change", function () {
                    _this.GetWaitLists();
                });
                // clicking on the select wait list button
                this.$container.on("click", ".ui-add-waitlist", function (e) {
                    var $addButton = $(e.currentTarget);
                    var $card = $addButton.closest(".ui-card-result");
                    var $removeButton = $card.find(".ui-remove-waitlist");
                    var waitListID = Number($card.data("waitlistid"));
                    _this.$selectedWaitList.SRVal(waitListID);
                    // clone the selected card and place it in the selected wait list slot
                    var $clone = $card.clone();
                    $clone.addClass("horizontal");
                    $clone.find(".buttons").empty();
                    _this.$selectedWaitListSlot.html($clone);
                    $.ScrollToWithAnimation(_this.$selectedWaitListSlot);
                });
            };
            WaitListSearch.prototype.GetWaitLists = function () {
                var _this = this;
                new starrez.service.waitlist.GetWaitListsSearch({
                    roomTypeIDs: this.$roomType.SRVal(),
                    locationIDs: this.$roomLocation.SRVal(),
                    pageID: portal.page.CurrentPage.PageID
                }).Post().done(function (searchResults) {
                    _this.$waitListResults.html(searchResults);
                });
            };
            ;
            return WaitListSearch;
        })();
        var WaitListStatus = (function () {
            function WaitListStatus($container) {
                this.Init($container);
            }
            WaitListStatus.prototype.Init = function ($container) {
                this.$container = $container;
                this.$removeButton = $container.find(".ui-remove-button");
                this.$selectedWaitList = $container.GetControl("SelectedWaitListID");
                this.$tableWaitList = $container.find(".ui-waitlist-status-table");
                this.$entryApplication = $container.GetControl("EntryApplicationID");
                this.AttachRemoveEvents();
                this.AttachTableHandler();
                this.pageID = Number(this.$removeButton.data("pageid"));
                this.$removeButton.Disable();
            };
            WaitListStatus.prototype.AttachRemoveEvents = function () {
                var _this = this;
                this.$removeButton.SRClick(function () {
                    _this.RemoveWaitList(_this.$container);
                });
            };
            WaitListStatus.prototype.AttachTableHandler = function () {
                var _this = this;
                var table = this.$container.find(".ui-active-table");
                var focusable = this.$container.find(".active-table-container");
                starrez.tablesetup.CreateTableManager(table, focusable, {
                    AttachRowClickEvent: true,
                    OnRowClick: function ($tr, $data, e, sender) {
                        if ($tr.isSelected()) {
                            _this.$removeButton.Enable();
                            _this.$selectedWaitList.SRVal($tr.data("waitlist"));
                        }
                        else {
                            _this.$removeButton.Disable();
                        }
                    }
                });
            };
            WaitListStatus.prototype.RemoveWaitList = function ($container) {
                var _this = this;
                new starrez.service.waitlist.RemoveFromWaitList({
                    entryApplicationID: this.$entryApplication.SRVal(),
                    waitListID: this.$selectedWaitList.SRVal(),
                    pageID: this.pageID
                }).Post().done(function (removeResults) {
                    portal.page.CurrentPage.ClearMessages();
                    _this.$tableWaitList.html(removeResults);
                    _this.Init($container);
                });
            };
            return WaitListStatus;
        })();
    })(waitlist = portal.waitlist || (portal.waitlist = {}));
})(portal || (portal = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function WaitListSearchModel($sys) {
            return {};
        }
        model.WaitListSearchModel = WaitListSearchModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var waitlist;
        (function (waitlist) {
            "use strict";
            var GetWaitListsSearch = (function (_super) {
                __extends(GetWaitListsSearch, _super);
                function GetWaitListsSearch(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "WaitList";
                    this.Controller = "waitlist";
                    this.Action = "GetWaitListsSearch";
                }
                GetWaitListsSearch.prototype.CallData = function () {
                    var obj = {
                        locationIDs: this.o.locationIDs,
                        pageID: this.o.pageID,
                        roomTypeIDs: this.o.roomTypeIDs
                    };
                    return obj;
                };
                return GetWaitListsSearch;
            })(starrez.library.service.AddInActionCallBase);
            waitlist.GetWaitListsSearch = GetWaitListsSearch;
            var RemoveFromWaitList = (function (_super) {
                __extends(RemoveFromWaitList, _super);
                function RemoveFromWaitList(o) {
                    _super.call(this);
                    this.o = o;
                    this.Customer = "General";
                    this.Area = "WaitList";
                    this.Controller = "waitlist";
                    this.Action = "RemoveFromWaitList";
                }
                RemoveFromWaitList.prototype.CallData = function () {
                    var obj = {
                        entryApplicationID: this.o.entryApplicationID,
                        pageID: this.o.pageID,
                        waitListID: this.o.waitListID
                    };
                    return obj;
                };
                return RemoveFromWaitList;
            })(starrez.library.service.AddInActionCallBase);
            waitlist.RemoveFromWaitList = RemoveFromWaitList;
        })(waitlist = service.waitlist || (service.waitlist = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var starrez;
(function (starrez) {
    var wpmregistration;
    (function (wpmregistration) {
        "use strict";
        function InitialiseRegistrationPage($container) {
            new RegistrationPage($container);
        }
        wpmregistration.InitialiseRegistrationPage = InitialiseRegistrationPage;
        var RegistrationPage = (function () {
            function RegistrationPage($container) {
                this.$container = $container;
                this.$setupButton = $container.find(".ui-setup");
                this.AttachButtonEvents();
            }
            RegistrationPage.prototype.AttachButtonEvents = function () {
                var _this = this;
                this.$setupButton.SRClick(function () {
                    _this.SetupPayment();
                });
            };
            RegistrationPage.prototype.SetupPayment = function () {
                var call = new starrez.service.wpmregistration.SetupPayment({
                    pageID: portal.page.CurrentPage.PageID,
                    processID: portal.page.CurrentPage.ProcessID
                });
                var url = starrez.library.service.CreateUrl(call.GetURLWithParameters());
                if (window.parent) {
                    parent.location.href = url;
                }
                else {
                    location.href = url;
                }
            };
            return RegistrationPage;
        })();
    })(wpmregistration = starrez.wpmregistration || (starrez.wpmregistration = {}));
})(starrez || (starrez = {}));

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));
var starrez;
(function (starrez) {
    var service;
    (function (service) {
        var wpmregistration;
        (function (wpmregistration) {
            "use strict";
            var SetupPayment = (function (_super) {
                __extends(SetupPayment, _super);
                function SetupPayment(o) {
                    _super.call(this);
                    this.o = o;
                    this.Area = "WPMRegistration";
                    this.Controller = "wpmregistration";
                    this.Action = "SetupPayment";
                }
                SetupPayment.prototype.CallData = function () {
                    var obj = {
                        pageID: this.o.pageID,
                        processID: this.o.processID
                    };
                    return obj;
                };
                return SetupPayment;
            })(starrez.library.service.ActionCallBase);
            wpmregistration.SetupPayment = SetupPayment;
        })(wpmregistration = service.wpmregistration || (service.wpmregistration = {}));
    })(service = starrez.service || (starrez.service = {}));
})(starrez || (starrez = {}));

var starrez;
(function (starrez) {
    var youtube;
    (function (youtube) {
        "use strict";
        function Initialise($container) {
            SetYouTubeWidth($container);
            $(window).resize(function () {
                SetYouTubeWidth($container);
            });
        }
        youtube.Initialise = Initialise;
        function SetYouTubeWidth($container) {
            var widgetSectionWidth = $container.closest(".ui-widget-section").width();
            if (widgetSectionWidth > 560) {
                widgetSectionWidth = 560;
            }
            var $iframe = $container.children("iframe");
            $iframe.attr("width", widgetSectionWidth);
            $container.width(widgetSectionWidth);
        }
    })(youtube = starrez.youtube || (starrez.youtube = {}));
})(starrez || (starrez = {}));

var starrez;
(function (starrez) {
    var zopimchat;
    (function (zopimchat) {
        "use strict";
        function Initialise($container) {
            var model = starrez.model.ZopimChatModel($container);
            $zopim(function () {
                $zopim.livechat.setName(model.EntryName);
                if (model.EntryEmail != "") {
                    $zopim.livechat.setEmail(model.EntryEmail);
                }
                $zopim.livechat.button.setPosition(model.ChatDisplayLocation);
            });
        }
        zopimchat.Initialise = Initialise;
    })(zopimchat = starrez.zopimchat || (starrez.zopimchat = {}));
})(starrez || (starrez = {}));

/*
    THIS FILE IS AUTO-GENERATED.  DO NOT EDIT IT.  ANY CHANGES YOU MAKE WILL BE OVERWRITTEN
    
    */
var starrez;
(function (starrez) {
    var model;
    (function (model) {
        "use strict";
        function ZopimChatModel($sys) {
            return {
                ChatDisplayLocation: $sys.data('chatdisplaylocation'),
                EntryEmail: $sys.data('entryemail'),
                EntryName: $sys.data('entryname')
            };
        }
        model.ZopimChatModel = ZopimChatModel;
    })(model = starrez.model || (starrez.model = {}));
})(starrez || (starrez = {}));

