﻿function LoadCascadingDropdown(rootPath, target, functionPointer, param) {
    var urlString;
    var art;
    var hovedTema;
    var underTema;
    var formTarget = DetermineFormAction(target);

    if (!rootPath || rootPath === "") {
        art = formTarget[0];
        hovedTema = formTarget[1];
        underTema = formTarget[2];
    }
    else {
        art = formTarget[1];
        hovedTema = formTarget[2];
        underTema = formTarget[3];
    }

    urlString = rootPath + "/SearchCriteria/" + functionPointer;
    if (!param || param === "" || param === "ALL" || param === "NONE") {
        param = undefined;
    }
    urlString += "/" + param;
    urlString += "/" + art;
    urlString += "/" + hovedTema;
    urlString += "/" + underTema;
    $.ajax({
        type: "POST",
        url: urlString,
        beforeSend: function () {
            target.attr("disabled", "disabled");
        },
        success: function (data) {
            target.removeAttr("disabled");
            // Evaluate the JSON
            data = eval(data);
            // Clear all options from sub category select 
            target.children().remove();
            // Fill sub category select
            $.each(data, function (index, option) {
                var selected = option.Selected ? " selected =\"selected\"" : "";
                var row = "<option value=\"" + option.Value + "\"" + selected + ">" + option.Text + "</option>";
                $(row).appendTo(target);
            });
            // Cascading load, so trigger a change in the target, so that it can continue the load-chain
            target.trigger("change");
        },
        error: function () {
            target.removeAttr("disabled");
        }
    });
}

// This function looks for a parent form node, looks up its 
// action returns it as an array the first four parts of the 
// path
function DetermineFormAction(element) {
    var currentElement;
    var action;
    var splitterRegexp = /^\/([^\/]+)\/([^\/]+)\/([^\/]+).*$/;
    var splitAction;
    if (element.length !== 1) {
        return undefined;
    }
    currentElement = element;
    while (currentElement.length > 0) {
        currentElement = currentElement.parent();
        if (currentElement.is('form')) {
            action = currentElement.attr('action');
            splitAction = splitterRegexp.exec(action);
            if (splitAction.length == 4) {
                return [splitAction[1], splitAction[2], splitAction[3], undefined];
            }
            else if (splitAction.length == 5) {
                return [splitAction[1], splitAction[2], splitAction[3], splitAction[4]];
            }
            
        }
    }
    return undefined;
}

function CheckDisabled(disabledRules) {
    var currentValue;
    var currentDisableRule;
    for (var i in disabledRules) {
        if (disabledRules[i].control) {
            currentValue = disabledRules[i].control.val();
            currentDisableRule = disabledRules[i].rule;
            if (currentDisableRule && currentDisableRule === currentValue) {
                return true; // Some control in the rule list has the registered value.
            }
        }
    }
    return false; // None of the controls in the rule list have the registered value.
}

function EnableDisableControl(control, disabledRules) {
    if (CheckDisabled(disabledRules) === true) {
        control.attr("disabled", "disabled");
    }
    else {
        control.removeAttr("disabled");
    }
}

function RegisterControlDependencies(control, disabledRules) {
    // If the target control is not defined, do nothing.
    if (!control) {
        return;
    }
    // Go through the list of rules. Each rule shall contain a control and a 
    // value. For each control in the list, set a handler for the change event.
    // This handler checks the value of all controls in the rule set, and if any
    // have the value defined in the rule, that means the control defined in the 
    // control parameter (not the rule) shall be disabled.
    for (var i in disabledRules) {
        if (disabledRules[i].control) {
            disabledRules[i].control.change(function () {
                EnableDisableControl(control, disabledRules);
            });
        }
    }
    // In order to initialize correctly, trigger a change event for each 
    // rule-component.
    for (var j in disabledRules) {
        if (disabledRules[i].control) {
            disabledRules[i].control.trigger("change");
        }
    }
}

function StyleRequiredDropDown(dropdown)
{
    if (dropdown.val() === "NONE") {
        dropdown.addClass("requiredSelection");
    }
    else {
        dropdown.removeClass("requiredSelection");
    }
}

