﻿
function WebHailControl(mainContainerId) {
    // Private constants
    {
        var FIRST_NAME = "FirstName";
        var LAST_NAME = "LastName";
        var PHONE_NUM = "PhoneNumber";
        var EMAIL = "Email";
        var SEND_SMS = "SendSms";
    }

    // Prototype
    {
        var control = {
            id: CreateUUID(),
            controlContainerId: mainContainerId,
            pickupAddress: new AddressPrototype(),
            destinationAddress: new AddressPrototype(),
            isInitialized: false,
            dataReferences: {
                firstNameId: "",
                lastNameId: "",
                phoneId: "",
                emailId: "",
                sendSmsId: "",
                syncWithServerContactInfoId: "",
                backgroundEstimate: {
                    pickupPointId: "",
                    destinationPointId: "",
                    jsonRouteLegsId: "",
                    synchWithServerBackgroundEstimateId: ""
                }
            },
            watchers: {
                firstNameWatcher: null,
                lastNameWatcher: null,
                phoneWatcher: null,
                emailWatcher: null,
                sendSmsWatcher: null
            },
            initAddress: new InitAddressPrototype(),
            initAddressQueue: [],
            expectedInitAddrCount: 0
        };
    }

    // Public members
    {
        control.IsInitialized = function () {
            return this.isInitialized;
        };

        control.IsVisible = function () {
            return IsExists(this.controlContainerId);
        };
    }

    // Private methods
    {
        control.GetValue = function (fieldName) {
            switch (fieldName) {
                case FIRST_NAME:
                    return GetControlValue(control.dataReferences.firstNameId);
                case LAST_NAME:
                    return GetControlValue(control.dataReferences.lastNameId);
                case PHONE_NUM:
                    return GetControlValue(control.dataReferences.phoneId);
                case EMAIL:
                    return GetControlValue(control.dataReferences.emailId);
                case SEND_SMS:
                    return GetControlValue(control.dataReferences.sendSmsId);
                default:
                    return "";
            };
        };

        control.SyncWithServerContactInfo = function () {
            var btn = GetControl(this.dataReferences.syncWithServerContactInfoId);
            if (btn)
                btn.click();
        };

        control.UpdateValidatedPickupAddress = function () {
            if (this.IsInitialized())
                this.pickupAddress.UpdateValidatedAddress();
        };
        control.UpdateValidatedDestinationAddress = function () {
            if (this.IsInitialized())
                this.destinationAddress.UpdateValidatedAddress();
        };

        control.OnValueChangedHandler = function (prevValue, currentValue) {
            control.SyncWithServerContactInfo();
        };
    }

    // Public methods
    {
        control.Initialize = function () {
            Trace("WebHail.Initialization(" + control.id + ")");

            if (!this.IsInitialized() && this.IsVisible()) {
                AddPageInitializeRequestHandler(IntializeRequestHandler);

                this.watchers.firstNameWatcher = new InputWatcherPrototype(this.dataReferences.firstNameId, "");
                this.watchers.lastNameWatcher = new InputWatcherPrototype(this.dataReferences.lastNameId, "");
                this.watchers.phoneWatcher = new InputWatcherPrototype(this.dataReferences.phoneId, "");
                this.watchers.emailWatcher = new InputWatcherPrototype(this.dataReferences.emailId, "");
                this.watchers.sendSmsWatcher = new InputWatcherPrototype(this.dataReferences.sendSmsId, true);

                this.watchers.firstNameWatcher.Initialize(function () { return control.GetValue(FIRST_NAME) }, control.OnValueChangedHandler);
                this.watchers.lastNameWatcher.Initialize(function () { return control.GetValue(LAST_NAME) }, control.OnValueChangedHandler);
                this.watchers.phoneWatcher.Initialize(function () { return control.GetValue(PHONE_NUM) }, control.OnValueChangedHandler);
                this.watchers.emailWatcher.Initialize(function () { return control.GetValue(EMAIL) }, control.OnValueChangedHandler);
                this.watchers.sendSmsWatcher.Initialize(function () { return control.GetValue(SEND_SMS) }, control.OnValueChangedHandler);

                this.isInitialized = true;

                this.ContactInfoTextBoxesActivate();
                this.AddressTextBoxesActivate();
            }
        };

        control.ContactInfoTextBoxesActivate = function () {
            if (this.IsInitialized()) {
                this.watchers.firstNameWatcher.Activate();
                this.watchers.lastNameWatcher.Activate();
                this.watchers.phoneWatcher.Activate();
                this.watchers.emailWatcher.Activate();
                this.watchers.sendSmsWatcher.Activate();
            }
        };

        control.AddressTextBoxesActivate = function () {
            if (this.IsInitialized()) {
                this.pickupAddress.Activate();
                this.destinationAddress.Activate();
            }
        };

        control.StopWatchers = function () {
            if (this.watchers.firstNameWatcher) this.watchers.firstNameWatcher.StopMonitoring();
            if (this.watchers.lastNameWatcher) this.watchers.lastNameWatcher.StopMonitoring();
            if (this.watchers.phoneWatcher) this.watchers.phoneWatcher.StopMonitoring();
            if (this.watchers.emailWatcher) this.watchers.emailWatcher.StopMonitoring();
            if (this.watchers.sendSmsWatcher) this.watchers.sendSmsWatcher.StopMonitoring();

            if (control.pickupAddress) control.pickupAddress.StopWatchers();
            if (control.destinationAddress) control.destinationAddress.StopWatchers();
        };

        control.CheckAndPostInitAddresses = function (serializedAddress) {
            this.initAddressQueue.push(serializedAddress);

            if (this.initAddressQueue && this.initAddressQueue.length == this.expectedInitAddrCount) {
                var data = HtmlEncode(JSON.stringify(this.initAddressQueue));
                control.PostAddressOnServer(data);
            }
        };

        control.InitAddressCoordinates = function () {
            this.expectedInitAddrCount = 0;
            this.initAddressQueue = [];

            var pickupAddress = this.pickupAddress.GetText();
            var destAddress = this.destinationAddress.GetText();

            if (pickupAddress && pickupAddress != "")
                this.expectedInitAddrCount++;
            if (destAddress && destAddress != "")
                this.expectedInitAddrCount++;

            FindAddressByText(pickupAddress, function (serializedAddress) {
                control.CheckAndPostInitAddresses("pickup::" + serializedAddress);
            });

            FindAddressByText(destAddress, function (serializedAddress) {
                control.CheckAndPostInitAddresses("destination::" + serializedAddress);
            });
        };

        control.PostAddressOnServer = function (data) {
            this.initAddress.SetText(data);
            this.initAddress.SyncWithServer();
        };

        control.ProceedBackgroundEstimate = function () {
            var pickupPoint = GMap_ParseLatLng(GetControlValue(this.dataReferences.backgroundEstimate.pickupPointId));
            var destPoint = GMap_ParseLatLng(GetControlValue(this.dataReferences.backgroundEstimate.destinationPointId));
            GMap_BuildRouting(null, pickupPoint, destPoint,
                function (directionResult) {
                    var legs = [];
                    if (directionResult) {
                        var route = directionResult.routes[0];
                        if (route && route.legs) {
                            legs = GMap_FillRouteLegsLatLng(route.legs);
                        }
                    }
                    SetControlValue(control.dataReferences.backgroundEstimate.jsonRouteLegsId, HtmlEncode(JSON.stringify(legs)));
                    ClickButton(control.dataReferences.backgroundEstimate.synchWithServerBackgroundEstimateId);
                },
                function (status) {
                    SetControlValue(control.dataReferences.backgroundEstimate.jsonRouteLegsId, HtmlEncode(JSON.stringify([])));
                    ClickButton(control.dataReferences.backgroundEstimate.synchWithServerBackgroundEstimateId);
                });
        };
    }

    return control;
}

