﻿
//
// General prototypes
//
function AddressPrototype() {
    var addressPrototype = {
        inputId: "",
        hiddenfieldId: "",
        hiddenFieldIsUpdateRequiredId: "",
        syncWithServerButtonId: "",
        watcher: null
    };

    addressPrototype.GetControl = function () {
        return GetControl(this.inputId);
    };

    addressPrototype.GetText = function () {
        return GetControlValue(this.inputId);
    };

    addressPrototype.SetText = function (value) {
        SetControlValue(this.inputId, value);
    };

    addressPrototype.GetHiddenField = function () {
        return GetControlValue(this.hiddenfieldId);
    };

    addressPrototype.SetHiddenField = function (value) {
        SetControlValue(this.hiddenfieldId, value);
    };

    addressPrototype.IsValueChanged = function () {
        if(this.watcher)
            return this.watcher.IsValueChanged();
        else
            return true;
    };

    addressPrototype.IsUpdateRequired = function() {
        return GetControlValue(this.hiddenFieldIsUpdateRequiredId) == "True";
    };

    addressPrototype.ResetUpdateRequiredFlag = function () {
        SetControlValue(this.hiddenFieldIsUpdateRequiredId, "False");
    };

    addressPrototype.SyncWithServer = function () {
        var btn = GetControl(this.syncWithServerButtonId);
        if(btn)
            btn.click();
    };

    addressPrototype.ValueGetter = function () {
        return addressPrototype.GetText();
    };

    addressPrototype.OnValueChangedHandler = function (prevValue, currentValue) {
        Trace("Address::OnValueChangedHandler");
        currentValue = currentValue == null ? "" : currentValue;
        var val = GMap_AdjustedAirportCode(currentValue);
        addressPrototype.SetText(val);
        addressPrototype.SetHiddenField(val);
        addressPrototype.watcher.SaveValue();

        addressPrototype.SyncWithServer();
    };
    
    addressPrototype.Initialize = function (inputId, hiddenFieldId, hiddenFieldIsUpdateRequiredId, validatorId, syncWithServerButtonId) {
        this.inputId = inputId;
        this.hiddenfieldId = hiddenFieldId;
        this.hiddenFieldIsUpdateRequiredId = hiddenFieldIsUpdateRequiredId;
        this.syncWithServerButtonId = syncWithServerButtonId;

        this.watcher = new InputWatcherPrototype(this.inputId, "");
        this.watcher.Initialize(addressPrototype.ValueGetter, addressPrototype.OnValueChangedHandler);
    };

    addressPrototype.Activate = function () {
        this.watcher.Activate();
    };

    addressPrototype.StopWatchers = function() {
        if (addressPrototype.watcher) {
            addressPrototype.watcher.StopMonitoring();
            addressPrototype.watcher.StopValueChangedTimer();
        }
    };

    addressPrototype.UpdateValidatedAddress = function () {
        if (addressPrototype.GetHiddenField()) {
            if (addressPrototype.IsUpdateRequired()) {
                var addressesText = addressPrototype.GetHiddenField();
                var addresses = addressesText.split("::");

                if (addresses.length != 2)
                    return;

                var formattedAddress = addresses[0];
                var unformattedAddress = addresses[1];

                if (!AreAddressesEqual(addressPrototype.GetText(), formattedAddress) &&
                    AreAddressesEqual(addressPrototype.GetText(), unformattedAddress)) {
                    addressPrototype.SetText(formattedAddress);
                }
                addressPrototype.watcher.SaveValue();
                addressPrototype.ResetUpdateRequiredFlag();
            }
            addressPrototype.SetHiddenField("");
        }
    };

    return addressPrototype;
}

function InitAddressPrototype() {
    var prototype = {
        hiddenField: "",
        syncWithServerButtonId: ""
    };

    prototype.SetText = function (value) {
        return SetControlValue(this.hiddenField, value);
    };
    prototype.SyncWithServer = function() {
        var btn = GetControl(this.syncWithServerButtonId);
        if(btn) btn.click();
    };

    prototype.Initialize = function(hiddenFieldId, syncWithServerButtonId) {
        this.hiddenField = hiddenFieldId;
        this.syncWithServerButtonId = syncWithServerButtonId;        
    };

    return prototype;
}

function PostedFormPrototype(path) {
    var prototype = {
        path: path,
        params: [],
        method: "POST"
    };

    prototype.GetPath = function () {
        return this.path;
    };
    prototype.SetPath = function (path) {
        this.path = path;
    };

    prototype.GetMethod = function () {
        return this.method;
    };
    prototype.SetMethod = function(method) {
        this.method = method;
    };

    prototype.GetParams = function () {
        return this.params;
    };
    prototype.SetParams = function (params) {
        this.params = params;
    };

    prototype.Submit = function () {
        var form = document.createElement("form");
        form.setAttribute("method", this.method);
        form.setAttribute("action", this.path);

        for (var key in this.params) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", this.params[key]);

            form.appendChild(hiddenField);
        }

        document.body.appendChild(form);
        form.submit();
    };

    return prototype;
}

