Utils = {
    addLoadEvent : function(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        }
        else {
            window.onload = function() {
                oldonload();
                func();
            }
        }
    },

    hideElements: function(targetIds) {
        for (var i = 0; i < targetIds.length; i++)
            $(targetIds[i]).style.display = 'none';
    },

    // ----------------
    // slider functions    
    sliderTargetOpen: [],
    toggleSlider: function(targetId) {
        if (this.sliderTargetOpen[targetId]) {
            Effect.SlideUp($(targetId));
            this.sliderTargetOpen[targetId] = false;
        } else {
            Effect.SlideDown($(targetId));
            this.sliderTargetOpen[targetId] = true;
        }
    },

    slideDown: function(targetId, onlyIfUp) {
        if (onlyIfUp) {
            if (!this.sliderTargetOpen[targetId]) {
                Effect.SlideDown($(targetId));
                this.sliderTargetOpen[targetId] = true;
            }
        } else {
            Effect.SlideDown($(targetId));
            this.sliderTargetOpen[targetId] = true;
        }
    },
    slideUp: function(targetId, onlyIfDown) {
        if (onlyIfDown) {
            if (this.sliderTargetOpen[targetId]) {
                Effect.SlideUp($(targetId));
                this.sliderTargetOpen[targetId] = false;
            }
        } else {
            Effect.SlideUp($(targetId));
            this.sliderTargetOpen[targetId] = false;
        }
    },

    fadeIn: function(targetId, time) {
        var duration = 1.0;
        if (time) duration = time;
        Effect.Fade(targetId, {from: 0, to:1.0, duration: duration});
    },

    fadeOut: function(targetId, time) {
        var duration = 1.0;
        if (time) duration = time;
        Effect.Fade(targetId, {from: 1.0, to:0, duration: duration});
    },

    pageWidth: function() {
        return window.innerWidth != null ? window.innerWidth : document.body != null ? document.body.clientWidth : null;
    },

    pageHeight: function() {
        return window.innerHeight != null ? window.innerHeight : document.body != null ? document.body.clientHeight : null;
    }


};


var ExpanderImage = {
    expandImage: 'images/expand.jpg',
    collapseImage: 'images/collapse.jpg',
    isOpen: {},

    toggleExpand: function(imgId) {
        if (imgId && $(imgId)) {
            if (this.isOpen[imgId]) {
                $(imgId).src = this.expandImage;
                this.isOpen[imgId] = false;
            } else {
                $(imgId).src = this.collapseImage;
                this.isOpen[imgId] = true;
            }
        }
    }

};

// Swap.js - start
var ExpandImage = 'expand.jpg';
var CollapseImage = 'collapse.jpg';

function GetTag(TagID) {
    //returns a reference to the HTML element with ID = TagID
    var Ret = document.getElementById(TagID);
    if (!Ret) alert("GetTag: tag '" + TagID + "' does not exist.");
    return Ret;
}

function ToggleExpand(ExpandID, ImagePath) {
    var ExpandButton = GetTag(ExpandID + "_expand_button");
    var ShortHTML = GetTag(ExpandID + "_short_html");
    var LongHTML = GetTag(ExpandID + "_long_html");

    if (ShortHTML.style.display == "none") {
        ShortHTML.style.display = "";
        LongHTML.style.display = "none";
        ExpandButton.src = ImagePath + ExpandImage;
    } else {
        ShortHTML.style.display = "none";
        LongHTML.style.display = "";
        ExpandButton.src = ImagePath + CollapseImage;
    }
}

function ShowHide(ExpandID, SelectID, Value) {
    var ShortHTML = GetTag(ExpandID + "_short_html");
    var LongHTML = GetTag(ExpandID + "_long_html");
    var Select = document.getElementById(SelectID);
    if (!Select) alert("ShowHide: tag '" + SelectID + "' does not exist.");

    if (Select.options[Select.selectedIndex].value == Value) {
        ShortHTML.style.display = "none";
        LongHTML.style.display = "";
        SetHiddenField(ExpandID, 'true');
    } else {
        ShortHTML.style.display = "";
        LongHTML.style.display = "none";
        SetHiddenField(ExpandID, 'false');
    }
}

function SetHiddenField(FieldID, Value) {
    var HiddenField = document.getElementById(FieldID);
    HiddenField.value = Value;
}

function showDiv(divId) {
    var div = document.getElementById(divId);
    if (div) {
        div.className = "";
    }
}

