// these functions may be used in every other script

function getElement(id) {
    return document.getElementById(id);
}

// returns an array of DOM objects with class className
// className - class property of tags (eg: mandatory)
// where - DOM node, to start search from (can be null, then document is used)
// tagName - return only tags of this type (eg: input), can be null (for all tags)
function getElementsByClass(className, where, tagName) {
    var matches = [],    // array for returned DOM nodes
        i = 0,           // loop counter
        j = 0,           // found element counter
        elements = null, // all descendants of where
        count = 0,       // number of the descendants
        pattern = null;  // regepx pattern

    if (!where) {
        where = document;
    }
    if (!tagName) {
        tagName = '*';
    }
    
    elements = where.getElementsByTagName(tagName);
    count = elements.length;
    pattern = new RegExp("(^|\\\\s)" + className + "(\\\\s|$)");
    for (i = 0; i < count; i += 1) {
        if (pattern.test(elements[i].className)) {
            matches[j] = elements[i];
            j += 1;
        }
    }
    return matches;
}

// used for main page resizing (when the page loads)
function resize() {
    var mainContent = getElement('mainContent'),
        sidebar1 = getElement('sidebar1');
    
    if (sidebar1.offsetHeight > mainContent.offsetHeight) {
        mainContent.style.height = sidebar1.offsetHeight + 'px';
    }
}

// check is an input node has any value set
function isEmpty(node) {
    if (node.value === '') {
        return true;
    }
    return false;
}

// check a text input node if it's value is a valid email
function isValidEmail(node) {
    if (-1 === node.value.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/)) {
        return false;
    }
    return true;
}

// check a text input node, if it's value is a valid url
function isValidUrl(node) {
    var r = new RegExp("^(ftp|http|https)://([a-zA-Z0-9-_]+[.])*[a-zA-Z0-9-_]+[.][a-zA-Z]{2,4}/?$", "i"),
        res = r.test(node.value);

    if (res) {
        return true;
    }
    return false;
}

// show validation error messages and focus on first unfilled required field
function errorAfterFormCheck(form, input_name, error_msg) {
    if (-1 !== form[input_name].className.search('invalid')) {
        form[input_name].focus();
        alert(error_msg);
        return true;
    }
    return false;
}