function InputWatcherPrototype(controlId, value) {
    // Private constants
    {
        var CHECK_CHANGES_INTERVAL = 500;
        var BEFORE_CLICK_TIMEOUT = 1500;
        var DEFAULT_VALUE = value;
    }

    // Prototype
    {
        var watcher = {
            id: CreateUUID(),
            controlId: controlId,
            previousValue: DEFAULT_VALUE,
            timers: {
                valueChangedTimer: null,
                checkValueTimer: null,
                isValueChangedTimerActive: false,
                isCheckValueTimerActive: true
            },
            events: {
                GetValue: function() { return null; },
                OnValueChanged: function(previouseValue, currentValue) {  }
            }
        };
    }

    // Public members
    {
        watcher.GetControl = function () {
            return GetControl(this.controlId);
        };

        watcher.GetValue = function() {
            return this.events.GetValue
                ? this.events.GetValue()
                : DEFAULT_VALUE;
        };

        watcher.IsValueChanged = function () {
            var currentValue = this.GetValue();
            var result = !(this.previousValue == currentValue);

            Trace("InputWatcherPrototype::IsValueChanged : " + this.previousValue + " : " + currentValue + " = " + result);

            return result;
        };

        watcher.IsCheckValueTimerActive = function() {
            return this.timers.isCheckValueTimerActive;
        };

        watcher.IsValueChangedTimerActive = function() {
            return this.timers.isValueChangedTimerActive;
        };
    }

    // Private methods
    {
        watcher.OnValueChanged = function () {
            if (this.events.OnValueChanged) {
                Trace("OnValueChanged::this.events.OnValueChanged != null");

                var previous = this.previousValue;
                this.SaveValue();
                this.events.OnValueChanged(previous, this.GetValue());
            }
        };

        watcher.ClearPreviousValue = function() {
            Trace("ClearPreviousValue");
            watcher.previousValue = "";
        };

        watcher.SaveValue = function () {
            this.previousValue = this.GetValue();

            Trace("SaveValue: '" + this.previousValue + "' value saved.");
        };

        watcher.StartCheckValueTimer = function () {
            Trace("Starting CheckValue timer...");

            this.StopCheckValueTimer();
            this.timers.isCheckValueTimerActive = true;

            this.timers.checkValueTimer = setInterval(function () {
                if (watcher.IsValueChanged()) {// && !watcher.IsValueChangedTimerActive()) {
                    Trace("Value is changed and ValuChanged timer is not active. ValueChanged timer is going to start.");
                    watcher.SaveValue();
                    watcher.StartValueChangedTimer();
                }
            }, CHECK_CHANGES_INTERVAL);

            Trace("CheckValue timer started.");
        };
        watcher.StopCheckValueTimer = function () {
            Trace("Stoping CheckValue timer...");

            clearInterval(this.timers.checkValueTimer);
            this.timers.checkValueTimer = null;
            this.timers.isCheckValueTimerActive = false;

            Trace("CheckValue timer stoped");
        };

        watcher.StartValueChangedTimer = function () {
            Trace("Starting ValueChanged timer...");

            this.StopValueChangedTimer();
            this.timers.isValueChangedTimerActive = true;

            this.timers.valueChangedTimer = setTimeout(function () {
                Trace("...value changed");
                watcher.OnValueChanged();
                watcher.timers.isValueChangedTimerActive = false;
            }, BEFORE_CLICK_TIMEOUT);

            Trace("ValueChanged timer started.");
        };
        watcher.StopValueChangedTimer = function () {
            Trace("Stoping ValueChanged timer...");

            clearTimeout(this.timers.valueChangedTimer);
            this.timers.valueChangedTimer = null;
            this.timers.isValueChangedTimerActive = false;

            Trace("ValueChanged timer stoped.");
        };

        watcher.StartMonitoring = function () {
            Trace("Starting monitoring...");

            this.StopMonitoring();
            this.StartCheckValueTimer();
            Trace("Monitoring started.");
        };
        watcher.StopMonitoring = function () {
            Trace("Stop monitoring...");

            this.StopCheckValueTimer();

            Trace("Monitring stoped.");
        };
    }

    // Public methods
    {
        watcher.Initialize = function(valueGetter, onValueChangedHandler) {
            Trace("InputWatcherPrototype::Initialize");

            this.events.GetValue = valueGetter;
            this.events.OnValueChanged = onValueChangedHandler;
        };

        watcher.Activate = function (isNotValueChangedOnFocus) {
            Trace("InputWatcherPrototype::Activate");

            var control = this.GetControl();
            if (control) {
                AddFocusEventHandler(control, function () {
                    Trace("InputWatcherPrototype::OnFocus(" + isNotValueChangedOnFocus + ")");
                    if (isNotValueChangedOnFocus == null || isNotValueChangedOnFocus != true)
                        watcher.StartValueChangedTimer();
                    watcher.StartMonitoring();
                });
                AddBlurEventHandler(control, function () {
                    Trace("InputWatcherPrototype::OnBlur");
                    watcher.StopMonitoring();
                    if (watcher.IsValueChanged())
                        watcher.OnValueChanged();
                });
            }
        };
    }

    return watcher;
}

