
// AJAX error event handler
function EndRequestHandler(sender, args) {
    if (args.get_error() != undefined) {
        var errorMessage;        
        if (args.get_response().get_statusCode() == '200') {
            errorMessage = args.get_error().message.replace('Sys.WebForms.PageRequestManagerServerErrorException: ', "");
        }
        else {
            errorMessage = 'Der opstod en ukendt fejl.';
        }
        args.set_errorHandled(true);
        alert(errorMessage);
    }
}



function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}


/*
Opens a new browser window and place it in the middle of the screen.
@param url the location to display in the new window.
*/
function virkOpenWindowInternal(url) {
    var properties = "directories=0,left=" + ((screen.width - 500) / 2) + ",top=" + ((screen.height - 500) / 2) + ",location=0,toolbar=0,scrollbars=yes,menubar=no,width=500,height=500,resizable=no";
    var virkPopupInternal = openPopup(url, "virkPopupInternal", properties);
    virkPopupInternal.focus();
}

/*
Opens a new window or reuse an existing one with the specified name.
@param URL the location to display in the new window.
@param windowName the name of the window, if a window already exist with this name its location will be changed.
@param properties a string containing a list of motifiers to apply to the new window.
*/
function openPopup(URL, windowName, properties) {
    if (!properties) {
        properties = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes";
    }
    if (URL && URL.length > 0) {
        var winref = window.open(URL, windowName, properties);
        winref.focus();
        return winref;
    }
}

/* Disable all client side validating before post-back */
function DisableAllValidators() {
    if (self.Page_Validators) {
        for (i = 0; i < Page_Validators.length; i++) {
            ValidatorEnable(Page_Validators[i], false);
        }
    }
}


// Method to reimplement the possibility to press a key in a dropdown box with grouped items
// and letting the first item with starting the pressed char to be selected.
// Example HTML:
// <select onkeydown="return MarkOption('* ', this, event);">
// 	<option value="">Alabama</option>
// 	<option value="Auburn">* Auburn</option>
// 	<option value="Birmingham">* Birmingham</option>
// 	<option value="Clanton">* Clanton</option>
// 	<option value="Daphne">* Daphne</option>
// </select>
// 	<option value="">Louisiana</option>
// 	<option value="Abbeville">* Abbeville</option>
// 	<option value="Bossier City">* Bossier City</option>
// 	<option value="Columbia">* Columbia</option>
// 	<option value="Denham Springs">* Denham Springs</option>
// </select>
// Notice the "return " before the MarkOption method in the event handler in order to cancel
// processing the events when an item was found. Otherwise the browser will re-select an item
// in the list starting with the key pressed (skipping those starting with padText).
// The method must be registered in the on "onkeydown" event. If you use e.g. "onkeypressed"
// the ASP.NET DefaultButton="SearchButton" statement will cause the method to fail.
// Parameters:
// - padText   - the string used to indent the sub items in each group in the list.
// - theSelect - the select box the event happened in.
// - e         - the event (the user pressed a key).
function MarkOption(padText, theSelect, e) {
    // Prepare variable to hold the pressed char.
    var charPressed = "";

    // Get the ASCII code from the event.
    if (window.event) {
        var keynum = e.keyCode;
    }
    else if (e.which) {
        keynum = e.which;
    }

    if (keynum == 9) return true;

    // Convert ASCII to char.
    var keychar = String.fromCharCode(keynum);

    // Test if the char was alphanumeric (en-us).	
    var regex = /^[0-9A-Za-z]+$/;
    if (regex.test(keychar)) {
        charPressed = keychar.toLowerCase();
    }
    else {
        charPressed = "";
    }

    // Test if the char was a DK char.
    if (charPressed == "") {
        if (keynum == 192 || keynum == 230) charPressed = String.fromCharCode(230);
        if (keynum == 222 || keynum == 248) charPressed = String.fromCharCode(248);
        if (keynum == 221 || keynum == 229) charPressed = String.fromCharCode(229);
    }

    // Was it an allowed char?
    if (charPressed != "") {
        // Yes - Was the char the same as last time?
        // Notice that the previousChar attribute is added to the select box as a custom attribute.
        if (charPressed != theSelect.previousChar) {
            // No - Update previousChar to current and set the startSearchIndex to 0 meaning search the entire list.
            theSelect.previousChar = charPressed;
            var startSearchIndex = 0;
        }
        else {
            // Yes - Set startSearchIndex to the next item after the selected or 0 if the end was reached.
            var startSearchIndex = (theSelect.selectedIndex - 1 == theSelect.options.length) ? 0 : theSelect.selectedIndex + 1;
        }

        // Loop through all items in the list starting at startSearchIndex.
        for (var i = startSearchIndex; i < theSelect.options.length; i++) {
            // Do the item start with the padText text?
            if (theSelect.options[i].text.substr(0, padText.length) == padText) {
                // Yes - Get the first char after the padText.
                var firstChar = theSelect.options[i].text.substr(padText.length, 1).toLowerCase();
            }
            else {
                // No - Just get the first char.
                var firstChar = theSelect.options[i].text.substr(0, 1).toLowerCase();
            }

            // Is the item's first char the same as the pressed?
            if (firstChar == charPressed) {
                // Yes - set the selected index to current.
                theSelect.selectedIndex = i;

                // Stop the loop.
                // Return false to stop processing events - otherwise the browser will re-select an item in the list starting with
                // the key pressed (skipping those starting with padText).
                return false;
            }
        }

        // If no items was found, the same key as last time was pressed and the startSearchIndex is greater than 0
        // (meaning a matching item for the char was found), start all over again recursively. This will select the first item
        // in the list when the last was reached.
        if (charPressed == theSelect.previousChar && startSearchIndex > 0) {
            // Reset previous char forcing the list to be looped from the beginning.
            theSelect.previousChar = "";

            // Call this method recursively.
            MarkOption(padText, theSelect, e);
        }
    }

    // No items found.
    // Return true to continue processing events like tab, enter etc.
    return true;
}

