﻿var SignupManager = {
    AvailableCredit: 0,
    FirstPlanSelected: true,
    OsBitSupport: null,
    SelectedPlan: '',
    SelectedOs: null,
    SelectedBitType: undefined,
    SelectedInterfaces: 0,
    AdditionalInterfacesReason: '',
    SelectedBackups: { daily: 0, weekly: 0, monthly: 0 },
    SelectedUpgrades: { memory: 0, storage: 0, data: 0 },
    RequestQueue: jqmq({ delay: -1, batch: 1, callback: function(item) {
        var params = item.getParams();
        params.onException = function(context, e) { SignupManager.RequestQueue.next(); throw e; }
        if (item.htmlId) {
            new Ajax.Updater(item.htmlId, item.url, params);
        } else {
            new Ajax.Request(item.url, params);
        }
    }
    }),

    Initialize: function(options) {
        Object.extend(this, options);
        this.SpecifiedPlan = this.SelectedPlan;

        this.Defaults = {
            Os: this.SelectedOs,
            BitType: this.SelectedBitType
        };

        this.SelectDefaults();
    },

    SelectDefaults: function() {
        if (this.Defaults.Os !== undefined && this.Defaults.BitType !== undefined) {
            this.SelectOs(this.Defaults.Os, this.Defaults.BitType);
        } else {
            // Default to linux
            this.OsTypeClicked("Linux");
        }
    },

    OsTypeClicked: function(type) {
        $("OperatingSystems" + type).selectedIndex = 1;
        this.OsSelected(type, $("OperatingSystems" + type).value);
    },

    OsSelected: function(type, osName, bits) {
        this.SelectOsType(type);
        this.SelectedOs = osName;
        $("OperatingSystemName").value = osName;

        var first = true;

        $$(".OperatingSystemBitsType").each(function(bitType) {
            var found = SignupManager.OsBitSupport[osName].indexOf(bitType.value) > -1;
            var selectedBits = bits || (found ? bitType.value : null);

            bitType[found ? "enable" : "disable"]();

            if (first && bitType.value == selectedBits) {
                first = false;
                bitType.checked = true;
                SignupManager.BitTypeSelected(bitType.value);
            }
        });
    },

    SelectOs: function(name, bits) {
        $$("#OperatingSystemsWindows, #OperatingSystemsLinux").each(function(list) {
            $A(list.options).each(function(item) {
                if (item.value == name) {
                    var type = list.getAttribute("type");

                    list.selectedIndex = item.index;
                    SignupManager.OsSelected(type, item.value, bits);
                }
            });
        });
    },

    SelectOsType: function(type) {
        $$("input[id=OperatingSystemType][value='" + type + "']").first().checked = true;
        $("OperatingSystems" + (type == "Windows" ? "Linux" : "Windows")).selectedIndex = 0;
    },

    BitTypeSelected: function(bits) {
        this.SelectedBits = bits;
        this.LoadPlans();
    },

    SelectPlan: function(planId) {
        this.SelectedPlan = planId;
        opt = $$("input[id=VPSDetailsDTO_PlanId][value='" + planId + "']").first();
        opt.checked = true;

        $$(".PlanList tr").each(function(row) {
            row.removeClassName("highlight");
        });

        var row = opt.up(2);
        row.addClassName("highlight");

        this.PopulateExtrasOptions(planId);
        this.PopulateBackupOptions(planId);
        this.PopulateInterfaceOptions(planId);
        this.UpdateTotal();
        this.GetCostForUpgrades(planId);
    },

    BackupOptionSelected: function(selectBox) {
        var type = $(selectBox).getAttribute('type');
        var value = $(selectBox).value;

        this.SelectedBackups[type] = value;
        this.UpdateTotal();
    },

    InterfaceOptionSelected: function(selectBox) {
        var type = $(selectBox).getAttribute('type');
        var value = $(selectBox).value;

        this.SelectedInterfaces = value;

        this.UpdateTotal();
    },

    InterfaceReasonSelected: function(value) {
        this.AdditionalInterfacesReason = value;
    },

    UpgradesOptionSelected: function(selectBox) {
        var type = $(selectBox).getAttribute('type');
        var value = $(selectBox).value;
        this.SelectedUpgrades[type] = value;

        this.GetCostForUpgrades(this.SelectedPlan);

        this.UpdateTotal();
    },

    Wait: function(milliseconds) {
        var date = new Date();
        var curDate = null;

        do { curDate = new Date(); }
        while (curDate - date < milliseconds);
    },

    PopulateBackupOptions: function(planId) {
        var _this = this;
        var ajaxspec = { url: '/Signup/GetBackupOptions', getParams: function() {
            return {
                method: 'post', parameters: {
                    planId: planId
                },
                onComplete: function(response) {
                    var response = response.responseText.evalJSON();

                    $$(".BackupSelection").each(function(item) {
                        var type = item.getAttribute("type");

                        SignupManager.PopulateDropDown(item, response[type], SignupManager.SelectedBackups[type]);
                    });
                    _this.RequestQueue.next();
                }
            };
        }
        };
        this.RequestQueue.add(ajaxspec);
    },

    PopulateInterfaceOptions: function(planId) {
        var _this = this;
        var ajaxspec = { url: '/Signup/GetInterfaceOptions', getParams: function() {
            return {
                method: 'post', parameters: {
                    planId: planId
                },
                onComplete: function(response) {
                    var items = response.responseText.evalJSON();

                    var selectBox = $$(".AdditionalInterfaces").first();

                    SignupManager.PopulateDropDown(selectBox, items, SignupManager.SelectedInterfaces);
                    SignupManager.ToggleIpAddressTerms();
                    _this.RequestQueue.next();
                }
            };
        }
        };
        this.RequestQueue.add(ajaxspec);
    },

    PopulateAdditionalUpgrades: function(planId) {

        $$("div[name=upgrade]").each(function(div) {
            div.innerHTML = "";
        });

        $$("div[name=plan]").each(function(div) {
            div.style.display = "";
        });

        var additionalMemory = $("VPSDetailsDTO_AdditionalMemory")
        var additionalStorage = $("VPSDetailsDTO_AdditionalStorage");
        var additionalDataTransfer = $("VPSDetailsDTO_AdditionalDataTransfer");

        var planMemory = $(planId + "_Memory");
        var planAdditionalMemory = $(planId + "_AdditionalMemory");

        var planStorage = $(planId + "_Storage");
        var planAdditionalStorage = $(planId + "_AdditionalStorage");

        var planDataTransfer = $(planId + "_DataTransfer");
        var planAdditionalDataTransfer = $(planId + "_AdditionalDataTransfer");

        var planCostPerMonth = document.getElementById(planId + "_CostPerMonth");
        var planAdditionalCostPerMonth = document.getElementById(planId + "_AdditionalCostPerMonth");

        planAdditionalMemory.appendChild(additionalMemory);
        planMemory.style.display = "none";

        planAdditionalStorage.appendChild(additionalStorage);
        planStorage.style.display = "none";

        planAdditionalDataTransfer.appendChild(additionalDataTransfer);
        planDataTransfer.style.display = "none";


        planAdditionalCostPerMonth.innerHTML = planCostPerMonth.innerHTML;
        planCostPerMonth.style.display = "none";
    },

    GetCostForUpgrades: function(planId) {
        var _this = this;
        var ajaxspecs = { url: '/Signup/CalculateCostOfUpgrades', getParams: function() {
            return {
                method: 'post', parameters: {
                    planId: planId,
                    additionalMemory: _this.SelectedUpgrades['memory'],
                    additionalStorage: _this.SelectedUpgrades['storage'],
                    additionalDataTransfer: _this.SelectedUpgrades['data']
                },
                onComplete: function(response) {

                    var item = response.responseText;
                    var costElement = document.getElementById(planId + "_AdditionalCostPerMonth");
                    costElement.innerHTML = item;
                    _this.RequestQueue.next();
                }
            };
        }
        };
        this.RequestQueue.add(ajaxspecs);
    },

    ToggleIpAddressTerms: function() {
        var show = parseInt(this.SelectedInterfaces) > 0;

        var region = $("AdditionIpTerms");

        region.style.display = show ? "" : "none";

        if (!show) {
            this.AdditionalInterfacesReason = '';

            $("VPSDetailsDTO_AdditionalInterfacesOther").value = '';
        }

        $$(".AdditionalInterfacesReason").each(function(item) {
            item.checked = item.value == SignupManager.AdditionalInterfacesReason;
        });
    },

    PopulateExtrasOptions: function(planId) {
        var _this = this;

        var ajaxspec = { url: '/Signup/GetExtrasOptions', getParams: function() {
            return {
                method: 'post',
                parameters: {
                    planId: planId,
                    guestId: this.GuestId
                },
                onComplete: function(response) {
                    var items = response.responseText.evalJSON();

                    ["memory", "storage", "data"].each(function(type) {
                        var value = "";

                        var selectBox = $$(".UpgradeSelection[type='" + type + "']").first();
                        selectBox.update();

                        $A(items[type]).each(function(item) {
                            var opt = document.createElement('option');
                            opt.text = item.Value;
                            opt.value = item.Key;

                            if (item.Key == value)
                                opt.setAttribute("selected", "true");

                            if (item.Value == "SelectedValue")
                                value = item.Key;
                            else
                                selectBox.options.add(opt);

                            if (opt.value == -1) { opt.disabled = true; }
                        });
                        var found = false;
                        $A(selectBox.options).each(function(option) {
                            if (option.value == _this.SelectedUpgrades[type] && _this.FirstPlanSelected) {
                                selectBox.selectedIndex = option.index;
                                found = true;
                            }
                        });

                        if (!found) {
                            _this.SelectedUpgrades[type] = selectBox.options[0].value;
                            selectBox.selectedIndex = 0;
                        }
                    });
                    _this.FirstPlanSelected = false;
                    _this.PopulateAdditionalUpgrades(planId);
                    _this.RequestQueue.next();
                }
            };
        }
        };
        this.RequestQueue.add(ajaxspec);
    },

    PopulateDropDown: function(selectBox, items, selectedValue) {
        selectBox.update();

        $A(items).each(function(item) {
            var opt = document.createElement('option');
            opt.text = item.Value;
            opt.value = item.Key;
            selectBox.options.add(opt);
        });

        $A(selectBox.options).each(function(option) {
            if (option.value == selectedValue) {
                selectBox.selectedIndex = option.index;
            }
        });
    },

    UpdateTotal: function() {
        if (SignupManager.SelectedPlan == '') {
            return;
        }

        var _this = this;

        var ajaxspec = { url: '/signup/calculatetotal', getParams: function() {
            return {
                method: 'post',
                parameters: {
                    osName: SignupManager.SelectedOs,
                    osBitType: SignupManager.SelectedBits,
                    planId: SignupManager.SelectedPlan,
                    additionalInterfaces: SignupManager.SelectedInterfaces,
                    dailyBackups: SignupManager.SelectedBackups.daily,
                    weeklyBackups: SignupManager.SelectedBackups.weekly,
                    monthlyBackups: SignupManager.SelectedBackups.monthly,
                    additionalMemory: SignupManager.SelectedUpgrades.memory,
                    additionalStorage: SignupManager.SelectedUpgrades.storage,
                    additionalDataTransfer: SignupManager.SelectedUpgrades.data
                },
                onComplete: function(response) {
                    var total = response.responseText;

                    SignupManager.SetTotalText(total);
                    _this.RequestQueue.next();
                }
            };
        }
        };
        this.RequestQueue.add(ajaxspec);
    },

    SetTotalText: function(total) {
        $$(".TotalCostValue").each(function(item) {
            item.innerHTML = total;
        });

        var due = parseFloat(total.substring(1)) - this.AvailableCredit;

        $$(".TotalDueValue").each(function(item) {
            item.innerHTML = "$" + (due > 0 ? (Math.round(due * 100) / 100).toFixed(2) : 0.00);
        });
    },

    LoadPlans: function() {
        new Ajax.Updater('PlansList', '/Plans/GetPlans', {
            method: 'post', parameters: {
                osName: SignupManager.SelectedOs,
                osBitType: SignupManager.SelectedBits,
                specifiedPlan: SignupManager.SpecifiedPlan,
                guestId: SignupManager.GuestId
            },
            onComplete: function() {
                var opt = $$("input[id=VPSDetailsDTO_PlanId][safename='" + SignupManager.SpecifiedPlan + "']").first();
                if (typeof opt != "undefined") {
                    SignupManager.SelectedPlan = opt.value;
                }

                if (SignupManager.SelectedPlan != '') {
                    var opt = $$("input[id=VPSDetailsDTO_PlanId][value='" + SignupManager.SelectedPlan + "']").first();
                    if (typeof opt != "undefined") {
                        SignupManager.SelectPlan(SignupManager.SelectedPlan);
                    } else {
                        var opt = $$("input[id=VPSDetailsDTO_PlanId]").first();
                        if (typeof opt != "undefined") {
                            SignupManager.SelectPlan(opt.value);
                        }
                    }
                } else {
                    var opt = $$("input[id=VPSDetailsDTO_PlanId]").first();
                    if (typeof opt != "undefined") {
                        SignupManager.SelectPlan(opt.value);
                    }
                }
            }
        });
    },

    DisplayPhoneVerificationFields: function(displayFields, displayPinError, phoneNumber) {
        // Clear any error messages since if we get here there shouldn't be any other validation errors
        if (displayFields) {
            ShowErrorMessage('');
        }

        $("FraudEvaluationPinRequired").value = displayFields;
        $("PhoneVerificationDiv").style.display = displayFields ? "block" : "none";

        if ($("PhoneVerificationPhoneNumber").value == "") {
            $("PhoneVerificationPhoneNumber").value = phoneNumber;
        }

        $("PhoneVerificationPinError").style.display = displayPinError ? "block" : "none";
        if (displayPinError) {
            $("PhoneVerificationPinError").innerHTML = "Invalid PIN";
        }
    },

    ProcessSignupForm: function(form) {

        var serializedForm = Form.serialize(form);

        SetFormBusy(form, true);

        var myAjax = new Ajax.Request('/SignUp/ValidateForm', {
            parameters: serializedForm,

            onFailure: function(req) {
                ShowErrorMessage("Unknown error: " + req.responseText, 'Failure');
                SetFormBusy(form, false);
            },

            onSuccess: function(req) {
                SetFormBusy(form, false);

                var response = req.responseText.evalJSON();

                if (response.ResponseType == "FRAUDEVALUATION" || response.ResponseType == "INCORRECTPIN") {
                    switch (response.FraudAdvice) {
                        case "flag":
                            SignupManager.DisplayPhoneVerificationFields(true, response.ResponseType == "INCORRECTPIN", response.PhoneNumber);
                            break;
                        case "allow":
                            SignupManager.DisplayPhoneVerificationFields(false, false, "");
                            return ProcessForm(form);
                        case "block":
                            SignupManager.BlockSignup(form);
                            break;
                    }
                }
                else {
                    SignupManager.DisplayPhoneVerificationFields(false, false, "");
                    return ProcessForm(form);
                }
            }
        });

        return false;
    },

    BlockSignup: function(form) {
        this.DisplayPhoneVerificationFields(false, false, "");
        $("BlockedSignupDiv").style.display = "block";
        form.disable();
    },

    SetupPhoneVerification: function() {
        if (!$("FraudEvaluationPinRequired").value) {
            return;
        }

        $("PhoneVerificationPinError").style.display = "none";
        $("PhoneVerificationPhoneError").style.display = "none";
        var form = $("customersignupform");
        var serializedForm = Form.serialize(form);

        var attempts = parseInt($("PhoneCallAttempts").value);
        if (attempts >= 3) {
            $("PhoneVerificationPhoneError").style.display = "block";
            $("PhoneVerificationPhoneError").innerHTML = "We cannot process this order";
            form.disable();
            return;
        }

        $("BusyCalling").style.display = "block";
        form.disable();

        new Ajax.Request('/SignUp/SetupPhoneVerification', {
            method: 'post',
            parameters: serializedForm + "&phoneNumber=" + $("PhoneVerificationPhoneNumber").value,
            onSuccess: function(req) {
                var response = req.responseText.evalJSON();
                $("BusyCalling").style.display = "none";
                form.enable();

                switch (response.Status) {
                    case "SUCCESS":
                        $("HashedFraudEvaluationPin").value = response.HashedPin;
                        $("PhoneCallAttempts").value = parseInt($("PhoneCallAttempts").value) + 1;
                        break;
                    case "INVALIDNUMBER":
                        $("PhoneVerificationPhoneError").style.display = "block";
                        $("PhoneVerificationPhoneError").innerHTML = "The code cannot be sent to this phone number";
                        break;
                    case "FAILURE":
                        $("PhoneVerificationPhoneError").style.display = "block";
                        $("PhoneVerificationPhoneError").innerHTML = "Error sending code, please check your number and try again";
                        break;
                    case "INSUFFICIENTFUNDS":
                        $("HashedFraudEvaluationPin").value = response.HashedPin;
                        SignupManager.ProcessSignupForm(form);
                        break;
                }
            },
            onFailure: function(req) {
                $("BusyCalling").style.display = "none";
                form.enable();
                ShowErrorMessage("Unknown error: " + req.responseText, 'Failure');
            }
        });
    },

    CleanupUpgrades: function() {
        document.getElementById("AdditionalUgrades").innerHTML = "";
        return true;
    }
};