function SetDropDownTooltip(dropdown) {
    dropdown.removeAttr("title");
    dropdown.attr("title", dropdown.children(":selected").text());
}

function InitializeCascadingDropdowns(rootPath, fylkeDropdown, kommuneDropdown, valdDropdown, jaktfeltDropdown) {
    // Start by attaching the load function to the change event for all relevant dropdowns
    if (fylkeDropdown && fylkeDropdown.length > 0) {
        SetDropDownTooltip(fylkeDropdown);
        fylkeDropdown.change(function () {
            StyleRequiredDropDown($(this));
            SetDropDownTooltip($(this));
        });
        if (kommuneDropdown && kommuneDropdown.length > 0) {
            fylkeDropdown.change(function () {
                LoadCascadingDropdown(rootPath, kommuneDropdown, "GetKommuneDropdownIFylke", $(this).val());
            });
        }
        StyleRequiredDropDown(fylkeDropdown);
    }
    if (kommuneDropdown && kommuneDropdown.length > 0) {
        SetDropDownTooltip(kommuneDropdown);
        kommuneDropdown.change(function () {
            StyleRequiredDropDown($(this));
            SetDropDownTooltip($(this));
        });
        if (valdDropdown && valdDropdown.length > 0) {
            kommuneDropdown.change(function () {
                LoadCascadingDropdown(rootPath, valdDropdown, "GetValdDropdownIKommune", $(this).val());
            });
        }
        StyleRequiredDropDown(kommuneDropdown);
    }
    if (valdDropdown && valdDropdown.length > 0) {
        SetDropDownTooltip(valdDropdown);
        valdDropdown.change(function () {
            StyleRequiredDropDown($(this));
            SetDropDownTooltip($(this));
        });
        if (jaktfeltDropdown && jaktfeltDropdown.length > 0) {
            valdDropdown.change(function () {
                LoadCascadingDropdown(rootPath, jaktfeltDropdown, "GetJaktfeltDropdownIVald", $(this).val());
            });
        }
        StyleRequiredDropDown(valdDropdown);
    }

    if (jaktfeltDropdown && jaktfeltDropdown.length > 0) {
        SetDropDownTooltip(jaktfeltDropdown);
        jaktfeltDropdown.change(function () {
            StyleRequiredDropDown($(this));
            SetDropDownTooltip($(this));
        });
        StyleRequiredDropDown(jaktfeltDropdown);
    }
}

/* Gjør komponenten med id targetID synlig dersom usynlig,
usynlig dersom synlig. */
function toggleComponentVisibility(eventArgs, targetId) {
    var obj = document.getElementById(targetId);
    $(obj).slideToggle(100);
}



/* Tar inn en liste med komponenter spesifisert som '#id'. Det første elementet
i lista er det som brukes som resultatfelt, der summen av de andre elementene
i lista lagres.
*/
function SummerTekstfelt(eventargs, data) {
    var i = 0;
    var sum = 0;
    var resultatfelt = $(data[0]);
    for (i = 1; i < data.length; i++) {
        var o = $(data[i]);
        var v = parseInt((o != null && o.val() != '') ? o.val() : '0', 10);
        if (v != null)
            sum += v;
    }
    resultatfelt.val(sum);
}

function PerformFieldSum(sourceFields, sumfield) {
    var i = 0;
    var object = null;
    var value = 0;
    var sum = 0;
    for (i = 0; i < sourceFields.length; i++) {
        object = $("#" + sourceFields[i]);
        var len = object.length;
        var val = object.val();
        if (object !== null && object.length === 1 && object.val() != "") {
            value = parseInt(object.val(), 10);
            if (value == null || isNaN(value) === true) {
                sum = "Ugyldig tall";
                break;
            }
            else {
                sum += value;
            }
        }
    }
    $("#" + sumfield).val(sum);
    //$("#" + sumfield).html(sum);
}