function IntializeRequestHandler(sender, args) {
    CheckTextInputs();
    args._request._body = args._request._body.replace(/%3E|%3C/g, '');
}
function CheckTextInputs() {
    var list = document.getElementsByTagName('input');
    if (list != null) {
        for (var idx in list) {
            var input = list[idx];
            if (input != null && input.type == 'text') {
                RemoveForbiddenChars(input);
            }
        }
    }
}
function RemoveForbiddenChars(txtInput) {
    var pattern = /^[\s\t]+|[\s\t]+$|[<>]/g;
    
    var oldInputValue = txtInput.value;
    var newInputValue = oldInputValue.replace(pattern, '');
    
    if (oldInputValue != newInputValue) {
        txtInput.value = newInputValue;
    }
}

function FindAddressByText(addressText, onSuccess) {
    if (addressText && Trim(addressText) != "" && onSuccess) {
        GMap_FindAddress(new GMap(), addressText, null, ["street_address", "subpremise", "airport"],
            function (results) { ProcessFoundAddresses(results, onSuccess) }, null);
    }
}
function ProcessFoundAddresses(results, onProcessed) {
    if (results && results.length == 1 && onProcessed) {
        var result = results[0];
        result.geometry.location = GMap_LatLngMapping(result.geometry.location);

        Trace("ProcessFoundAddresses::result = " + result);
        onProcessed(GMap_SemicolonSerializationAddress(result));
    }
}

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

