//Using events_common.js to add eventhandlers onload.
addEventHandler(window, "load", setInputMaxLength);
addEventHandler(window, "load", prepareToggleDescription);
addEventHandler(window, "load", preparePopupLinks);

/*
Name: setInputMaxLength
Purpose: Sets a maxlength to globalMaxLength on inputfields with type text
         provided maxlength is not already set.
Arguments: no arguments.
*/
function setInputMaxLength() {

    var globalMaxLength = 128;
    var inputs = document.getElementsByTagName("input");

    for (var i = 0; i < inputs.length; i++) {
        var inputType = inputs[i].getAttribute('type');
        var maxLength = inputs[i].getAttribute('maxlength');
        //maxlength not set in IE gives a large value
        if (inputType == 'text') {

            /* if the css-class is set to FSfocus on a input type text element, then we set focus to the element at onload.
               The prefix FS stands for functional stylesheet.. meaning the class does not exist in css-file in
               traditional meaning. Instead we use it to trigger a certain functionality, here setting focus onload. */
            if (inputs[i].className.indexOf("FSfocus") != -1) {
                inputs[i].focus();
            }
            if (maxLength == null || maxLength > 10000) {
                inputs[i].setAttribute('maxlength', globalMaxLength);
            }

            //the workaround below is too shakey atm.. better to not have maxlength set in ie...
            //IE workaround, it doesnt understand setAttribute for maxlength
            /*
            if (maxLength == inputs[i].getAttribute('maxlength')) {
                var element = inputs[i];
                var newElement = null;
                var createElementText = "";
                //Get all the existing attributes
                createElementText += " type=\""  + inputs[i].getAttribute("type")+"\"";
                createElementText += " name=\""  + inputs[i].name+"\"";
                createElementText += " value=\"" + inputs[i].getAttribute("value")+"\"";
                createElementText += " style=\"" + inputs[i].style.cssText+"\"";
                createElementText += " class=\"" + inputs[i].className+"\"";
                createElementText += " id=\""    + inputs[i].getAttribute("id")+"\"";
                createElementText += " title=\"" + inputs[i].getAttribute("title")+"\"";
                //Add maxlength
                createElementText += " maxlength=\"" + globalMaxLength+"\"";

                //Create a new element to replace the old one
                newElement = document.createElement("<input" + createElementText + ">");
                element.parentNode.replaceChild(newElement, element);
            }
            */
        }


    }
}

/*
    Trims whitespaces from a string
    usage: string.trim()
*/
String.prototype.trim = function () {
    var regexp = /^\s*|\s*$/g;
    return this.replace(regexp, "");
}


//isToggleActivated - If toggle is activated or not.
var isToggleActivated = true;
/*
Name: toggleDescription
Purpose: Toggles helptexts for an element on page.
Arguments: e - fired event.
*/
function toggleDescription(e) {
    //Get target element (where event fired)
    var targ = getTargetElement(e);

    var style = document.getElementById("description_" + targ.id).style;
    if (style.display == 'block') {
        if (isToggleActivated) {
            style.display = 'none';
        }
    } else {
        style.display = 'block';
    }
}

/*
Name: hideDescription
Purpose: Hides helptext for an element on page.
Arguments: e - fired event.
*/
function hideDescription(e) {
    //Get target element (where event fired)
    var targ = getTargetElement(e);
    var elem = targ.parentNode;

    var style = elem.style;
    if (style.display == 'block') {
        style.display = 'none';
    }
}

/*
Name: getForAttribute
Purpose: Get the for attribute for a given element (probably a label)
Arguments: element
Returns: for attribute
*/
function getForAttribute(element) {
    var attribute;
    if (element.getAttribute("for") == null) {
        attribute = element.attributes['for'].value;
        // Required by IE6 and IE7
    } else {
        attribute = element.getAttribute("for");
        // Required by Safari (for Mac)
    }
    return attribute;
}

