﻿var validationControls = new Hashtable();
var globalErrorControl;
var currentCategory;

function ValidationControl(controlId, message, params, category, validationType) {
    this.controlId = controlId;
    this.message = message;
    this.valid = true;
    this.validationMethod = function() { }; //do nothing
    this.validationType = validationType;
    this.oldBorder = null;
    this.oldColor = null;
    this.validationParams = params;
    this.category = category;

    this.registerCallback = function(callback) {
        this.validationMethod = callback;
    }

    this.UpdateProperties = function() {
        if (this.controlId != null) {
            var control = document.getElementById(this.controlId);
            if (control != null) {
                if (!this.valid) {
                    if (this.category != null && this.category != "Info") {
                        this.oldColor = control.style.color;
                        this.oldBorder = control.style.border;
                        MarkInvalidControl(control);

                        if (control.type != "hidden" && control.style.display != "none" && !control.disabled) {
                            try {
                                control.focus();
                            }
                            catch (err) {
                                //do nothing     
                            }
                        }
                    }
                    this.valid = true;
                }
                else {
                    if (this.category != null && this.category != "Info") {
                        if (this.oldColor != null) {
                            control.style.color = this.oldColor;
                        }
                        if (this.oldBorder != null) {
                            control.style.border = this.oldBorder;
                        }

                        if (control.type != "hidden" && control.style.display != "none" && !control.disabled) {
                            try {
                                control.focus();
                            }
                            catch (err) {
                                //do nothing     
                            }
                        }
                    }
                    this.valid = true;
                }
            }
        }
    }

    this.Validate = function(category) {
        if (this.category == category) {
            if (this.validationMethod != null) {
                var control = null;
                if (this.controlId != null) {
                    control = $get(this.controlId);
                }

                if (this.validationParams == null) {
                    this.validationParams = new Array();
                }

                if (!this.validationMethod(this, control, this.validationParams)) {
                    this.valid = false;
                    return this.message;
                }
                else {
                    this.valid = true;
                }
            }
            return "";
        }
        //otherwise skip
        return "";
    }
}

function MarkInvalidControl(control) {
    if (control != null) {
        control.style.color = "red";
        control.style.border = "2px solid red";
    }
}

///<summary>Walk all html INPUT, TEXTAREA and SELECT elements contained by the passed object
///and return the control ids for all controls that match the search criteria.</summary>
///<param name="obj">The control at which to start the search</param>
///<param name="type">The type of controls to search for</param>
///<returns>All control ids located as an array</returns>
function Find(obj, type) {
    var n, aList;
    var returnArray = new Array();

    if (obj == null) {
        return returnArray;
    }

    // get text & checked
    if (type == "radio" || type == "checkbox") {
        aList = obj.getElementsByTagName("INPUT");
        for (n = 0; n < aList.length; n++) {
            if ((aList[n].id != null) && (aList[n].id != "")) {
                if (type == "radio" && aList[n].type == "radio") {
                    Array.add(returnArray, aList[n].id);
                } else if (type == "checkbox" && aList[n].type == "checkbox") {
                    Array.add(returnArray, aList[n].id);
                }
            }
        }
    }
    else if (type == "select") {
        aList = obj.getElementsByTagName("option");
        for (n = 0; n < aList.length; n++) {
            if (aList[n] != null) {
                //returns the actual controls...
                Array.add(returnArray, aList[n]);
            }
        }
    }

    return returnArray;
}

function AddCustomValidationCtrlMessage(category, control, validationMethodName, message, params) {
    var validation = new ValidationControl(control, message, params, category, null);
    validation.registerCallback(GetCustomValidationMethod(validationMethodName));
    validationControls.put(category, validation);
}

function AddCustomValidationMessage(category, validationMethodName, message, params) {
    var validation = new ValidationControl(null, message, params, category, null);
    validation.registerCallback(GetCustomValidationMethod(validationMethodName));
    validationControls.put(category, validation);
}

function AddValidationMessage(category, control, validationType, message, params) {
    var validation = new ValidationControl(control, message, params, category, validationType);
    validation.registerCallback(GetValidationMethod(validationType));
    validationControls.put(category, validation);
}

