var msIE=false;          //true when client is Internet Explorer

// Example use: var match = reURL.exec(string);
// match[1] -- host protocol
// match[2] -- host:port
// match[3] -- URL
// match[5] -- Query
var reURL = new RegExp("^(https?)://([^/]+)(/[^\\?]+(\\?(.*))?)$");

// BrowserDetect code from http://www.quirksmode.org/js/detect.html
// This seems more reliable.
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{	// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 	// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
if (BrowserDetect.browser == "Explorer") {
    msIE = true;
}

/*
 * Positions list column header (first row) at the top of the list when scrolled. IE only. 
 */
function doListScroll() {
    try {
        var oList=event.srcElement, oHead=oList.all.tags("TR")[0];
        oHead.style.top = oList.scrollTop;
    }catch(e) {}
}

/*
 * Enables keyboard scrolling of lists for Mozilla. 
 */
function doKeyDown(e) {
    var k=e.keyCode, oSource=e.target, sTag=oSource.tagName;
    var oScrollDiv=document.getElementById("list");
    if (!oScrollDiv) {
        oScrollDiv=document.getElementById("codeBrowser");
    }
    if (!oScrollDiv) {
        oScrollDiv=document.getElementById("homeBody");
    }
    
    if (sTag=="SELECT" || (sTag=="INPUT" && oSource.type!="checkbox")) {
        return;
    }
    if (k==40) {       //down arrow
        oScrollDiv.scrollTop += 40;
    }else if(k==38) { //up arrow
        oScrollDiv.scrollTop -= 40;
    }else if(k==37) { //left arrow
        oScrollDiv.scrollLeft -= 40;
    }else if(k==39) { //right arrow
        oScrollDiv.scrollLeft += 40;
        e.preventDefault();  //try to prevent Mozilla from scrolling the entire page but doesn't seem to work
    }else if(k==33) { //page up
        oScrollDiv.scrollTop -= 240;
    }else if(k==34) { //page down
        oScrollDiv.scrollTop += 240;
    }
}

/*
 * Hides/shows the left panel
 */
function hidePanel() {
    var oLeftPanel=document.getElementById("leftPanel");
    var oMargin=document.getElementById("panelMargin");
    var oImg=document.getElementById("panelBtn");
    
    if (oLeftPanel.offsetWidth>50) {
        oLeftPanel.style.width="15px";
        oMargin.style.visibility="hidden";
        oImg.src="images/Panel_Open.png";
        oImg.title="Show Panel";
        oImg.align="";
        oImg.alt=">";
    }else {
        oLeftPanel.style.width="170px";
        oMargin.style.visibility="visible";
        oImg.src="images/Panel_Close.png";
        oImg.title="Hide Panel";
        oImg.align="right";
        oImg.alt="<";
    }
    doResize();
}

/*
 * Save report function
 */
function saveReport() {
    var sPath=prompt("Save Report As", "report_name");
    var oList=document.getElementById("lstQuickLinks");
    var oOption=document.createElement("OPTION");
    var coll=oList.getElementsByTagName("OPTION");
    var n=coll.length, i;
    if (sPath) {
        for (i=0; i<n; i++) {
            if (coll[i].text.toLowerCase()==sPath.toLowerCase()) {
                alert("The report '" + sPath + "' already exists.\n\nPlease enter a unique name for this report.");
                saveReport();
                return;
            }
        }
        oOption.text=sPath;
        if (msIE) {
            oList.options.add(oOption);
        }else {
            oList.appendChild(oOption);
        }
    }
}

/*
 * For edit query pages, fired when the Query For drop-down list box selection changes
 *
 * SGM 2006-07-28: This function is only used by the mockups; the real
 * Edit Query page uses 'activeDropdownChanged', below.
 */
function selectQuery(base) {
    var oList=document.getElementById("lstQueryFor");
    var sURL = base + "_" + oList.value + ".html";
    document.location.href=sURL;
}


// control reaction: called when an active drop-down is modified;
// previously, I was using a per-element onclick event, which is valid
// according to the HTML spec, but does not work in IE; so now, we
// use a handler for the entire control
function activeDropdownChanged(listID) {
    var oList = document.getElementById(listID);
                      
    // ignore items that have an empty value attribute, for example
    // the blank item at the top of the Quick Links dropdown
    if (oList.value) {
        // the dest URL is given by the value; sort of surprising that
        // this works, even in IE!
		var match = reURL.exec(document.location.href);
        if (match[3] == oList.value) {
            document.location.reload(true);
        }
        document.location.href = oList.value;
    }
}

// same thing as activeDropdownChanged
function activeCheckboxChanged(chkID) {
    var oList = document.getElementById(chkID);
                      
    if (oList.value) {
        document.location.href = oList.value;
    }
}

/*
 * Toggles all checkboxes, as used by the "Select All" button.
 * Initially sets all checkboxes and thereafter alternates between
 * selecting and unselecting all checkboxes.
 *
 * AKB 2006-07-30: Moved here from Defects|Individual template.
 * Also added the Select/Unselect toggling.
 */
function checkAll(flag) {
    // this was for the checkbox in the header column
    //var flag=document.getElementById("chkSelectAll").checked;
    //
    // but now we use a pushbutton

    var coll=document.getElementsByTagName("INPUT");
    var n=coll.length, i;
    
    for (i=0; i<n; i++) {
        if (coll[i].type=="checkbox" && !coll[i].disabled) {
            coll[i].checked=flag;
        }
    }
}

/*
 * Checks that at least one checkbox on the form has been selected.
 */
function hasCheckedAny() {
    var coll=document.getElementsByTagName("INPUT");
    var n=coll.length, i;
    
    for (i=0; i<n; i++) {
        if (coll[i].type == "checkbox" && coll[i].checked == true) {
            return true;
        }
    }
	return false;
}


// ------------------------- for atest ---------------------------
// find a button, given its label text; this assumes we only use
// <input> elements, as per DR 4534
function findButtonByLabel(label) {
    // NOTE: This function is not standard, but is implemented in
    // at least Mozilla, FF and IE.
    var coll = document.getElementsByTagName("INPUT");

    var n = coll.length, i;
    for (i=0; i < n; i++) {
        if (coll[i].type == "submit" && coll[i].value == label) {
            return coll[i];
        }
    }

    return null;     // not found
}


function findCheckboxByNameAndValue(name, value) {
    var coll = document.getElementsByTagName("INPUT");

    var n = coll.length, i;
    for (i=0; i < n; i++) {
        if (coll[i].type == "checkbox"
            && coll[i].name == name
            && coll[i].value == value) {
            return coll[i];
        }
    }

    return null;     // not found
}


// find a 'tagName' element that is in a table cell where the
// preceding cell has 'label' as its text
function findLabeledElement(label, tagName) {
    return findLabeledElementDFS(document.body, label, tagName);
}

function findLabeledElementDFS(node, label, tagName) {
    if (node.tagName == "TABLE") {
        var v = findLabeledElementInTable(node, label, tagName);
        if (v) {
            return v;
        }
    }

    var coll = node.childNodes;
    var n = coll.length, i;
    for (i=0; i < n; i++) {
        var v = findLabeledElementDFS(coll[i], label, tagName);
        if (v) {
            return v;
        }
    }

    return null;
}

function findLabeledElementInTable(table, label, tagName) {
    var i,j;
    for (i=0; i < table.rows.length; i++) {
        var r = table.rows[i];

        // true if the preceding cell in this row has text that
        // matches the label
        var prevMatchedLabel = false;

        for (j=0; j < r.cells.length; j++) {
            var c = r.cells[j];

            if (prevMatchedLabel) {
                // look for an <input> child
                for (k=0; k < c.childNodes.length; k++) {
                    if (c.childNodes[k].tagName == tagName) {
                        return c.childNodes[k];
                    }
                }
            }

            // test for match rather than exact equality so we don't
            // get fooled by extra whiltespace, hyperlinks, etc.
            if (RegExp(label).test(c.innerHTML)) {
                prevMatchedLabel = true;
            }
        }
    }
    return null;
}

function findLabeledInput(label) {
    return findLabeledElement(label, "INPUT");
}


// return the *string* that is selected in a dropdown
function getDropdownSelString(dd) {
    return dd.options[dd.selectedIndex].text;
}


// return all of the option texts, in order, comma-separated
function getDropdownOptions(dd) {
    var ret = "";

    var i;
    for (i=0; i < dd.options.length; i++) {
        if (i > 0) {
            ret += ",";
        }
        ret += dd.options[i].text;
    }
    
    return ret;
}


// see if there is any paragraph containing 'innerHTML' that matches
// the given text regex pattern
function findElementWithMatchingText(tag, pattern) {
    var coll = document.getElementsByTagName(tag);
    var i;
    var r = RegExp(pattern);
    for (i=0; i < coll.length; i++) {
        if (r.test(coll[i].innerHTML)) {
            return coll[i];
        }
    }
    return null;
}


function hasParagraphMatching(pattern) {
    return findElementWithMatchingText("P", pattern)? true : false;
}

function hasPreMatching(pattern) {
    return findElementWithMatchingText("PRE", pattern)? true : false;
}


function getNamedLinkTarget(pattern) {
    var a = findElementWithMatchingText("A", pattern);
    if (!a) {
        return null;
    }
    return a.href;
}

function openHelpFocus(lnk) {
	newwindow=window.open(lnk,'name');
	if (window.focus) {
            newwindow.resizeTo(Math.min(screen.width, 900),Math.min(screen.height-50,840));           
            newwindow.focus();
        }
	return false;
}

function trimWS(str) { 
   return str.replace(/^\s*|\s*$/g,'');
}

// EOF

