﻿
function bookingController(VenueID, toggle, dialogName, custDetailsFormID, bookDetailsFormID) {
    this.BookingDetails = new bookingDetails(VenueID)
    this.TabsName = null
    this.DialogName = dialogName
    this.toggleThrobber = toggle
    this.ExistingCustLoaded = false;
    this.EmailCheckDone = null
    this.LoginCheckDone = null
    this.CustomerDetailsFormID = custDetailsFormID
    this.BookingDetailsFormID = bookDetailsFormID
    this.TabIndexStartDate = 0
    this.TabIndexEndDate = 1
    this.TabIndexReturningCust = 2
    this.TabIndexCustDetails = 3
    this.TabIndexBookingDetails = 4
    this.TabIndexBookingSummary = 5
    this.TabIndexPayment = 6
    this.LastOpenTabIndex = null
    this.PrevBtnClicked = false

    //Private Functions
    this.StartDateSelected = function (selectedDateString) {
        thisBooking.BookingDetails.StartDate = selectedDateString;
    }
    this.EndDateSelected = function (selectedDateString) {
        thisBooking.BookingDetails.EndDate = selectedDateString;
    }
    this.InvokeFormValidation = function (id) {
        var form = $('#' + id);
        if (form.valid()) {
            return true;
        }
        else {
            return false;
        }
    }
    var getKeys = function (obj) {
        var keys = [];
        for (var key in obj) {
            keys.push(key);
            //console.log(key + "=" + obj[key]);
        }
        return keys;
    }
    this.EnableNextButton = function () {
        $(".ui-dialog-buttonpane button:contains('Next')").button("enable").addClass("nextReady");
    }
    this.EnablePrevButton = function () {
        $(".ui-dialog-buttonpane button:contains('Prev')").button("enable").addClass("nextReady");
    }
    this.DisableNextButton = function () {
        $(".ui-dialog-buttonpane button:contains('Next')").button("disable").removeClass("nextReady");
    }
    this.DisablePrevButton = function () {
        $(".ui-dialog-buttonpane button:contains('Prev')").button("disable").removeClass("nextReady");
    }
    this.NextTab = function (tabControl) {
        var index = tabControl.tabs('option', 'selected');
        if (thisBooking.CheckTabChangeOk(index)) {
            $("#tabs").tabs("select", (index + 1));
        }
    }
    this.PrevTab = function (tabControl) {
        var index = tabControl.tabs('option', 'selected');
        thisBooking.PrevBtnClicked = true;
        $("#tabs").tabs("select", (index - 1));
        thisBooking.PrevBtnClicked = false;
    }
    this.updateThisBooking = function (changeTab) {
        //getKeys(this.BookingDetails)
        var jlst = $.toJSON(thisBooking.BookingDetails);

        var url = $("#jsonActionURLs").find(".sendToBackEnd").attr("href");
        //send to db
        $.post(url, {
            jsonData: jlst
        },
            function (data, textStatus) {
                thisBooking.BookingDetails.BookingID = parseInt(data);
                var url = $("#tabs").find(".bookingSummaryURL").attr("data-url");
                url = url.replace("0", thisBooking.BookingDetails.BookingID);
                if (changeTab) {
                    $("#tabs").tabs("url", thisBooking.TabIndexBookingSummary, url).tabs("select", thisBooking.TabIndexBookingSummary);
                };
            }
        );

    }
    this.updateCustomerDetails = function (tabControl, index) {
        var tabNumber
        if (index) {
            tabNumber = index + 1;
        }
        else {
            tabNumber = parseInt(tabControl.tabs('option', 'selected')) + 1;
        }
        var tab = $("#ui-tabs-" + tabNumber);
        //console.log("updateCustomerDetails");
        thisBooking.BookingDetails.Firstname = tab.find("#UserDetails_FirstName").val();
        thisBooking.BookingDetails.Lastname = tab.find("#UserDetails_LastName").val();
        thisBooking.BookingDetails.Address1 = tab.find("#UserDetails_Address1").val();
        thisBooking.BookingDetails.Address2 = tab.find("#UserDetails_Address2").val();
        thisBooking.BookingDetails.Town = tab.find("#UserDetails_Town").val();
        thisBooking.BookingDetails.County = tab.find("#UserDetails_County").val();
        thisBooking.BookingDetails.CountryID = tab.find("#UserDetails_CountryID").val();
        thisBooking.BookingDetails.Postcode = tab.find("#UserDetails_PostCode").val();
        thisBooking.BookingDetails.EmailAddress = tab.find("#UserDetails_EmailAddress").val();
        thisBooking.BookingDetails.Phonenumber = tab.find("#UserDetails_PhoneNumber").val();
        thisBooking.BookingDetails.Mobilenumber = tab.find("#UserDetails_MobileNumber").val();
        if (tab.find("#UserDetails_RecieveNewsletter").is(":checked")) {
            thisBooking.BookingDetails.Subscribe = true;
        }
        else {
            thisBooking.BookingDetails.Subscribe = false;
        }

    }
    this.updateBookingDetails = function (tabControl, index) {
        var tabNumber
        if (index) {
            tabNumber = index + 1;
        }
        else {
            tabNumber = parseInt(tabControl.tabs('option', 'selected')) + 1;
        }
        var tab = $("#ui-tabs-" + tabNumber);
        //console.log("updateBookingDetails");
        thisBooking.BookingDetails.NumAdults = tab.find("#BookingDetails_NoAdults").val();
        thisBooking.BookingDetails.HeardAboutID = tab.find("#BookingDetails_HeardAboutID").val();
        thisBooking.BookingDetails.OtherReason = tab.find("#BookingDetails_OtherHearAbout").val();
        thisBooking.BookingDetails.GuestDetails = tab.find("#BookingDetails_GuestDetails").val();
        thisBooking.BookingDetails.ChildrenDetails = tab.find("#BookingDetails_ChildrenDetails").val();
    }
    this.ValidateCustomerDetails = function () {
        //console.log("ValidateCustomerDetails")
        if (thisBooking.InvokeFormValidation(thisBooking.CustomerDetailsFormID)) {
            thisBooking.ShowError(thisBooking.FormValid);
            thisBooking.EnableNextButton();
        }
        else {
            thisBooking.DisableNextButton();
        }
    }
    this.ValidateBookingDetails = function () {
        if (thisBooking.InvokeFormValidation(thisBooking.BookingDetailsFormID)) {
            thisBooking.EnableNextButton();
        }
        else {
            thisBooking.DisableNextButton();
        }
    }
    this.TabChange = function (ui) {
        thisBooking.UpdateDialogTitle(parseInt(ui.index))
        //If we already have a booking ID then send the data to the db
        //console.log((thisBooking.BookingDetails.BookingID != null) + " last tab=" + thisBooking.LastOpenTabIndex);
        if (thisBooking.BookingDetails.BookingID != null && thisBooking.BookingDetails.StartDate != null && thisBooking.BookingDetails.EndDate != null) {
            if (thisBooking.LastOpenTabIndex == 3) {
                thisBooking.updateCustomerDetails(thisBooking.TabName, 3);
            }
            if (thisBooking.LastOpenTabIndex == 4) {
                thisBooking.updateBookingDetails(thisBooking.TabName, 4);
            }
            thisBooking.updateThisBooking(false);
        };
        //Handles everytime there is a tab change regardles of how it came about
        //console.log("TAB CHANGE" + ui.index);
        var index = parseInt(ui.index);
        var lastTabIndex = index - 1;
        var lastTab = $(thisBooking.TabName);
        //console.log(lastTabIndex);
        //Do any updates we need to do on the last tab (TabChange only enabled for tabs which are not date selectors)
        switch (lastTabIndex) {
            case thisBooking.TabIndexStartDate:
                break;
            case thisBooking.TabIndexEndDate:
                break;
            case thisBooking.TabIndexReturningCust:
                break;
            case thisBooking.TabIndexCustDetails: //Cust Details
                thisBooking.updateCustomerDetails(lastTab, 3);
                break;
            case thisBooking.TabIndexBookingDetails: //Booking Details
                //the updating for this bit need to be done before tab change
                break;
            default:
                //console.log("tab changed default");
        }
        thisBooking.LastOpenTabIndex = ui.index;
        //console.log("hide");
        hideThrobber();
    }
    this.TabChangeLoad = function (ui) {
        //Hadles tab changes when there is a page load
        var index = parseInt(ui.index);
        //Handles tab loads for non date select tabs
        if (thisBooking.CheckTabChangeOk(index)) {
            //thisBooking.UpdateDialogTitle(index)
            switch (index) {
                case thisBooking.TabIndexCustDetails:
                    prog = 30;
                    thisBooking.InvokeFormValidation(thisBooking.CustomerDetailsFormID);

                    $("#" + thisBooking.CustomerDetailsFormID).find("input").change(function () {
                        thisBooking.ValidateCustomerDetails();
                    }).keyup(function () {
                        thisBooking.ValidateCustomerDetails();
                    })
                    $("#" + thisBooking.CustomerDetailsFormID).find("select").change(function () {
                        thisBooking.ValidateCustomerDetails();
                    });
                    break;
                case thisBooking.TabIndexBookingDetails:
                    prog = 30;
                    thisBooking.InvokeFormValidation(thisBooking.BookingDetailsFormID);
                    $("#" + thisBooking.BookingDetailsFormID).find("input").change(function () {
                        thisBooking.ValidateBookingDetails();
                    }).keyup(function () {
                        thisBooking.ValidateBookingDetails();
                    })
                    $("#" + thisBooking.BookingDetailsFormID).find("textarea").change(function () {
                        thisBooking.ValidateBookingDetails();
                    }).keyup(function () {
                        thisBooking.ValidateBookingDetails();
                    })
                    $("#" + thisBooking.BookingDetailsFormID).find("select").change(function () {
                        thisBooking.ValidateBookingDetails();
                    }); ;
                    break;
                default:
                    prog = 0;
            };
        };
    }
    this.UpdateSummary = function (ui) {
        if (thisBooking.CheckTabChangeOk(parseInt(ui.index))) {
            //thisBooking.UpdateDialogTitle(parseInt(ui.index))


            switch (parseInt(ui.index)) {
                case thisBooking.TabIndexStartDate: //Start Date
                    $("#lblCheckOutDate").text("(please select a date)");
                    $(".priceLbl").hide();
                    thisBooking.BookingDetails.EndDate = null;
                    $(".checkOutLbl").show();
                    $("#lblCheckInDate").text(thisBooking.BookingDetails.StartDate);
                    var url = $("#tabs").find(".checkOutSelectURL").attr("data-url");
                    url = url.replace("checkinDS", escape(thisBooking.BookingDetails.StartDate));
                    url = url.replace("startDS", escape(thisBooking.BookingDetails.StartDate));
                    thisBooking.clearCalendarControls();
                    $("#tabs").tabs("url", thisBooking.TabIndexEndDate, url).tabs("select", thisBooking.TabIndexEndDate);
                    break;
                case thisBooking.TabIndexEndDate: //End date
                    $("#lblCheckOutDate").text(thisBooking.BookingDetails.EndDate);
                    //Get price and update summary
                    var url = $("#jsonActionURLs").find(".getPrice").attr("href");
                    var details = {
                        venueID: thisBooking.BookingDetails.VenueID,
                        startDateString: thisBooking.BookingDetails.StartDate,
                        endDateString: thisBooking.BookingDetails.EndDate
                    }
                    showThrobber();
                    $.post(url, details, function (data) {
                        $("#lblTotalPrice").text(data.FormatedPrice);
                        $("#lblNumNights").text(data.NoNights);
                        $("#lblDepositDue").text(data.FormatedAmount);
                        thisBooking.BookingDetails.NoNights = data.NoNights;
                        thisBooking.BookingDetails.TotalPrice = data.Price;
                        thisBooking.BookingDetails.AmountDue = data.AmountDue;
                        hideThrobber();
                        $(".priceLbl").show();
                        //thisBooking.clearCalendarControls();
                        if (isAuthenticated) {
                            $("#tabs").tabs("select", thisBooking.TabIndexCustDetails);
                        }
                        else {
                            $("#tabs").tabs("select", thisBooking.TabIndexReturningCust);
                        };
                    });
                    break;
                case thisBooking.TabIndexReturningCust: //Returning Cust
                    //login?
                    $("#tabs").tabs("select", thisBooking.TabIndexCustDetails);
                    break;
                default:
                    prog = 0;
            };
        };
    }
    this.CheckEmailUnique = function (email) {
        var url = $("#jsonActionURLs").find(".checkEmailUnique").attr("href");
        var details = {
            emailAddr: email
        }
        showThrobber();
        //console.log("check email unique " + url);
        $.post(url, details, function (data) {
            hideThrobber();
            //console.log('check done isUnique=' + (data.toString() == "true"))
            if (data.toString() == "true") {
                thisBooking.EmailCheckDone = true;
                thisBooking.BookingDetails.EmailAddress = email;
                $("#tabs").tabs("select", thisBooking.TabIndexCustDetails);
            }
            else {
                thisBooking.EmailCheckDone = false;
                //select radio box
                $("#chkExist").prop("checked", true);
                enablePasBox();
                thisBooking.ShowError(thisBooking.EmailUniqueError);
            }
            //$("#tabs").tabs("select", thisBooking.TabIndexReturningCust);
        });
    }
    this.LoginUser = function () {
        var email = $('input[id=txtEmail]', '#loginDetails').val();
        var pass = $('input[id=txtPassword]', '#loginDetails').val();
        var url = $("#jsonActionURLs").find(".loginJSON").attr("href");
        var details = {
            emailAddr: email,
            password: pass
        }
        showThrobber();
        //console.log("login url " + url);
        $.post(url, details, function (data) {
            hideThrobber();
            //console.log('login done')
            if (data.toString() == "true") {
                thisBooking.LoginCheckDone = true;
                $("#tabs").tabs("select", thisBooking.TabIndexCustDetails);
            }
            else {
                thisBooking.LoginCheckDone = false;
                thisBooking.ShowError(data.toString());
            }
            //$("#tabs").tabs("select", thisBooking.TabIndexReturningCust);
        });
    }
    this.clearCalendarControls = function () {
        $("#tabs").find(".calenderControl").remove();
    }
    this.UpdateProgress = function (index) {
        var prog = 0;
        switch (index) {
            case thisBooking.TabIndexStartDate:
                thisBooking.DisablePrevButton();
                prog = 0;
                break;
            case thisBooking.TabIndexEndDate:
                thisBooking.EnablePrevButton();
                prog = 20;
                break;
            case thisBooking.TabIndexReturningCust:
                thisBooking.EnablePrevButton();
                prog = 20;
                break;
            case thisBooking.TabIndexCustDetails:
                thisBooking.EnablePrevButton();
                prog = 40;
                break;
            case thisBooking.TabIndexBookingDetails:
                thisBooking.EnablePrevButton();
                prog = 60;
                break;
            case thisBooking.TabIndexBookingSummary:
                thisBooking.EnablePrevButton();
                prog = 80;
                break;
            default:
                prog = 100;
        }
        $("#pbar").progressbar({ value: prog });
    }
    this.UpdateDialogTitle = function (index) {
        var title = '';
        switch (index) {
            case thisBooking.TabIndexStartDate:
                title = "Select Check-in Date";
                break;
            case thisBooking.TabIndexEndDate:
                title = "Select Check-out Date";
                break;
            case thisBooking.TabIndexReturningCust:
                title = "Returning Customer";
                break;
            case thisBooking.TabIndexCustDetails:
                title = "Your Details";
                break;
            case thisBooking.TabIndexCustDetails:
                title = "Booking Details";
                break;
            case thisBooking.TabIndexBookingSummary:
                title = "Confirm Booking";
                break;
            default:
                title = "Retreats Group Ltd";
        }
        $('div.bookingDialg').dialog('option', 'title', title);
    };
    this.ShowError = function (err) {
        //Add error Span if there isnt one
        var errorDiv = $(".ui-dialog-buttonpane .errorContainer");
        if (errorDiv.length == 0) {
            errorDiv = $("<div></div>").addClass("errorContainer").appendTo($(".ui-dialog-buttonpane"))
        }
        errorDiv.text(err).show();
        //alert($("." + this.DialogName).html());
    }
    this.CheckTabChangeOk = function (index) {
        var valid = false;
        switch (index) {
            case thisBooking.TabIndexStartDate:
                valid = true;
                break;
            case thisBooking.TabIndexEndDate:
                if (thisBooking.BookingDetails.StartDate) {
                    valid = true;
                }
                else {
                    thisBooking.ShowError(thisBooking.CheckInError);
                }
                break;
            case thisBooking.TabIndexReturningCust:
                if (thisBooking.ExistingCustLoaded) {
                    var email = $('input[id=txtEmail]', '#loginDetails').val();
                    if (validateEmail(email)) {
                        if ($('input[name=newCustomer]:checked', '#loginDetails').val() == 'true') {
                            //New customer
                            //Check if we have already checked unique email
                            //console.log("chk done?" + thisBooking.EmailCheckDone);
                            if (thisBooking.EmailCheckDone == true) {
                                valid = true;
                            }
                            else {
                                if (thisBooking.EmailCheckDone == false) {
                                    //Failed unique check
                                    thisBooking.EmailCheckDone = null;
                                    valid = false;
                                }
                                else {
                                    //Check the address when complete it will check call this again
                                    thisBooking.CheckEmailUnique(email);
                                    valid = false;
                                }
                            }
                        }
                        else {
                            if (thisBooking.LoginCheckDone == true) {
                                valid = true;
                            }
                            else {
                                if (thisBooking.LoginCheckDone == false) {
                                    //Failed unique check
                                    thisBooking.LoginCheckDone = null;
                                    valid = false;
                                }
                                else {
                                    //Check the pass when complete it will check call this again
                                    //existing cust log them in
                                    if ($("#txtPassword").val() == "") {
                                        thisBooking.ShowError(thisBooking.EnterPassErr);
                                    }
                                    else {
                                        thisBooking.LoginUser();
                                    }
                                    valid = false;
                                }
                            }

                        }
                    }
                    else {
                        thisBooking.ShowError(thisBooking.EmailValid);
                    }
                }
                else {
                    valid = true;
                }
                break;
            case thisBooking.TabIndexCustDetails:
                if (thisBooking.BookingDetails.EndDate && thisBooking.BookingDetails.StartDate) {
                    valid = true;
                }
                else {
                    if (!thisBooking.BookingDetails.StartDate) {
                        thisBooking.ShowError(thisBooking.CheckInError);
                    }
                    else {
                        thisBooking.ShowError(thisBooking.CheckOutError);
                    }
                }
                break;
            case thisBooking.TabIndexBookingDetails:
                if (thisBooking.InvokeFormValidation(thisBooking.CustomerDetailsFormID)) {
                    valid = true;
                }
                else {
                    thisBooking.ShowError(thisBooking.FormValidError);
                }
                break;
            case thisBooking.TabIndexBookingSummary:
                if (thisBooking.InvokeFormValidation(thisBooking.BookingDetailsFormID)) {
                    //if we dont have a booking is stop
                    if (thisBooking.BookingDetails.BookingID == null) {
                        valid = true;
                        var lastTab = $(thisBooking.TabName);
                        thisBooking.updateBookingDetails(lastTab, 4);
                        //We should have everything we need for the booking lets make it official
                        thisBooking.updateThisBooking(true);
                        valid = false;
                    }
                    else {
                        //continue
                        valid = true;
                    }
                }
                else {
                    thisBooking.ShowError(thisBooking.FormValidError);
                }
                break;
            default:
                title = "Retreats Group Ltd";
        }
        if (valid) {
            var errorDiv = $(".ui-dialog-buttonpane .errorContainer");
            errorDiv.hide()
            thisBooking.UpdateProgress(index)
            if (index == thisBooking.TabIndexCustDetails || index == thisBooking.TabIndexBookingDetails) {
                thisBooking.ShowError(thisBooking.FormValidError);
            };
        }
        return valid;
    }
    //Errors
    this.CheckInError = "Please select a Check-in date"
    this.CheckOutError = "Please select a Check-out date"
    this.FormValidError = "Please fill out the required fields (*)"
    this.FormValid = "Please click next when you have finished entering your details"
    this.EmailValid = "You must enter a valid email"
    this.EmailUniqueError = "We already have this email in our system, please enter your password"
    this.PassSent = "Your password has been reset and sent to your email address"
    this.EnterPassErr = "Your must enter a password"
    this.LoginFail = "The user name or password provided is incorrect."
    this.AgreeTerms = "You must agree to the terms and conditions"
}

function bookingDetails(VenueID) {
    this.VenueID = VenueID
    this.BookingID = null
    this.StartDate = null
    this.EndDate = null
    this.NoNights = null
    this.TotalPrice = null
    this.AmountDue = null
    //Cust details
    this.Firstname = null
    this.Lastname = null
    this.Address1 = null
    this.Address2 = null
    this.Town = null
    this.County = null
    this.CountryID = null
    this.Postcode = null
    this.Phonenumber = null
    this.Mobilenumber = null
    this.EmailAddress = null
    this.Subscribe = null
    //Booking details
    this.NumAdults = null
    this.HeardAboutID = null
    this.OtherReason = null
    this.GuestDetails = null
    this.ChildrenDetails = null
}