function AddAction(actionType, controlId, handlerMethod) {
    if (controlId != null) {
        var eventName = GetEventName(actionType);
        var handler = GetCustomActionMethod(handlerMethod);
        var control = $get(controlId);

        if (control != null && eventName != null && handler != null) {
            $addHandler(control, eventName, handler);
        }
    }
}

function GetEventName(actionType) {
    if (actionType == "DDLSelectedIndexChanged") {
        return "change";
    }
    else if (actionType == "RBLSelectedIndexChanged") {
        return "click";
    }
    else if (actionType == "FocusLost") {
        return "blur";
    }
    else {
        return null;
    }
}

function GetCustomActionMethod(methodName) {
    //assume the validationType is a function name
    var func = window[methodName];
    if (func != null) {
        return func;
    }
    else {
        return null;
    }
}

function GetCustomValidationMethod(methodName) {
    //assume the validationType is a function name
    var func = window[methodName];
    if (func != null) {
        return func;
    }
    else {
        return null;
    }
}

function GetValidationMethod(validationType) {
    if (validationType == "IsNumber") {
        return ValidateNumberControl;
    }
    else if (validationType == "DDLSelectionRequired") {
        return ValidateDropDownControl;
    }
    else if (validationType == "TextRequired") {
        return ValidateTextRequired;
    }
    else if (validationType == "TextLengthLimit") {
        return ValidateTextLength;
    }
    else if (validationType == "CBLChecked") {
        return ValidateCBLChecked;
    }
    else if (validationType == "RBLChecked") {
        return ValidateRBLChecked;
    }
    else if (validationType == "WarningMessage") {
        return ValidateAlwaysFalse;
    }
    else if (validationType == "InfoMessage") {
        return ValidateAlwaysFalse;
    }
    else if (validationType == "YesNoMessage") {
        return ValidateAlwaysFalse;
    }
    else {
        return null;
    }
}

//Always invalid. Used to show warning messages where the error has been discovered on the server side.
function ValidateAlwaysFalse(source, control, paramsArray) {
    return false;
}

//Validates that the given textbox control has a text length <= first item in params array.
function ValidateTextLength(source, control, paramsArray) {
    if (control != null && paramsArray[0] != null) {
        var text = control.value;
        return text != null && text.length <= parseInt(paramsArray[0]);
    }
    return false;
}

//Validates that the user has entered text in the given text control
function ValidateTextRequired(source, control, paramsArray) {
    if (control != null) {
        var text = control.value;
        return text != null && text.length > 0;
    }
    return false;
}

//Validates that the user has entered a number in the given text control
function ValidateNumberControl(source, control, paramsArray) {
    if (control != null) {
        return !isNaN(Number.parseInvariant(control.value));
    }
    return false;
}

//Validates that the user has selected a "dynamic" item in the given drop down list
function ValidateDropDownControl(source, control, paramsArray) {
    if (control != null) {
        //if the selected value is a number < 0 then assume this is a static drop down item (such as select an item -->)
        var asNumber = Number.parseInvariant(control.value);
        if (!isNaN(asNumber) && asNumber > 0) {
            return true;
        }
        else if (!isNaN(asNumber) && asNumber < 0) {
            return false;
        }
        else {
            //it might still be a currency or something so just check if the text is empty or not
            return control.value != null && control.value != "";
        }
    }
    return false;
}

//Validates that the user has checked at least one item in the given check box list.
function ValidateCBLChecked(source, control, paramsArray) {
    //find all radio buttons within the given list control
    var radioButtons = Find(control, "checkbox");
    var elem = null;
    for (var i = 0; i < radioButtons.length; i++) {
        elem = document.getElementById(radioButtons[i]);
        if (elem != null && elem.checked) {
            return true;
        }
    }
    return false;
}

