/* BUILTINS */

String.prototype.trim = function () {
    return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

Array.prototype.indexOf = function(obj) {
    var result = -1;
    for (var i = 0; i < this.length; i++) {
        if (this[i] == obj) {
            result = i;
            break;
        }
    }
    return result;
}

Array.prototype.contains = function(obj) {
    return (this.indexOf(obj) >= 0);
}

/* DOM NAVIGATION */

function getRowForCell(el) {
    do  {
        if (el.nodeName == 'TR')
            return el;
    } while (el = el.parentNode);
}

function getTableForCell(el) {
    do  {
        if (el.nodeName == 'TABLE')
            return el;
    } while (el = el.parentNode);
}

function getTableForRow(el) {
    do  {
        if (el.nodeName == 'TABLE')
            return el;
    } while (el = el.parentNode);
}

function getNextRow(el) {
    while (el = el.nextSibling) {
        if (el && el.nodeName == 'TR')
            return el;
    }
}

function hasClass(element, clazz) {
    if (element.className) {
        var classVals = element.className.split(' ');
        return classVals.contains(clazz);
    }
}

function getTableWidth(cell) {
    var row = getRowForCell(cell);
    return row.cells.length;
}

NodeRetriever = function(parent, nodeType) {
    this.outNodes = [];
    this.nodeType = nodeType;
    if (parent.childNodes) {
        this.findNodes(parent);
    }
}

NodeRetriever.prototype = {
    
    findNodes: function(parent) {
        if (parent.childNodes && parent.childNodes.length > 0) {
            for (var i = 0; i < parent.childNodes.length; i++) {
                var node = parent.childNodes[i];
                if (node.nodeName == this.nodeType) {
                    this.outNodes.push(node);
                }
                if (node.childNodes && node.childNodes.length > 0) {
                    this.findNodes(node);
                }
            }
        }
    }, 
    
    getNodes: function() {
        return this.outNodes;
    }
}

/* NET */

var net = new Object();

net.ContentLoader = function(component, url, method, requestParams) {
    this.component = component;
    this.url = url;
    this.requestParams = requestParams;
    this.method = method;
    this.request = null;
}

net.ContentLoader.handleAjaxResponse = function() {
    var req = this.request;
    if (req.readyState == 4) {
        if (req.status == 200 || req.status == 0)
            this.component.ajaxUpdate(req);
        else
            this.component.handleError(req);
    }
}

net.ContentLoader.prototype = {
    
    getTransport: function() {
        var transport;
        if (window.XMLHttpRequest)
            transport = new XMLHttpRequest();
        else if(window.ActiveXObject) {
            try {
                transport = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(err) {
                transport = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        return transport;
    },
    
    sendRequest: function() {
        var requestParams = [];
        for (var i = 0; i < arguments.length; i++)
            requestParams.push(arguments[i]);
        
        var oThis = this;
        this.request = this.getTransport();
        var qstr = this.queryString(requestParams);
        this.request.onreadystatechange = function() { net.ContentLoader.handleAjaxResponse.call(oThis);}
        this.request.open(this.method, this.url + "?" + qstr, true);
        this.request.send(null);
    },
    
    queryString: function(args) {
        var requestParams = [];
        for (var i = 0; i < this.requestParams.length; i++) 
            requestParams.push(this.requestParams[i]);
        for (var j = 0; j < args.length; j++)
            requestParams.push(args[j]);
        
        var queryString = "";
        if (requestParams && requestParams.length > 0) {
            for (var i = 0; i < requestParams.length; i++)
                queryString += requestParams[i] + '&';
            queryString = queryString.substring(0, queryString.length - 1);
        }
        return queryString;
    }
}

/* GUI COMPONENTS */

var GUI = new Object();

GUI.ExpandTableCell = function() {
}

GUI.ExpandTableCell.prototype = {
    ajaxUpdate: function(request) {
        var curRow = getRowForCell(this.cell);
        var curTbl = getTableForRow(curRow);
        var newRow = curTbl.insertRow(curRow.rowIndex + 1);
        
        newRow.className = "expanded";
        /*newRow.innerHTML = request.responseText;*/
        var newCell = newRow.insertCell(0);
        newCell.colSpan = getTableWidth(this.cell);
        newCell.innerHTML = request.responseText;
    },
    
    ajaxCall: function() {
        var params = this.pushParams();
        var ajaxHelper = new net.ContentLoader(this, this.url, "GET", params);
        ajaxHelper.sendRequest();
    },
    
    pushParams: function() {
        var params = [];
        return params;
    },
    
    expand: function() {
        var tcell = this.cell;
        var curRow = getRowForCell(tcell);
        var isSelected = hasClass(tcell, "selectedCell");
        
        if (isSelected) {
            this.cell.className = this.cell.className.replace("selectedCell", "");
            var nextRow = getNextRow(curRow);
            if (hasClass(nextRow, "expanded"))
                nextRow.style.display = "none";
        }
        else {
            this.cell.className += " selectedCell";
            var nextRow = getNextRow(curRow);
            if (nextRow && hasClass(nextRow, "expanded")) {
                nextRow.style.display = "table-row";
            }
            else {
                this.ajaxCall();
            }
        }
    }
}

GUI.OligoCell = function(oligoID, cell) {
    this.oligoID = oligoID;
    this.cell = cell;
    this.url = "servlet/OligoInfoServlet";
    this.width = -1;
}
GUI.OligoCell.prototype = new GUI.ExpandTableCell();
GUI.OligoCell.prototype.pushParams = function() {
    var params = [];
    params.push("oligoID=" + this.oligoID);
    return params;
}

GUI.PWFisherCell = function(pathwayID, cell) {
    this.pathwayID = pathwayID;
    this.cell = cell;
    this.url = "servlet/PWFisherInfoServlet";
    this.width = -1;
}
GUI.PWFisherCell.prototype = new GUI.ExpandTableCell();
GUI.PWFisherCell.prototype.pushParams = function() {
    var params = [];
    params.push("pathway=" + this.pathwayID);
    return params;
}

GUI.PWGlobalCell = function(pathwayID, cell) {
    this.pathwayID = pathwayID;
    this.cell = cell;
    this.url = "servlet/PWGlobalInfoServlet";
    this.width = -1;
}
GUI.PWGlobalCell.prototype = new GUI.ExpandTableCell();
GUI.PWGlobalCell.prototype.pushParams = function() {
    var params = [];
    params.push("pathway=" + this.pathwayID);
    return params;
}

function oligoCellEventHandler(event) {
    var oligoCell = this.oligoCell;
    if (oligoCell) {
        oligoCell.expand();
    }
}

function attachOligoCells() {
    //launchDebugger();
    var tbl = document.getElementById("search");
    if (tbl) {
        var nodeRetriever = new NodeRetriever(tbl, "TD");
        var ocells = nodeRetriever.getNodes();
        for (var i = 0; i < ocells.length; i++) {
            var cell = ocells[i];
            if (hasClass(cell, "oligoCell")) {
                // FIX THIS - should walk the cell node
                var oid = cell.innerHTML;
                cell.oligoCell = new GUI.OligoCell(oid, cell);
                cell.onclick = oligoCellEventHandler;
            }
        }
    }
}

function pwFisherCellEventHandler(event) {
    var pwFisherCell = this.pwFisherCell;
    if (pwFisherCell) {
        pwFisherCell.expand();
    }
}
function attachPWFisherCells() {
    //launchDebugger();
    var tbl = document.getElementById("search");
    if (tbl) {
        var nodeRetriever = new NodeRetriever(tbl, "TD");
        var pwcells = nodeRetriever.getNodes();
        for (var i = 0; i < pwcells.length; i++) {
            var cell = pwcells[i];
            if (hasClass(cell, "pwFisherCell")) {
                var pid = cell.innerHTML;
                cell.pwFisherCell = new GUI.PWFisherCell(pid, cell);
                cell.onclick = pwFisherCellEventHandler;
            }
        }
    }
}

function pwGlobalCellEventHandler(event) {
    var pwGlobalCell = this.pwGlobalCell;
    if (pwGlobalCell) {
        pwGlobalCell.expand();
    }
}

function attachPWGlobalCells() {
    var tbl = document.getElementById("global");
    if (tbl) {
        var nodeRetriever = new NodeRetriever(tbl, "TD");
        var pwcells = nodeRetriever.getNodes();
        for (var i = 0; i < pwcells.length; i++) {
            var cell = pwcells[i];
            if (hasClass(cell, "pwGlobalCell")) {
                var pid = cell.innerHTML;
                cell.pwGlobalCell = new GUI.PWGlobalCell(pid, cell);
                cell.onclick = pwGlobalCellEventHandler;
            }
        }
    }
}


/* DEBUGGER */

var debug = new Object();
debug.Debugger = function() {
    this.newWin = window.open("", "_blank", "height=600, left=835, width=600, top=200, scrollbars=yes");
    this.doc = this.newWin.document;
    this.doc.open("text/plain", "replace");
}

debug.Debugger.prototype = {
    
    write: function(text) {
        this.doc.writeln(text);
    },
    
    close: function() {
        this.doc.close();
        this.newWin.close();
    }
}

function launchDebugger() {
    dbg = new debug.Debugger();
    dbg.write("Debugger launched");
}

function closeDebugger() {
    dbg.close();
}



/* OLD CRIPE */
var urlarr = new Array();
urlarr[1] = './rootTip.html';
urlarr[2] = './radicalEpiblastColeoptile.html';
urlarr[3] = './rootTip.html';
urlarr[4] = './rootTip.html';
urlarr[5] = './riceshoot.html';
urlarr[6] = './riceshoot.html';
urlarr[7] = './riceshoot.html';

function getTissue(o) {
    if (o >= 1 && o < 8) {
        return "Click For Image";
    }
    else {
        return "Image Not Available";
    }
}

function showTissue(o) {
    if (o >= 1 && o < 8) {
        var url = urlarr[o];
        window.open(url, '_tissue', 'resizable,dependent,width=740,height=680');
    }
}

function showOntology(o, t) {
    window.open('showOntology.jsp?cellType=' + o + '&ontologyType=' + t, 
    '_ontology', 'resizable,scrollbars=yes,dependent,width=740,height=600');
}

function showOligoInfo(o) {
    window.open('oligoInfo.jsp?id=' + o, '_oligo', 
    'resizable,scrollbars=yes,dependent,width=540,height=360');
}

function showPath(id) {
    if (id == 'all') {
        alert('Please select a pathway.');
    }
    else {
        window.open('imgs/' + id + '.jpg', '_path', 
        'resizable,dependent,width=700,height=600,scrollbars=yes');
    }
}

function toggle(id) {
    ul = "ul_" + id;
    img = "img_" + id;
    ulElement = document.getElementById(ul);
    imgElement = document.getElementById(img);
    
    if (ulElement) {
        if (ulElement.className == 'closed') {
            ulElement.className = "open";
            imgElement.src = "images/open.png";
        }
        else {
            ulElement.className = "closed";
            imgElement.src = "images/closed.png";
        }
    }
    
    
}
function setPicture(name) {
    diag = document.getElementById("diagram1");
    if(diag) {
        diag.src = "images/" + name + ".jpg";
    }
}
function handleLayer(o) {
    var a = document.getElementById("aLayer").style;
    if (o == 'PN') {
        a.visibility = 'visible';
        a.display = 'block';
        
    }
    else {
        a.visibility = 'hidden';
        a.display = 'none';
    }
}

function highlight_column_head(name, location, sortType) {
    var target = document.getElementById(name + '-select-div');
    target.style.backgroundImage = 'url(images/srt_' + sortType + '_hl.jpg)';
    var tgh = document.getElementById(name + '-select-head');
    tgh.style.backgroundImage = 'url(images/rc-title-hl-bg.png)';
    
    if (location == 'leftmost') {
         var tgtheader = document.getElementById(name + '-ch-outer');
         tgtheader.style.backgroundImage = 'url(images/rc-title-hl.png)';
         tgtheader.style.backgroundRepeat = 'no-repeat';
         tgtheader.style.backgroundPosition = 'top left';
     }
    else if (location == 'rightmost') {
        var tgtheader = document.getElementById(name + '-ch-outer');
        tgtheader.style.backgroundImage = 'url(images/rc-title-hl.png)';
        tgtheader.style.backgroundRepeat = 'no-repeat';
        tgtheader.style.backgroundPosition = 'top right';
    }
}

function unhighlight_column_head(name, location, sortType) {
    var target = document.getElementById(name + '-select-div');
    target.style.backgroundImage = 'url(images/srt_' + sortType + '.jpg)';
    var tgh = document.getElementById(name + '-select-head');
    tgh.style.backgroundImage = 'url(images/rc-title-bg.png)';
    
    if (location == 'leftmost') {
        var tgtheader = document.getElementById(name + '-ch-outer');
        tgtheader.style.backgroundImage = 'url(images/rc-title.png)';
         tgtheader.style.backgroundRepeat = 'no-repeat';
         tgtheader.style.backgroundPosition = 'top left';
    }
    else if (location == 'rightmost') {
        var tgtheader = document.getElementById(name + '-ch-outer');
        tgtheader.style.backgroundImage = 'url(images/rc-title.png)';
        tgtheader.style.backgroundRepeat = 'no-repeat';
        tgtheader.style.backgroundPosition = 'top right';
    }
}