//
// ScriptManager helpers
//
function AddPageRequestHandler(endRequest, beginRequest) {
    RemovePageRequestHandler(endRequest, beginRequest);
    if (endRequest)
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
    if (beginRequest)
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
}

function RemovePageRequestHandler(endRequest, beginRequest) {
    if (endRequest)
        Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(endRequest);
    if (beginRequest)
        Sys.WebForms.PageRequestManager.getInstance().remove_beginRequest(beginRequest);
}

function AddPageInitializeRequestHandler(handler) {
    RemovePageInitializeRequestHandler(handler);
    if(handler)
        Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(handler);
}
function RemovePageInitializeRequestHandler(handler) {
    if(handler)
        Sys.WebForms.PageRequestManager.getInstance().remove_initializeRequest(handler);
}

//
// Helper methods
//
function SetCookie(key, value, expirationDays) {
    var expirationDate = new Date();
    expirationDate.setDate(expirationDate.getDate() + expirationDays);
    var cookieValue = escape(value) + ((expirationDays == null) ? "" : "; expires=" + expirationDate.toUTCString());
    document.cookie = key + "=" + cookieValue;
}

function GetTimeZoneOffset() {
    var currentDate = new Date();
    var gmtOffset = -currentDate.getTimezoneOffset();
    return gmtOffset;
}

function Confirm(e, msg) {
    e = e || window.event;

    msg = msg && msg != '' ? msg : "Are you sure?";
    
    var res = confirm(msg);
    if (!res) {
        if (e.preventDefault)
            e.preventDefault();
    }
    e.returnValue = res;
    return res;
}

function IsExists(id) {
    return GetControl(id) ? true : false;
}

function IsVisible(id) {
    return GetControl(id) && GetControl(id).style.display != 'none';
}

function ShowControl(id) {
    if (GetControl(id))
        GetControl(id).style.display = 'block';
}
function HideControl(id) {
    if (GetControl(id))
        GetControl(id).style.display = 'none';
}

function SetControlInvisible(id) {
    var control = GetControl(id);
    if (control != null) {
        control.style.visibility = 'hidden';
    }
}

function EnableControl(id) {
    var control = GetControl(id);
    if (control) {
        control.disabled = false;
        if (control.attributes["activeimageurl"] && control.attributes["src"]) {
            control.attributes["src"].value = control.attributes["activeimageurl"].value;
        }
    }
}
function DisableControl(id) {
    var control = GetControl(id);
    if (control) {
        control.disabled = true;
        if (control.attributes["inactiveimageurl"] && control.attributes["src"]) {
            control.attributes["src"].value = control.attributes["inactiveimageurl"].value;
        }
    }
}

function SelectCheckbox(id, isSelected) {
    var control = GetControl(id);
    if(control) {
        control.checked = isSelected;
    }
}
function IsCheckboxSelected(id) {
    var control = GetControl(id);
    return control.checked;
}

function GetControl(id) {
    return id
        ? document.getElementById(id)
        : null;
}
function GetControlId(obj) {
    return obj == null ? "" : obj.id;
}

function GetControlValue(id) {
    var control = GetControl(id);
    return control == null ? null : control.value;
}
function SetControlValue(id, value) {
    var control = GetControl(id);
    if (control) {
        if (control.value != value) {
            control.value = value;
        }
        return true;
    }
    else {
        return false;
    }
}

function GetControlInnerHtml(id) {
    var control = GetControl(id);
    return (control == null || control.innerHTML == null) ? null : control.innerHTML.trim();
}

function SetControlInnerHtml(id, innerHtml) {
    var control = GetControl(id);
    if (control) {
        if (control.innerHTML != innerHtml) {
            control.innerHTML = innerHtml;
        }
        return true;
    }
    else {
        return false;
    }
}