function hideDiv(divId) {
    var div = document.getElementById(divId);
    if (div) {
        div.className = "hiddenDiv";
    }
}

DataTableUtils = {
    // use for only small numbers of rows (i.e 20 or less)
    copyRow: function(dataTable1, dataTable2, table1Row, propNames) {
        var table1cols = dataTable1.getNumberOfColumns();
        if (table1Row < dataTable1.getNumberOfRows()) {
            if (table1cols == dataTable2.getNumberOfColumns()) {
                var newRowIndex = dataTable2.addRow();
                for (var col = 0; col < table1cols; col++) {
                    var properties = this.getCellProperties(dataTable1, table1Row, col, propNames);
                    var value = dataTable1.getValue(table1Row, col);
                    var formattedValue = dataTable1.getFormattedValue(table1Row, col);
                    if (!formattedValue) formattedValue = value;
                    dataTable2.setCell(newRowIndex, col, value, formattedValue, properties);
                }
            }
        }
    },

    copyManyRows: function(dataTable1, dataTable2, table1RowArray, propNames) {
        var table1cols = dataTable1.getNumberOfColumns();
        if (table1RowArray.length > 0 && table1RowArray.length <= dataTable1.getNumberOfRows()) {
            if (table1cols == dataTable2.getNumberOfColumns()) {
                // add new rows in bulk to dataTable2
                var newRowIndex = dataTable2.getNumberOfRows();
                dataTable2.addRows(table1RowArray.length);
                // iterate over the selected rows and copy data
                for (var table1Row = 0; table1Row < table1RowArray.length; table1Row++) {
                    for (var col = 0; col < table1cols; col++) {
                        var properties = this.getCellProperties(dataTable1, table1RowArray[table1Row], col, propNames);
                        var value = dataTable1.getValue(table1RowArray[table1Row], col);
                        var formattedValue = dataTable1.getFormattedValue(table1RowArray[table1Row], col);
                        if (!formattedValue) formattedValue = value;
                        dataTable2.setCell(newRowIndex, col, value, formattedValue, properties);
                    }
                    newRowIndex++;
                }
            }
        }
    },

    // returns a new table with the indicated rows removed
    removeRows: function(dataTable, rowIndicies, propNames) {
        if (dataTable) {
            // put rows to remove into a hash
            var removeRows = new Hash();
            $A(rowIndicies).each(function (rowIndex) {
                removeRows.set(rowIndex, true);
            });
            // copy over each cell
            var newDataTable = this.cloneNoData(dataTable);
            for (var row = 0; row < dataTable.getNumberOfRows(); row++) {
                if (!removeRows.get(row)) {
                    var newRowIndex = newDataTable.addRow();
                    for (var col = 0; col < dataTable.getNumberOfColumns(); col++) {
                        var properties = this.getCellProperties(dataTable, row, col, propNames);
                        var value = dataTable.getValue(row, col);
                        var formattedValue = dataTable.getFormattedValue(row, col);
                        if (!formattedValue) formattedValue = value;
                        newDataTable.setCell(newRowIndex, col, value, formattedValue, properties);
                    }
                }
            }
            return newDataTable;
        }
    },

    // returns a new DataTable with the same columns but without the data of the passed table
    cloneNoData: function(dataTable) {
        var newDataTable = new google.visualization.DataTable();
        if (dataTable) {
            for (var col = 0; col < dataTable.getNumberOfColumns(); col++) {
                newDataTable.addColumn(dataTable.getColumnType(col), dataTable.getColumnLabel(col), dataTable.getColumnId(col));
            }
        }
        return newDataTable;
    },

    // returns an object of the cell's properties with names in propNames
    getCellProperties: function(dataTable, row, col, propNames) {
        var properties = new Hash();
        $A(propNames).each(function(propName) {
            var propValue;
            try {
                propValue = dataTable.getProperty(row, col, propName);
            } catch (e) {
            }
            if (propValue)
                properties.set(propName, propValue);
        });
        return properties.toObject();
    },

    getAllRowsSelectedObject: function(dataTable) {
        var selection = new Array();
        for (var i = 0; i < dataTable.getNumberOfRows(); i++) {
            selection[selection.length] = {row: i};
        }
        return selection;
    }
}