//Enable the AddressNumberTextBox validator when the validateHouseNo is performed
function ValidatorEnableHouseNo(houseTxtBx, roadTxtBx, houseTxtbxValidator) {
    //if the both the AddressRoadTextBox AddressNumberTextBox aren't empty so enable the AddressNumberTextBox validator
    if (houseTxtBx != 0 && roadTxtBx != 0)
        ValidatorEnable(houseTxtbxValidator, true);
}

//This function check if the "AddressRoadTextBox" contains a number and then move that number inton "AddressNumberTextBox"

function validateHouseNo(roadTxtBx, HousTxtBx) {
    if (roadTxtBx.value != "") {
        // Save the "AddressRoadTextBox" value into txt variable
        var txt = roadTxtBx.value;
        //Try to cach the error in case of the browser doesn't support this JavaScript
        try {
            var counter = 0;  //To count with a counter 

            var strSplit = new Array(); //An array to save the split "AddressRoadTextBox" value
            var checkForSpace = new Array();    //An array to save a list of integer
            strSplit = txt.split("");       //Split the "AddressRoadTextBox" valude by character and save it
            var str = "";                     //To save the "AddressRoadTextBox" value without number
            for (var x = 0; x < strSplit.length; x++)    //For each string in the "AddressRoadTextBox" value
            {
                counter++;                  //count the number of word
                if (isNaN(strSplit[x]))      //If the string is not a number
                    str = strSplit[x];
                else if (parseInt(strSplit[x]) >= 0)    //parse the string to integer to save only integer values
                    checkForSpace.push(parseInt(strSplit[x]));  //Save only the integer value
            }
            if (checkForSpace.length > 0)      //Check if there is at least one number in the "AddressRoadTextBox" value
            {
                var arr2 = new Array();
                for (var p = 0; p < counter; p++)
                    arr2.push(strSplit[p]);         //copy each string into the arr2 until the first number

                var arrInt = new Array();    //house number array 
                for (var x = 0; x < arr2.length; x++) {
                    var l = arr2[x];
                    if (!(isNaN(trim(l))) && (trim(l) != ""))    //if the value is number and not empty
                        arrInt.push(trim(l));               //save it in the integer array
                }
                var first = arrInt[0];    //the first number in the "AddressRoadTextBox" value
                var houseInfo = txt.substr(txt.indexOf(first), txt.length);  //the house information is saved
                var addresse = txt.substr(0, txt.indexOf(first));    //"AddressRoadTextBox" value is saved

                if (houseInfo.indexOf(",") > 0)   //check if there is any commer in the house number
                {
                    HousTxtBx.value = trim(houseInfo.substr(0, houseInfo.indexOf(",")));

                }
                else if (houseInfo.indexOf("-") > 0)  //if the house number contains - like 1-3
                {
                    HousTxtBx.value = trim(houseInfo);
                    //	                    HousTxtBx.IsValid = true;
                }
                else if (houseInfo != null)   //take the reste of the text
                {
                    var arrspace = new Array();
                    arrspace = houseInfo.split(" ");
                    //use only the house number
                    HousTxtBx.value = trim(arrspace[0]);
                    //	                    ValidatorEnableHouseNo(HouseNoBxValidator); 
                }
                roadTxtBx.value = trim(addresse);    //Trim and save the "AddressRoadTextBox" value
            }
        }

        catch (err)  //if the browser doesn't support our function or other error
        {
            alert("Husk at adskilde vej navn og husnummer");
            roadTxtBx.value = trim(txt);
            HousTxtBx.value = "";
        }
    }
}