function CreateUUID() {
    var s = [];
    var hexDigits = "0123456789ABCDEF";
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[12] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01

    var uuid = s.join("");
    return uuid;
}

function Trace(info) {
//    console.info(info);
}

function HtmlEncode(text) {
    if(text) {
        text = text.replace(/</g, "&lt;");
        text = text.replace(/>/g, "&gt;");
        text = text.replace(/"/g, "&quot;");
    }
    return text;
}

function HtmlDecode(text) {
    if (text) {
        text = text.replace(/&lt;/g, "<");
        text = text.replace(/&gt;/g, ">");
        text = text.replace(/&quot;/g, '"');
    }
    return text;
}
    
function Trim(text) {
    return text.replace(/(^\s+)|(\s+$)/g, "");
}

function BlockEnterKey(e) {
    e = e || window.event;
    if (e.keyCode == 13) {
        if (e.preventDefault)
            e.preventDefault();
        e.returnValue = false;
        return false;
    }
    e.returnValue = true;
    return true;
}

function ClickButton(buttonId) {
    var buttonToClick = GetControl(buttonId);
    if (buttonToClick != null) {
        buttonToClick.click();
    }
}

function ClearChildren(controlId) {
    var control = GetControl(controlId);
    if (control != null) {
        var childrenCount = control.childNodes.length;
        for (var i = childrenCount - 1; i >= 0; i--) {
            control.removeChild(control.childNodes[i]);
        }
    }
}

function GetWindowWidth() {
    var width =
		        document.documentElement && document.documentElement.clientWidth ||
		        document.body && document.body.clientWidth ||
		        document.body && document.body.parentNode && document.body.parentNode.clientWidth ||
		        0;
    return width;
}

function GetWindowHeight() {
    var height =
		        document.documentElement && document.documentElement.clientHeight ||
		        document.body && document.body.clientHeight ||
  		        document.body && document.body.parentNode && document.body.parentNode.clientHeight ||
  		        0;
    return height;
}

function ShowModalDialog(modalId, modalBackgroundId, modalContainerId) {
    ShowControl(modalContainerId);
    ShowControl(modalId);
    ShowControl(modalBackgroundId);
    //document.body.style.overflowY = "hidden";

    ModalDialogResize(modalId);

    if (window.attachEvent)
        window.attachEvent('onresize', function () { ModalDialogResize(modalId); });
    else if (window.addEventListener)
        window.addEventListener('resize', function () { ModalDialogResize(modalId); }, false);
    else
        window.onresize = ModalDialogResize(modalId);
}
function HideModalDialog(modalId, modalBackgroundId, modalContainerId) {
    HideControl(modalContainerId);
    HideControl(modalId);
    HideControl(modalBackgroundId);
    document.body.style.overflowY = "auto";

    if (window.detachEvent)
        window.detachEvent('onresize', function () { ModalDialogResize(modalId); });
    else if (window.removeEventListener)
        window.removeEventListener('resize', function () { ModalDialogResize(modalId); }, false);
    else
        window.onresize = null;
}
function ModalDialogResize(modalId) {
    var left = window.XMLHttpRequest == null ? document.documentElement.scrollLeft : 0;
    var top = window.XMLHttpRequest == null ? document.documentElement.scrollTop : 0;

    var div = GetControl(modalId);

    div.style.left = Math.max((left + (GetWindowWidth() - div.offsetWidth) / 2), 0) + 'px';
    div.style.top = 50 + 'px';//Math.max((top + (GetWindowHeight() - div.offsetHeight) / 2), 0) + 'px';
}

function AddClickEventHandler(control, handler) {
    if (control && handler) {
        var oldHnl = (control.onclick) ? control.onclick : function () { };
        control.onclick = function () { oldHnl(); handler(); };
    }
}
function AddFocusEventHandler(control, handler) {
    if (control && handler) {
        var oldHnl = (control.onfocus) ? control.onfocus : function () { };
        control.onfocus = function () { oldHnl(); handler(); };
    }
}
function AddBlurEventHandler(control, handler) {
    if (control && handler) {
        var oldHnl = (control.onblur) ? control.onblur : function () { };
        control.onblur = function () { oldHnl(); handler(); };
    }
}
function AddChangeEventHandler(control, handler) {
    if (control && handler) {
        var oldHnl = (control.onchange) ? control.onchange : function () { };
        control.onchange = function () { oldHnl(); handler(); };
    }
}

function GetLettersAndDigits(text) {
    if (text == null || text == "")
        return "";

    var regex = /[a-zA-Z0-9]+?/g;
    var matches = text.match(regex);
    return matches.join("");
}

function AreAddressesEqual(address1, address2) {
    return GetLettersAndDigits(address1) == GetLettersAndDigits(address2);
}

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); 

