/*
    Common OCS JavaScript Functions
*/

// Disable log4javascript by default
var log4javascript_disabled = true;

function saveInputs(node) {
    var data = new Array();
    var inputs = node.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        data.push(inputs[i].checked);
    }
    return data;
}

function restoreInputs(node, data) {
    var inputs = node.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].checked != data[i]) {
            inputs[i].checked = data[i];
        }
    }
    return data;
}

function swapNodes(node1, node2) {
    var inp1 = saveInputs(node1);
    var inp2 = saveInputs(node2);
    if (node1.swapNode != undefined) {
        // IE
        node1.swapNode(node2);
        restoreInputs(node1, inp1);
        restoreInputs(node2, inp2);
    } else {
        // Mozilla
        var clonedNode1 = node1.cloneNode(true);
        clonedNode1.id = null;
        var oldNode2 = node2.parentNode.replaceChild(clonedNode1, node2);
        var oldNode1 = node1.parentNode.replaceChild(oldNode2, node1);
        node2.parentNode.replaceChild(oldNode1, clonedNode1);
        restoreInputs(oldNode1, inp1);
        restoreInputs(oldNode2, inp2);
    }
}

function submitForm(form, action) {
	var browserName=navigator.appName;
    if (action != null) {
	    if (browserName=="Microsoft Internet Explorer" && typeof document.body.style.maxHeight!="undefined") {
			document.getElementById(form.name).action = action;
        } else {
	    	form.action = action;
		}
	}
    if (browserName=="Microsoft Internet Explorer" && typeof document.body.style.maxHeight!="undefined") {
		document.getElementById(form.name).submit();
    } else {
	    form.submit();
    }
}

function openWindow(url,options) {
	window.open(url,'_blank',options);
}

function _moveTableRow(rowId, direction) {
    var row = document.getElementById(rowId);
    var tbody = row.parentNode;
    var last = tbody.rows.length - 1;
    for (var i = 0; i <= last; i++) {
       if (tbody.rows[i].id == rowId) {
           var j = i + direction;
           if (j >= 0 && j <= last) {
               swapNodes(tbody.rows[i], tbody.rows[j]);
           }
           break;
       }
    }
}

function addTableRow(tbodyId, prototypeRowId) {
    var tbody = document.getElementById(tbodyId);
    var prototypeRow = document.getElementById(prototypeRowId);
    var rows = tbody.rows;
    // clone the prototype
    var newRow = prototypeRow.cloneNode(true);
    // create new unique id
    newRow.id = newRow.id + "_" + rows.length;
    if (prototypeRow.nextSibling) {
        tbody.insertBefore(newRow, prototypeRow.nextSibling);
    } else {
        tbody.appendChild(newRow);
    }
    newRow.style.display="";
}

function deleteTableRow(element, message) {
    var answer = true;
    if (message) {
        answer = confirm(message);
    }
    if (answer) {
        while (element.nodeName != "TR") {
            element = element.parentNode;
        }
        var row = element;
        var tbody = row.parentNode;
        tbody.removeChild(row);
    }
}

function moveTableRowUp(element, numHeaderRows) {
    while (element.nodeName != "TR") {
        element = element.parentNode;
    }
    var row = element;
    var tbody = row.parentNode;
    for (var i = 0; i < tbody.rows.length; i++) {
        if (tbody.rows[i] == row) {
            break;
        }
    }
    if (i > numHeaderRows) {
        _moveTableRow(row.id, -1);
    }
}

function moveTableRowDown(element) {
    while (element.nodeName != "TR") {
        element = element.parentNode;
    }
    _moveTableRow(element.id, 1);
}

function addOption(theSel, theText, theValue) {
    var newOpt = new Option(theText, theValue);
    var selLength = theSel.length;
    theSel.options[selLength] = newOpt;
}

function deleteOption(theSel, theIndex) {
    var selLength = theSel.length;
    if(selLength>0) {
        theSel.options[theIndex] = null;
    }
}

function moveOptions(theSelFrom, theSelTo) {
    var selLength = theSelFrom.length;
    var selectedText = new Array();
    var selectedValues = new Array();
    var selectedCount = 0;

    var i;

    // Find the selected Options in reverse order
    // and delete them from the 'from' Select.
    for(i=selLength-1; i>=0; i--) {
        if(theSelFrom.options[i].selected) {
            selectedText[selectedCount] = theSelFrom.options[i].text;
            selectedValues[selectedCount] = theSelFrom.options[i].value;
            deleteOption(theSelFrom, i);
            selectedCount++;
        }
    }

    // Add the selected text/values in reverse order.
    // This will add the Options to the 'to' Select
    // in the same order as they were in the 'from' Select.
    for(i=selectedCount-1; i>=0; i--) {
        addOption(theSelTo, selectedText[i], selectedValues[i]);
    }
    
    orderOptions(theSelFrom,0);
    orderOptions(theSelTo,0);
}

function orderOptions(theSel,start) {
    var selLength = theSel.length;
    var tempText;
    var tempValue;
    
    for(var i = selLength - 1; i >= start; i--) {
        for(var j = start; j < i; j++) {
            if (theSel.options[i].text < theSel.options[j].text) {
                tempText = theSel.options[i].text;
                tempValue = theSel.options[i].value;
                theSel.options[i].text = theSel.options[j].text;
                theSel.options[i].value = theSel.options[j].value;
                theSel.options[j].text = tempText;
                theSel.options[j].value = tempValue;
            }
        }
    }
}