//Trim string function
function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g, "");
}


// Adds the option to the specified select.
function AddOption(dropdown, option) {
    try {
        dropdown.add(option, null); // standards compliant
    }
    catch (ex) {
        dropdown.add(option); // IE only
    }
}


// If the clicked checkbox is marked as a 'single box' then all other boxes are unchecked.
// If the clicked checkbox is not a single box then all single boxes are unchecked.
// A single box is defined as a select box with an index (position) below the specified 'singleCount'.
// Requires MooTools to be included!
function SelectSingleCheckBox(checkbox, checkboxGroupName, singleCount) {
    // Get the array with the checkboxes.
    var checkBoxes = $(checkboxGroupName).getElements('input');

    // Did the user click a box marked as single?
    var isSingleBox = checkBoxes.indexOf(checkbox) < singleCount;

    // Loop through all boxes.
    for (i = 0; i < checkBoxes.length; i++) {
        // Did the user click a box marked as single?
        if (isSingleBox) {
            // Yes - clear all other boxes.
            if (checkbox != checkBoxes[i]) {
                checkBoxes[i].checked = false;
            }
        }
        else {
            // No - Is it a single box?
            if (i < singleCount) {
                // Yes - clear all single boxes.
                checkBoxes[i].checked = false;
            }
        }
    }
}

//Enable the AddressNumberTextBox validator when the validateHouseNo is performed
function ValidatorEnableHouseNo(houseTxtBx, roadTxtBx, houseTxtbxValidator) {
    //if the both the AddressRoadTextBox AddressNumberTextBox aren't empty so enable the AddressNumberTextBox validator
    if (houseTxtBx != 0 && roadTxtBx != 0)
        ValidatorEnable(houseTxtbxValidator, true);
}

//This function check if the "AddressRoadTextBox" contains a number and then move that number inton "AddressNumberTextBox"

