﻿/// <reference path="jdiacono.js" />
/** 
*   Web utilities and namespaces
*   @author: James Diacono
*   @date: 2nd of June, 2010
*   @requires: jdiacono, jdiacono.ie
*/

/** Namespace: jdiacono.web
*  Contains: All javascript modules which reference the DOM
*/
if (!jdiacono.web) { 
    jdiacono.web = {};
}

/** Methods
*/
jdiacono.web.addAttributeValue = function (element, attributeName, value, separator) {
    ///<summary>
    ///		Adds an attribute value to any XML element in the DOM, if it is not already there
    ///</summary>
    ///<param name="element" type="DOM Element">
    ///<param name="attributeName" type="string">
    ///<param name="value" type="string">
    ///<param name="separator" type="string">
    ///<returns type="DOM Element" />
    separator = separator || ' ';

    var values = [];

    // Get an array of the attribute values:
    if (element.getAttribute(attributeName)) {
        values = element.getAttribute(attributeName).split(separator);
    }

    // If the value is not present:
    if (values.indexOf(value) === -1) {
        values.push(value);
    }

    if (element.className && attributeName.toLowerCase() === 'class') {
        element.className = values.join(separator);
    } else {
        element.setAttribute(attributeName, values.join(separator));
    }

    return element;
};

jdiacono.web.removeAttributeValue = function (element, attributeName, value, separator) {
    ///<summary>
    ///		Removes all instances of an attribute value in any XML element in the DOM
    ///</summary>
    ///<param name="element" type="DOM Element">
    ///<param name="attributeName" type="string">
    ///<param name="value" type="string">
    ///<param name="separator" type="string">
    ///<returns type="DOM Element" />
    separator = separator || ' ';

    var values = [];

    // Get an array of the attribute values:
    if (element.getAttribute(attributeName)) {
        values = element.getAttribute(attributeName).split(separator);
    }

    // Remove all instances of the attribute value:
    var i;
    while ((i = values.indexOf(value)) !== -1) {
        values.splice(i, 1);
    }

    if (element.className && attributeName.toLowerCase() === 'class') {
        element.className = values.join(separator);
    } else {
        element.setAttribute(attributeName, values.join(separator));
    }

    return element;
};