//Validates that the user has checked at least one item in the given radio button list.
function ValidateRBLChecked(source, control, paramsArray) {
    //find all radio buttons within the given list control
    var radioButtons = Find(control, "radio");
    var elem = null;
    for (var i = 0; i < radioButtons.length; i++) {
        elem = document.getElementById(radioButtons[i]);
        if (elem != null && elem.checked) {
            return true;
        }
    }
    return false;
}

//Called by controls when a confirm message needs to be displayed to the user
function ConfirmAction(id) {
    var showMsg = false;
    var toValidate = validationControls.get(id);
    if (toValidate != null) {
        var message = "<br /><ul>";
        var temp;
        var control;
        for (var i = 0; i < toValidate.length; i++) {
            temp = toValidate[i].Validate(id);
            if (!toValidate[i].valid) {
                message += "<li>" + temp;
                if (toValidate[i].controlId != null) {
                    control = document.getElementById(toValidate[i].controlId);
                    if (control != null) {
                        control.title = temp;
                    }
                }
            }
            showMsg |= !toValidate[i].valid;
        }
        message += "</ul>"
    }
    if (showMsg) {
        return ShowConfirmMessage("Bekräfta", message, toValidate);
    }
    else {
        return true;
    }
}

//Called by controls when validation should be performed
function Validate(category) {
    currentCategory = category;
    var showMsg = false;
    var toValidate = validationControls.get(category);
    if (toValidate != null) {
        var message = "<br /><ul>";
        var temp;
        var control;
        for (var i = 0; i < toValidate.length; i++) {
            temp = toValidate[i].Validate(category);
            if (!toValidate[i].valid) {
                message += "<li>" + temp;
                if (toValidate[i].controlId != null) {
                    control = document.getElementById(toValidate[i].controlId);
                    if (control != null) {
                        control.title = temp;
                    }
                }
            }
            showMsg |= !toValidate[i].valid;
        }
        message += "</ul>"
    }
    if (showMsg) {
        if (currentCategory == "Warnings") {
            return ShowErrorMessage("Varning", message, toValidate, true);
        }
        else if (currentCategory == "Info") {
            return ShowErrorMessage("Information", message, toValidate, false);
        }
        else if (currentCategory.toString().indexOf("_") > 0) {
            return ShowConfirmMessage("Bekräfta", message, toValidate);
        }
        else {
            return ShowErrorMessage("Du måste uppdatera följande fält flr att spara:", message, toValidate, true);
        }
    }
    else {
        return true;
    }
}

function ShowErrorMessage(headerMessage, bodyMessage, toValidate, error) {
    var container = $get("wrapper");
    var header = $get("errorHeader");
    var body = $get("errorBody");
    var errorFooter = $get("errorFooter");
    var confirmFooter = $get("confirmFooter");
    var image = $get("imgWarn");

    errorFooter.style.display = "block";
    confirmFooter.style.display = "none";

    container.style.display = "block";

    var closeHandler = toValidate == null ? null : toValidate[0].validationParams[0];

    if (globalErrorControl != null) {
        var globalCtrl = $find(globalErrorControl);
        if (globalCtrl != null) {
            $clearHandlers(globalCtrl._onOk);

            if (closeHandler == null || closeHandler == "") {
                globalCtrl._onOk = function(ev) {
                    ev.preventDefault();
                    ev.stopPropagation();
                    CloseErrorMessage(false);
                    return false;
                }
            }
            else {
                globalCtrl._onCancel = GetCustomActionMethod(closeHandler);
            }
            $addHandler($get("ctl00_closeButton"), "click", Function.createDelegate(globalCtrl, globalCtrl._onCancel));
        }
    }

    if (error) {
        body.style.color = "red";
        if (image != null) {
            image.src = "~/Resources/Warning.gif";
        }
    }
    else {
        body.style.color = "black";
        if (image != null) {
            image.src = "~/Resources/Info.png";
        }
    }

    header.innerHTML = headerMessage;
    body.innerHTML = bodyMessage;

    if (globalErrorControl != null) {
        var globalCtrl = $find(globalErrorControl);
        if (globalCtrl != null) {
            globalCtrl.show();
            return false;
        }
    }
    return true;
}

