// main.js

// ---------------------------------------------------------------------------

function addEvent(elm, evType, fn, useCapture) {

    if(elm) {

        if(elm.addEventListener) {

            elm.addEventListener(evType, fn, useCapture);
            return true;

        }
        else if(elm.attachEvent) {

            var r = elm.attachEvent('on' + evType, fn);
            return r;

        }
        else {

            elm['on' + evType] = fn;
            return true;

        }

    }

    return false;

}

// ---------------------------------------------------------------------------

function removeEvent(elm, evType, fn, useCapture) {

    if(elm) {

        if(elm.removeEventListener) {

            elm.removeEventListener(evType, fn, useCapture);
            return true;

        }
        else if(elm.detachEvent) {

            var r = elm.detachEvent('on' + evType, fn);
            return r;

        }

    }

    return false;

}

// ---------------------------------------------------------------------------

function grep(str) {

  var ar = new Array();

  var arSub = 0;

  for (var i in this) {

     if (typeof this[i] == "string" && this[i].indexOf(str) != -1) {

         ar[arSub] = this[i];
         arSub++;
     }

  }

  return ar;

}

Array.prototype.grep = grep

// ---------------------------------------------------------------------------

function preventDefault (e) {

    var target = (window.event) ? window.event.srcElement : e.target;

    //prevent default behavior

    if (window.event) {

      window.event.cancelBubble = true;
      window.event.returnValue  = false;

    } else if (e && e.preventDefault) {

      e.preventDefault();

    } else {

     element.action = 'javascript:void(0);';

    }

}

// ---------------------------------------------------------------------------

function deleteRow(e) {

    if ( edit ) {

        alert("You cannot delete a row while you are editing a row.");
        return false;

    }


    var target = (window.event) ? window.event.srcElement : e.target;
    var td     = target.parentNode;
    var tr     = td.parentNode;
    var tbody  = tr.parentNode;

    tbody.removeChild(tr);

    var rows = tbody.getElementsByTagName('tr');

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

     //   rows[i].id = rows[i].id.replace(/\d+$/, "") + i;

    //}

    if ( adjustWings )
        adjustWings(e);

    return false;

}

// ---------------------------------------------------------------------------

function swapRows(table_rows, thisId, table_body, direction) {

    var clickedrow_cloned  = table_rows[thisId].cloneNode(true);
    var adjacentrow_cloned = table_rows[parseInt(thisId) + direction].cloneNode(true);

    clickedrow_cloned.id  = table_rows[parseInt(thisId) + direction].id;
    adjacentrow_cloned.id = table_rows[thisId].id;

    var anchors = clickedrow_cloned.getElementsByTagName('a');

    _add_anchor_events(anchors);

    anchors = adjacentrow_cloned.getElementsByTagName('a');

    _add_anchor_events(anchors);

    var inputs = clickedrow_cloned.getElementsByTagName('input');

    _add_input_events(inputs);

    inputs  = adjacentrow_cloned.getElementsByTagName('input');

    _add_input_events(inputs);

    table_body.replaceChild(clickedrow_cloned,table_rows[parseInt(thisId) + direction]);
    table_body.replaceChild(adjacentrow_cloned,table_rows[thisId]);

}

// ---------------------------------------------------------------------------

function _add_input_events(inputs) {

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

        if ( inputs[i].id.match(/^edit/) ) {

            addEvent(inputs[i], 'click', editRow, false);

        }
        else {

            addEvent(inputs[i], 'click', deleteRow, false);

        }

    }

}

// ---------------------------------------------------------------------------

function _add_anchor_events(anchors) {

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

        addEvent(anchors[i], 'click', moveRow, false);

    }

}

// ---------------------------------------------------------------------------

function clearinnerHTML(obj) {

   while (obj.childNodes.length > 0) {

       obj.removeChild(obj.childNodes[0]);

   }

}

// ---------------------------------------------------------------------------