function SetSumField(sourceFields, sumField) {
    var i = 0;
    var object = null;
    for (i = 0; i < sourceFields.length; i++) {
        object = $("#" + sourceFields[i]);
        object.change(function() {
            PerformFieldSum(sourceFields, sumField);
        });
    }
}

/* If value of control is "0", make  target invisible, if different from "0", make it visible */
function ShowWhenValueIsZeroString(control, target) {
    if ($("#" + control).val() !== "0") {
        $("#" + target).show();
    }
    else {
        $("#" + target).hide();
    }
}

/* Takes selected items from list and inserts them into selection after checking if they are already present. */
function MultiselectableAdd(list, selection) {
    $("#" + list + " :selected").each(function () {
        if ($("#" + selection + " option[value=" + this.value + "]").length === 0) {
            $("#" + selection).append("<option value=\"" + this.value + "\" selected=\"selected\">" + this.text + "</option>");
        }
    });
}

/* Removes selected elemens from selection. */
function MultiselectableRemove(selection) {
    $("#" + selection + " :selected").each(function () {
        $("#" + selection + " option[value=" + this.value + "]").remove();
    });
}

/* Removes all elements from selection. */
function MultiselectableRemoveAll(selection) {
    $("#" + selection + " option").remove();
}

function LoadCascadingMultiselectDropdown(rootPath, target, functionPointer, param, seLåste, seAktive) {
    var urlString;
    var formAction;
    var art;
    if (!param || param === "") {
        // Clear all options from sub category select and trigger the cascade to continue.
        $("select#" + target + " option").remove();
        $("#" + target).trigger("change");
    }
    else {
        formAction = DetermineFormAction($("#" + target));
        if (!rootPath || rootPath === "") {
            art = formAction[0];
        }
        else {
            art = formAction[1];
        }

        urlString = rootPath + "/SearchCriteria/" + functionPointer;
        urlString += "/" + param;
        urlString += "/" + art;
        urlString += "/" + seLåste;
        urlString += "/" + seAktive;

        $.ajax({
            url: urlString,
            cache: true,
            dataType: "json",
            type: "POST",
//            beforeSend: function () {
//                alert("Sending request: " + urlString);
//            },
            success: function (data) {
                // Clear all options from sub category select 
                $("select#" + target + " option").remove();

                // Fill sub category select
                $.each(data, function (i, j) {
                    var selected = j.Selected ? " selected =\"selected\"" : "";
                    var row = "<option value=\"" + j.Value + "\"" + selected + ">" + j.Text + "</option>";
                    $(row).appendTo("select#" + target);
                });

                // Trigger cascading update
                $("#" + target).trigger("change");
            }//,
//            error: function () {
//                alert("Error, response: " + arguments[0].status + " " + arguments[0].statusText + ".\n\nURL: " + urlString);
//            }
        });
    }
}

function IsIllegalDate(illegalDates, date) {
    if (!illegalDates || illegalDates.length != 12) {
        return false;
    }
    var illegalInMonth = illegalDates[date.getMonth()];
    if (illegalInMonth) {
        for (var i = 0; i < illegalInMonth.length; i++) {
            if (illegalInMonth[i] === date.getDate()) {
                return true;
            }
        }
    }
    return false;
}

function AssignDatePicker(dateField, illegalDates, jaktår) {
    var nesteJaktår = jaktår + 1;
    var mindate = "01.04." + jaktår;
    var maxdate = "31.03." + nesteJaktår;
    if (dateField.length > 0) {
        dateField.datepicker({
            dateFormat: "dd.mm.yy",
            prevText: "Forrige",
            nextText: "Neste",
            firstDay: "1",
            monthNames: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"],
            dayNamesShort: ["Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"],
            dayNamesMin: ["Sø", "Ma", "Ti", "On", "To", "Fr", "Lø"],
            minDate: mindate,
            maxDate: maxdate,
            buttonImageOnly: true,
            beforeShowDay: function (date) {
                if (IsIllegalDate(illegalDates, date) === true) {
                    return [true, "unavailable", "Registrering for denne dagen finnes fra før"];
                }
                return [true, "", ""];
            }
        });
    }
}