function ShowConfirmMessage(headerMessage, bodyMessage, toValidate) {
    var container = $get("wrapper");
    var header = $get("errorHeader");
    var body = $get("errorBody");
    var errorFooter = $get("errorFooter");
    var confirmFooter = $get("confirmFooter");
    var image = $get("imgWarn");

    body.style.color = "black";

    if (image != null) {
        image.src = "~/Resources/Confirm.png";
    }

    //ok handler
    var okHandler = toValidate[0].validationParams[0];
    //cancelHandler
    var cancelHandler = null;
    if (toValidate[0].validationParams.length > 1) {
        cancelHandler = toValidate[0].validationParams[1];
    }

    if (globalErrorControl != null) {
        var globalCtrl = $find(globalErrorControl);
        if (globalCtrl != null) {
            $clearHandlers(globalCtrl._onOk);
            $clearHandlers(globalCtrl._onCancel);

            if (okHandler == "") {
                globalCtrl._onOk = function(ev) {
                    ev.preventDefault();
                    ev.stopPropagation();
                    CloseErrorMessage(false);
                    window.location = $get(toValidate[0].controlId).href;
                    return false;
                }
            }
            else {
                if (cancelHandler == null) {
                    //we are using a callback reference
                    globalCtrl._onOk = function(ev) {
                        ev.preventDefault();
                        ev.stopPropagation();
                        CloseErrorMessage(false);
                        eval(okHandler);
                        return false;
                    };
                }
                else {
                    globalCtrl._onOk = GetCustomActionMethod(okHandler);
                }
            }
            $addHandler($get("ctl00_okButton"), "click", Function.createDelegate(globalCtrl, globalCtrl._onOk));

            if (cancelHandler == null || cancelHandler == "") {
                globalCtrl._onCancel = function(ev) {
                    ev.preventDefault();
                    ev.stopPropagation();
                    CloseErrorMessage(false);
                    return false;
                }
            }
            else {
                globalCtrl._onCancel = GetCustomActionMethod(cancelHandler);
            }
            $addHandler($get("ctl00_cancelButton"), "click", Function.createDelegate(globalCtrl, globalCtrl._onCancel));

        }
    }

    errorFooter.style.display = "none";
    confirmFooter.style.display = "block";

    container.style.display = "block";

    header.innerHTML = headerMessage;
    body.innerHTML = bodyMessage;

    if (globalErrorControl != null) {
        var globalCtrl = $find(globalErrorControl);
        if (globalCtrl != null) {
            globalCtrl.show();
            return false;
        }
    }
    return false;
}

function CloseErrorMessage(update) {
    if (globalErrorControl != null) {
        var globalCtrl = $find(globalErrorControl);
        if (globalCtrl != null) {
            globalCtrl.hide();
            if (update) {
                if (validationControls != null && currentCategory != null) {
                    var valueArr = validationControls.get(currentCategory);
                    for (var i = 0; i < valueArr.length; i++) {
                        if (valueArr[i] != null) {
                            valueArr[i].UpdateProperties();    
                        }
                    }
                }
            }
        }
    }
}

//Find the parent control of control
function findParent(control) {
    if (control == null || control.id == null) {
        return null;
    }
    var controlId = control.id;
    var parentId = controlId.substring(controlId, controlId.lastIndexOf('_'))
    return document.getElementById(parentId);
}

// finds the control with id = id and which parent control is control
function findControl(id, control) {
    if (control != null) {
        return document.getElementById(control.id + "_" + id);
    }
    else {
        return document.getElementById(id);
    }
}

//selects the given index if the radio button list
function SelectRadioButton(rbl, index) {
    var radioButtons = Find(rbl, "radio");
    if (index >= 0 && index < radioButtons.length) {
        document.getElementById(radioButtons[index]).checked = true;
    }
}

//Gets the selected index of a radio button list
function GetSelectedIndex(rbl, index) {
    var radioButtons = Find(rbl, "radio");
    for (var i = 0; i < radioButtons.length; i++) {
        if (document.getElementById(radioButtons[i]).checked) {
            return i;
        }
    }
    return -1;
}