AjaxUtils = {
    getJson : function(url, fnComplete) {
        function getsuccess(oResponse) {
            fnComplete(oResponse.responseJSON);
        }
        ;
        function getfailure(oResponse) {
            fnComplete(null);
        }
        ;

        new Ajax.Request(url, { method: "get", onSuccess: getsuccess, onFailure: getfailure });
    },

    postJson : function(url, paramsObj, fnComplete) {
        function postsuccess(oResponse) {
            fnComplete(oResponse.responseJSON);
        }
        ;
        function postfailure(oResponse) {
            fnComplete(null);
        }
        ;

        new Ajax.Request(url, { method: "post", parameters: paramsObj, onSuccess: postsuccess, onFailure: postfailure });

    },

    replaceInnerHTMLWithUrl : function(targetElementId, url) {
        var targetElement = document.getElementById(targetElementId);
        targetElement.innerHTML = "<img src='images/folders/loading.gif'>";
        var callback = {
            //if our XHR call is successful, we want to make use of the returned data and create child nodes.
            success: function(oResponse) {
                var targetElement = document.getElementById(targetElementId);
                var responseText = oResponse.responseText;
                if (targetElement != null) {
                    targetElement.innerHTML = responseText;
                    YAHOO.log("innerHTML added sucessfully", "info", "example");
                }
            },

            failure: function(oResponse) {
                YAHOO.log("Failed to process XHR transaction.", "info", "example");
            },

            argument: {

            },

            timeout: 30000,

            cache: false
        };
        YAHOO.util.Connect.asyncRequest('GET', url, callback);
    }

}

SearchUtils = {
    appendCheckBox : function(parentNode, checkboxName, checkboxValue, label) {
        //            var checkboxString = "<input type='checkbox' name='"+ checkboxName +"' value='"+ checkboxValue +"'>";
        var checkbox;
        // try IE method, if fails then do firefox method
        try {
            checkbox = document.createElement("<input type='checkbox' name='" + checkboxName + "' value='" + checkboxValue + "'>");
        } catch(err) {
            checkbox = document.createElement("input");
            checkbox.type = "checkbox";
            checkbox.name = checkboxName;
            checkbox.value = checkboxValue;
        }
        parentNode.appendChild(checkbox);
        checkbox.setAttribute("checked", true);
        parentNode.appendChild(document.createTextNode(label));
        parentNode.appendChild(document.createElement("br"));
    },

    clearContainer : function(containerId) {
        var container = document.getElementById(containerId);
        container.innerHTML = '';
    },

    disableButtonAndAddSpinner : function(buttonId, spinnerDivId) {
        var buttonObj = document.getElementById(buttonId);
        var spinnerDiv = document.getElementById(spinnerDivId);
        if (buttonObj)
            buttonObj.disabled = true;
        if (spinnerDiv)
            spinnerDiv.innerHTML = "<img src='images/folders/loading.gif'>";
    },

    enableButtonAndRemoveSpinner : function(buttonId, spinnderDivId) {
        var buttonObj = document.getElementById(buttonId);
        var spinnerDiv = document.getElementById(spinnderDivId);
        if (buttonObj)
            buttonObj.disabled = false;
        if (spinnerDiv)
            spinnerDiv.innerHTML = '';

    }
};

QueryJcr = {
    submitQuery: function(queryPropertyNameId, queryTermId, queryResultsDivId, samplesCheckboxName, buttonId, spinnerDivId) {
        var queryPropertyName = '';
        var queryTerm = document.getElementById(queryTermId);
        if (queryTerm.value.length == 0) {
            return;
        }
        var queryUrl = "query.jcr?propertyName=" + queryPropertyName + "&queryTerm=" + queryTerm.value;

        SearchUtils.disableButtonAndAddSpinner(buttonId, spinnerDivId);

        var callback = {
            success: function(oResponse) {
                var queryResults = YAHOO.lang.JSON.parse(oResponse.responseText).queryResults;
                var queryResultsDiv = document.getElementById(queryResultsDivId);

                queryResultsDiv.innerHTML = '';
                if (queryResults) {
                    //Result is an array if more than one result, string otherwise
                    for (var i = 0; i < queryResults.length; i++) {
                        var result = queryResults[i];
                        SearchUtils.appendCheckBox(queryResultsDiv, samplesCheckboxName, result.id, result.name);
                    }
                }
                SearchUtils.enableButtonAndRemoveSpinner(buttonId, spinnerDivId);
            },

            failute: function(o) {
                SearchUtils.enableButtonAndRemoveSpinner(buttonId, spinnerDivId);
                alert("frmFailure:" + o.responseText);
            },

            timeout: 86400000,
            cache: false
        }; // timeout of 86,400,000 => 24 hours

        // do search
        YAHOO.util.Connect.asyncRequest('POST', queryUrl, callback);
    }
};