function validateHouseNo(roadTxtBx, HousTxtBx) {
    if (roadTxtBx.value != "") {
        // Save the "AddressRoadTextBox" value into txt variable
        var txt = roadTxtBx.value;
        //Try to cach the error in case of the browser doesn't support this JavaScript
        try {
            var counter = 0;  //To count with a counter 

            var strSplit = new Array(); //An array to save the split "AddressRoadTextBox" value
            var checkForSpace = new Array();    //An array to save a list of integer
            strSplit = txt.split("");       //Split the "AddressRoadTextBox" valude by character and save it
            var str = "";                     //To save the "AddressRoadTextBox" value without number
            for (var x = 0; x < strSplit.length; x++)    //For each string in the "AddressRoadTextBox" value
            {
                counter++;                  //count the number of word
                if (isNaN(strSplit[x]))      //If the string is not a number
                    str = strSplit[x];
                else if (parseInt(strSplit[x]) >= 0)    //parse the string to integer to save only integer values
                    checkForSpace.push(parseInt(strSplit[x]));  //Save only the integer value
            }
            if (checkForSpace.length > 0)      //Check if there is at least one number in the "AddressRoadTextBox" value
            {
                var arr2 = new Array();
                for (var p = 0; p < counter; p++)
                    arr2.push(strSplit[p]);         //copy each string into the arr2 until the first number

                var arrInt = new Array();    //house number array 
                for (var x = 0; x < arr2.length; x++) {
                    var l = arr2[x];
                    if (!(isNaN(trim(l))) && (trim(l) != ""))    //if the value is number and not empty
                        arrInt.push(trim(l));               //save it in the integer array
                }
                var first = arrInt[0];    //the first number in the "AddressRoadTextBox" value
                var houseInfo = txt.substr(txt.indexOf(first), txt.length);  //the house information is saved
                var addresse = txt.substr(0, txt.indexOf(first));    //"AddressRoadTextBox" value is saved

                if (houseInfo.indexOf(",") > 0)   //check if there is any commer in the house number
                {
                    HousTxtBx.value = trim(houseInfo.substr(0, houseInfo.indexOf(",")));

                }
                else if (houseInfo.indexOf("-") > 0)  //if the house number contains - like 1-3
                {
                    HousTxtBx.value = trim(houseInfo);
                    //	                    HousTxtBx.IsValid = true;
                }
                else if (houseInfo != null)   //take the reste of the text
                {
                    var arrspace = new Array();
                    arrspace = houseInfo.split(" ");
                    //use only the house number
                    HousTxtBx.value = trim(arrspace[0]);
                    //	                    ValidatorEnableHouseNo(HouseNoBxValidator); 
                }
                roadTxtBx.value = trim(addresse);    //Trim and save the "AddressRoadTextBox" value
            }
        }

        catch (err)  //if the browser doesn't support our function or other error
        {
            alert("Husk at adskilde vej navn og husnummer");
            roadTxtBx.value = trim(txt);
            HousTxtBx.value = "";
        }
    }
}
//Trim string function
function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g, "");
}


// Toggle layer visibility
function toggleLayer(whichLayer) {
    var elem, vis; if (document.getElementById)
    // this is the way the standards work
        elem = document.getElementById(whichLayer); else if (document.all)
    // this is the way old msie versions work
        elem = document.all[whichLayer]; else if (document.layers)
    // this is the way nn4 works
        elem = document.layers[whichLayer]; vis = elem.style;
    // if the style.display value is blank we try to figure it out here
    if (vis.display == '' && elem.offsetWidth != undefined && elem.offsetHeight != undefined)
        vis.display = (elem.offsetWidth != 0 && elem.offsetHeight != 0) ? 'block' : 'none'; vis.display = (vis.display == '' || vis.display == 'block') ? 'none' : 'block';
}


function UpdatePrice(theBoxId, unitPrice, maxQuantity, errorTextId, calculatedPriceId) {
    var enteredValue = document.getElementById(theBoxId).value * 1;
    if (enteredValue > maxQuantity || enteredValue < 1) {
        document.getElementById(errorTextId).innerHTML = "Indtast venligst et antal der er st&oslash;rre end 0 og h&oslash;jest " + maxQuantity + ".";
        $(errorTextId).setStyle('display', '');
        document.getElementById(calculatedPriceId).innerHTML = "-";
        return false;
    }
    else {
        $(errorTextId).setStyle('display', 'none');
    }
    document.getElementById(calculatedPriceId).innerHTML = numberFormat(unitPrice * enteredValue) + " kr.";
    return true;
}

function TestNumeric(e) {
    var k;
    if (e && e.which) { // NS
        k = e.which;
    } else if (window.event && window.event.keyCode) { // IE
        k = window.event.keyCode;
    }
    return (!k || (k > 47 && k < 58));
}

function numberFormat(number) {
    nStr = (number.toFixed(2) + "").replace(".", ",");
    x = nStr.split(',');
    x1 = x[0];
    x2 = x.length > 1 ? ',' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1))
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    return x1 + x2;
}