function swapDivs(divToShow, divToHide) {
    hideElement(divToHide);
    showElement(divToShow);
}

function showElement(elementToShow) {
    var element = document.getElementById(elementToShow);
    if (element != null) {
        element.style.visibility = "visible";
        element.style.display = "block";
    }
}

function hideElement(elementToHide) {
    var element = document.getElementById(elementToHide);
    if (element != null) {
        element.style.visibility = "hidden";
        element.style.display = "none";
    }
}

////////////////////////////////////////////////////////////////////////////////

function str(d) {
    var txt = "{";
    for (var k in d) {
        var t = typeof d[k];
        if (t != 'object')
            try {
                var v = d[k] != null ? d[k].toString() : 'null';
            } catch (e) {
            }
        else
            var v = str(d[k]);
        if (v.length > 20) {
            v = v.substring(0, 20)  + "...";
        }
        txt += k + ":" + v + ", ";
    }
    txt += "}";
    return txt;
}

function encode(data) {
    var enc = "";
    for (var k in data) {
        if (enc) enc += "&";
        enc += encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
    }
    return enc;
}

function showFailureMessage() {
    if (searchProcessing != null && searchProcessing.cancel != null) {
        searchProcessing.cancel();
    }
    alert('Loading has timed out, please try again.');
}

/*
 * Register global responders that will occur on all AJAX requests
 */
Ajax.Responders.register({
    onCreate: function(request) {
        startSessionTimer();
        document.documentElement.style.cursor = 'wait';
        request['timeoutId'] = window.setTimeout(
                function() {
                    // If we have hit the timeout and the AJAX request is active, abort it and let the user know
                    if (callInProgress(request.transport)) {
                        request.transport.abort();
                        showFailureMessage();
                        document.documentElement.style.cursor = 'auto';
                        // Run the onFailure method if we set one up when creating the AJAX object
                        if (request.options['onFailure']) {
                            request.options['onFailure'](request.transport, request.json);
                        }
                    }
                },
                90000 // 90 seconds
                );
    },
    onException: errorRedirectHandler,
    onComplete: errorRedirectHandler
});

function errorRedirectHandler(request) {
    // restore the mouse pointer
    document.documentElement.style.cursor = 'auto';

    // Clear the timeout, the request completed ok
    window.clearTimeout(request['timeoutId']);

    // Check for custom response header and possibly redirect
    var responseRedirect = request.getHeader('ajaxRedirect');
    var responseHeader = request.getHeader('ajaxHeader');
    if (responseRedirect != null && responseRedirect != '') {
        window.location = responseRedirect;
        return false;
    }  else if (responseHeader != null && responseHeader == 'redirect') {
        var browserName=navigator.appName;
        if (browserName=="Microsoft Internet Explorer") {
            document.write(request.transport.responseText);
        } else {
            document.documentElement.innerHTML = request.transport.responseText;
        }
        request.transport.abort();
    }

}

/*
 * Performs an AJAX call to the server and then returns
 * a response in JSON format.
 */
function ajax_json_member(actionURL, parameters, callback, asynchronous) {
    // adjust the actionURL
    actionURL = "/ocs/servlet/" + actionURL;
    asynchronous = (asynchronous != null) ? asynchronous : true;
    var handlerFunc = function(t) {
        document.documentElement.style.cursor = 'auto';
        var data;
        var responseText = t.responseText;
        if (responseText != null) {
            data = eval("(" + responseText + ")");
        }
        callback(data);
    }
    var options = {
        method : 'post',
        asynchronous : asynchronous,
        onComplete : handlerFunc,
        onFailure : errorAlert,
        on500 : errorAlert
    };
    if (parameters) options.postBody = parameters;
    new Ajax.Request(actionURL, options);
}

/*
 * This function makes a call to the server which
 * then returns HTML to update a div and call a
 * callback function if provided.
 */
function ajax_update(targetId, actionURL, parameters, asynchronous, callback) {
    // verify the target id
    var target = $(targetId);
    if ( ! target) {
        return;
    }
    // adjust the actionURL
    actionURL = "/ocs/servlet/" + actionURL;
    var handlerFunc = function(t) {
        document.documentElement.style.cursor = 'auto';
        if (t.responseText != null) {
            t.responseText.evalScripts();
        }
        if (callback != null) {
            callback(t, targetId);
        } else {
            target.innerHTML = t.responseText;
        }
    }

    var options = {
        method : 'post',
        asynchronous : asynchronous,
        evalScripts : true,
        onComplete : handlerFunc,
        onFailure : errorAlert
    };
    if (parameters) options.postBody = parameters;
    new Ajax.Request(actionURL, options);
}

function errorAlert(t) {
}

function callInProgress(xmlhttp) {
    switch (xmlhttp.readyState) {
        case 1: case 2: case 3:
        return true;
        break;
        default:
            return false;
            break;
    }
}

////////////////////////////////////////////////////////////////////////////////