function clearAuthenticationCache(page) {

    // Default to a non-existing page (give error 500).
    // An empty page is better, here.

    if (!page)
        page = '.force_logout';

        var url = window.location.href;

        var next = url.replace(/^(.*\/).*$/, "$1");

        if (! next.match(/admin/))
            next = next.replace(/web_auth/, "help");

        window.location.replace(next);

    try {

        document.execCommand("ClearAuthenticationCache");

    } catch(e) {

    }

        // Let's create an xmlhttp object
        var xmlhttp = new XMLHttpRequest();

        // Let's prepare invalid credentials
        xmlhttp.open("GET", page, true, "logout", "logout");

        // Let's send the request to the server
        xmlhttp.send(null);

        // Let's abort the request
        xmlhttp.abort();


//    var url = window.location.href;

//    var next = url.replace(/^(.*\/).*$/, "$1");

//    next = next.replace(/web_auth/, "help");

//    window.location.replace(next);

    return false;

}

// ----------------------------------------------------------------------------

// checks if an object is visible
// initially added for form validation so hidden fields aren't required
// from http://snippets.dzone.com/posts/show/5757

function isVisible(obj) {

    if (obj == document) return true;

    if (!obj) return false;

    if (!obj.parentNode) return false;

    if (obj.style) {

        if (obj.style.display    == 'none')   return false;
        if (obj.style.visibility == 'hidden') return false;

    }

    //Try the computed style in a standard way

    if (window.getComputedStyle) {

        var style = window.getComputedStyle(obj, "");

        if (style.display    == 'none')   return false;
        if (style.visibility == 'hidden') return false;

    }

    // Or get the computed style using IE's silly proprietary way

    var style = obj.currentStyle;

    if (style) {

        if (style['display']    == 'none')   return false;
        if (style['visibility'] == 'hidden') return false;

    }

    return isVisible(obj.parentNode);

}

// ---------------------------------------------------------------------------

// checks that all required fields have a value

// required fields are visible INPUT(text, password, file), TEXTAREA, and
// SELECT form elements which are not disabled or read-only, and whose id
// does not contain 'optional'

// returns the first failed element, or false if validation succeeds

// if validation fails, the focus is set to the failing field.

function checkRequiredFormFields(form) {

    var elements = form.elements;

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

        if (checkRequiredFormField(elements[i])) {

            return elements[i];

        }

    }

    // all fields ok

    return false;

}

// ---------------------------------------------------------------------------

// checks a single field to see if it is required, and if so, has a value

// required fields are visible INPUT(text, password, file), TEXTAREA, and
// SELECT form elements which are not disabled or read-only, and whose id
// does not contain 'optional'

// primarily used by checkRequiredFormFields(), but can be called directly
// if there are additional field specific validations required.

// if the validation succeeds, returns false; if the validation fails,
// sets focus to the field and returns true

function checkRequiredFormField(element) {

    if ( ! element || element.id.match(/optional/) || ! isVisible(element) ) {

        return false;

    }

    switch(element.tagName) {

        case 'INPUT':

            if ( element.disabled || element.readonly ) {

                return false;

            }

            switch(element.type) {

                case 'text':
                case 'file':
                case 'password':

                    if (( element.value) && (! element.value.match(/^\s*$/))) {

                        return false;

                    }

                    break;

                default:

                    // don't validate anything else (radio, checkbox, hidden, button, image, reset, submit)

                    return false;

            }

            break;

        case 'TEXTAREA':

            if ( element.disabled || element.readonly ) {

                return false;

            }

            if (( element.value) && (! element.value.match(/^\s*$/))) {

                return false;

            }

            break;

        case 'SELECT':

            if ( element.disabled ) {

                return false;

            }

            if ( element.options[element.selectedIndex].value != '' ) {

                return false;

            }

            break;

        default:

            return false;

    }

    element.focus();

    return true;

}

// ---------------------------------------------------------------------------