/*
Name: showHideOthersInGroup
Purpose: Show/hide a helptext and automatically hide others in the same group
Arguments: e - fired event.
*/
function showHideOthersInGroup(e) {
    var targ = getTargetElement(e);
    var labelForID = getForAttribute(targ);
    var groupName = document.getElementById(labelForID).name;
    var groupElements = document.getElementsByName(groupName);
    var labels = document.getElementsByTagName("label");

    for (var i = 0; i < groupElements.length; i++) {

        // Don't hide the helptext for the label that was clicked
        if (labelForID == groupElements[i].id) continue;
        // Get the group id
        var groupID = groupElements[i].getAttribute("id");

        // Hide other helptext descriptions
        for (var j = 0; j < labels.length; j++) {
            // Find labels with the class "hideOthers"
            if (labels[j].className.indexOf("hideOthers") != -1) {
                // Get the label's for-attribute
                var tempForValue = getForAttribute(labels[j]);
                // Compare the for-attribute with the clicked
                if (tempForValue == groupID) {
                    // Get the found label's id-attribute
                    var foundLabelId = labels[j].getAttribute("id");
                    // Find the matching description layer using id-attribute and hide the layer
                    var style = document.getElementById("description_" + foundLabelId).style;
                    style.display = 'none';
                }
            }
        }
    }
    // Show / hide clicked label description
    toggleDescription(e);
}

/*
Name: prepareToggleDescription
Purpose: Adds eventhandlers for toggling descriptions (helptexts).
Arguments: None.
*/
function prepareToggleDescription() {
    var labels = document.getElementsByTagName("label");
    var divs = document.getElementsByTagName("div");

    //Add eventhandlers for label-elements with correct classname.
    for (var i = 0; i < labels.length; i++) {
        //Add eventhandlers for groups of descriptions that need to hide others
        if (labels[i].className.indexOf("hideOthers") != -1) {
            addEventHandler(labels[i], "click", showHideOthersInGroup);
        }
        if (labels[i].className.indexOf("descriptionShow") != -1) {
            addEventHandler(labels[i], "click", toggleDescription);
        }
    }
    //Add eventhandlers for div-elements with correct classname.
    for (var i = 0; i < divs.length; i++) {
        if (divs[i].className == "descriptionClose") {
            addEventHandler(divs[i], "click", hideDescription);
        }
        if (divs[i].className.indexOf("descriptionShow") != -1) {
            addEventHandler(divs[i], "click", toggleDescription);
        }
    }
}
/*
Name: setFocusOnload
Purpose: functionality for setting focus on a formfield onload.
Arguments: the Id of the formfield
*/
function setFocus(elementId) {
    document.getElementById(elementId).focus();
}

/*
Name: setFocusOnload
Purpose: functionality for enabling/disabling a form field
Arguments: the Id of the formfield,
           true = field should be disabled
           false = field should be enabled
*/
function setDisabled(elementId, mode) {
    element = document.getElementById(elementId);
    if (mode) {
        element.disabled = true;
        if (element.type != 'radio' && element.type  != 'checkbox') {
            element.className += " disabled";
        }
    } else {
        element.disabled = false;
        if (element.type != 'radio' && element.type  != 'checkbox') {
            element.className = element.className.replace(/\s?disabled/gi,"");
        }
    }
}

/*
Name: textAreaMaxLength
Purpose: functionality for limiting input in an textarea
Arguments: field = the textarea formfield
           maxlength = max length of input

Usage: textAreaMaxLength(this,200) on onchange, onkeyup, onkeydown and onblur           
*/
function textAreaMaxLength(field,maxlength) {
    if (field.value.length > maxlength) {
        field.value = field.value.substring(0,maxlength);
    }
}

/*
Name: preparePopupLinks()
Purpose: Add onclick to links that has the popup* style-class
Arguments:
    e - The occured event.
*/
function preparePopupLinks() {
	var links = document.getElementsByTagName("a");
	for (var i = 0; i < links.length; i++) {
		if (null != links[i].className) {
			if (links[i].className.indexOf("popup") > -1) {
				var functionName;
				var classNames = links[i].className.split(" ");
				for (var j = 0; j < classNames.length; j++) {
					if (classNames[j].indexOf("popup") > -1) {
						functionName = classNames[j];
					}
				}
				links[i].onclick = eval(functionName);
			}
		}
	}
}