function EnableRBL(rbl, enable) {
    rbl.disabled = !enable;
    var radioButtons = Find(rbl, "radio");
    for (var i = 0; i < radioButtons.length; i++) {
        document.getElementById(radioButtons[i]).disabled = !enable;
    }
}

//Used by Confirm messages using client callbacks
function ValidationActionCompleted(returnValue) {
    if (returnValue != null && returnValue.toString().length > 0) {
        ShowErrorMessage("Operationen misslyckades", returnValue, null, true);
    }
    else {
        window.location.reload();
    }
}

//HASHTABLE IMPLEMENTATION
/**
Created by: Michael Synovic
on: 01/12/2003
    
This is a Javascript implementation of the Java Hashtable object.
    
Contructor(s):
Hashtable()
Creates a new, empty hashtable
    
Method(s):
void clear() 
Clears this hashtable so that it contains no keys. 
boolean containsKey(String key) 
Tests if the specified object is a key in this hashtable. 
boolean containsValue(Object value) 
Returns true if this Hashtable maps one or more keys to this value. 
Object get(String key) 
Returns the value to which the specified key is mapped in this hashtable. 
boolean isEmpty() 
Tests if this hashtable maps no keys to values. 
Array keys() 
Returns an array of the keys in this hashtable. 
void put(String key, Object value) 
Maps the specified key to the specified value in this hashtable. A NullPointerException is thrown is the key or value is null.
Object remove(String key) 
Removes the key (and its corresponding value) from this hashtable. Returns the value of the key that was removed
int size() 
Returns the number of keys in this hashtable. 
String toString() 
Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ", " (comma and space). 
Array values() 
Returns a array view of the values contained in this Hashtable. 
            
*/
function Hashtable() {
    this.clear = hashtable_clear;
    this.containsKey = hashtable_containsKey;
    this.containsValue = hashtable_containsValue;
    this.get = hashtable_get;
    this.isEmpty = hashtable_isEmpty;
    this.keys = hashtable_keys;
    this.put = hashtable_put;
    this.remove = hashtable_remove;
    this.size = hashtable_size;
    this.toString = hashtable_toString;
    this.values = hashtable_values;
    this.hashtable = new Array();
}

/*=======Private methods for internal use only========*/

function hashtable_clear() {
    this.hashtable = new Array();
}

function hashtable_containsKey(key) {
    var exists = false;
    for (var i in this.hashtable) {
        if (i == key && this.hashtable[i] != null) {
            exists = true;
            break;
        }
    }
    return exists;
}

function hashtable_containsValue(value) {
    var contains = false;
    if (value != null) {
        for (var i in this.hashtable) {
            if (this.hashtable[i] == value) {
                contains = true;
                break;
            }
        }
    }
    return contains;
}

function hashtable_get(key) {
    return this.hashtable[key];
}

function hashtable_isEmpty() {
    return (parseInt(this.size()) == 0) ? true : false;
}

function hashtable_keys() {
    var keys = new Array();
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            keys.push(i);
    }
    return keys;
}

function hashtable_put(key, value) {
    if (key == null || value == null) {
        throw "NullPointerException {" + key + "},{" + value + "}";
    } else {
        var arr = null;
        if (this.hashtable[key] != null) {
            arr = this.hashtable[key];
            if (!Array.contains(arr, value)) {
                var contains = false;
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i].message == value.message) {
                        contains = true;
                    }
                }
                if (!contains) {
                    Array.add(arr, value);
                }
            }
        }
        else {
            arr = new Array();
            Array.add(arr, value);
            this.hashtable[key] = arr;
        }
    }
}

function hashtable_remove(key) {
    var rtn = this.hashtable[key];
    this.hashtable[key] = null;
    return rtn;
}

function hashtable_size() {
    var size = 0;
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            size++;
    }
    return size;
}

function hashtable_toString() {
    var result = "";
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            result += "{" + i + "},{" + this.hashtable[i] + "}\n";
    }
    return result;
}

function hashtable_values() {
    var values = new Array();
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            values.push(this.hashtable[i]);
    }
    return values;
}

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); 

