function getAllDistinctCategories(rr)
{
	var cats = new Array();
	var exists = false;
	for(var r=0; r<rr.length; r++)
	{
		if(cats.length!=0)
		{
			for(var i=0; i<cats.length; i++)
			{
				if(cats[i] == rr[r][1])
					exists = true;
			}
		}
		if(!exists)
			cats[cats.length] = rr[r][1];
			
		exists = false;
	}
	return cats;
}
function getItems(rr, cat)
{
	var e = new Array();
	for(var i = 0; i<rr.length; i++)
	{
		if(rr[i][1]==cat)
			e[e.length] = {title:rr[i][0], url:rr[i][2]};
	}
	return e;				
}

function transform(rr){
	var categories = getAllDistinctCategories(rr);
	var resources = new Array();
	resources["categories"] = new Array();
	for(var i=0; i<categories.length; i++)
	{
		resources["categories"][i] = {name:categories[i],items:getItems(rr, categories[i])};
	}
	return resources;
}
function display()
{
	var e = getElement("relatedResources");
	var s = "";
	for(var i=0; i<relatedResources.categories.length; i++)
	{
		s+="<div style=\"padding:3px;\">";
		
		s+="<span style=\"font-weight:bold;\">"+relatedResources.categories[i].name+"</span><br />";
		for(var j=0; j<relatedResources.categories[i].items.length; j++)
		{
			if(j!=0)
				s+="<p>"+relatedResources.categories[i].items[j].title+"<br /><a href\""+relatedResources.categories[i].items[j].url+"\">Read More</a></p>";
			else
				s+=relatedResources.categories[i].items[j].title+"<br /><a href\""+relatedResources.categories[i].items[j].url+"\">Read More</a>";
		}		
		s+="</div>";
	}
	e.innerHTML = s;
}
function changetab(e, cat)
{
	var tf = document.getElementById("tabfooter");
	tf.style.backgroundColor = e.style.backgroundColor;
	var tbl = document.getElementById("tbl"+cat);
	tbl.style.borderColor = e.style.backgroundColor;
	var ic = document.getElementById("itemContainer");
	for(var i=0; i<ic.childNodes.length; i++)
		if(ic.childNodes[i].tagName == "TABLE")
			ic.childNodes[i].style.display = "none";
	tbl.style.display = "";
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}
function isExternal(url)
{
	var external = false;
	var prefixes = ["http://", "ftp://", "https://", "sftp://"];
	for(var a=0; a<prefixes.length; a++)
	{
		if(url.indexOf(prefixes[a])!=-1)
		{
			external = true;
			break;
		}
	}
	return external;
}
function cookie(n)
{
	this.name = n;
	this.value = "";
	this.expires = "";
	this.set = function(value, expires)
	{
		var ex = "";
		if (expires && expires != "")
		{
			var date = new Date();
			date.setTime(date.getTime()+(expires*24*60*60*1000));
			ex = "; expires="+date.toGMTString();
		}
		this.value = value;
		this.expires = ex;
		document.cookie = this.name+"="+this.value+this.expires+"; path=/";
	};
	this.erase = function()
	{
		createCookie(this.name,"",-1);
	};
	this.get = function() {
		if (document.cookie != "") 
		{
			var thisCookie = document.cookie.split("; ");
			for (i=0; i<thisCookie.length; i++) {
				if (this.name == thisCookie[i].split("=")[0]) {
					this.value = thisCookie[i].split("=")[1];
				}
			}
			if(this.value!="")
			{
				return this.value;
			}
			else
				return null;
		}
		else
			return null;
	};
}
function getAvailable(arr)
{
	var temp = new Array();
	for(var i=0; i<arr.length; i++)
	{
		if(!arr[i].selected) temp[temp.length] = arr[i];			
	}
	return temp;
}
function getFeature(pos, all)
{
	var available = getAvailable(all);
	if(pos.length > 0 || available.length > 0)
	{
		var sectionL = (pos.length)?pos.length:0;
		var allL = (available.length)?available.length:0;
		var i =  Math.floor(Math.random()*(sectionL + allL));
		if(i<(pos.length))
			return pos[i];
		else
		{
			available[i-pos.length].selected = true;
			return available[i-pos.length];
		}
	}
	else
		return null;
}
function nbInit()
{
	if(getElement("imgRotating"))
	{
		getElement("imgRotating").src = rbi[0];
		setTimeout("nextItem('imgRotating')", 3000);
	}
}
var nbc = 0;
function nextItem(id)
{
	/* older ie's wont handle fading, so were just going to do basic image src swapping */
	if(rbi.length > 1)
	{
		nbc++;
		var c = getElement(id);
		c.src = rbi[nbc];	
		if(nbc==(rbi.length-1))
			nbc=-1;
		setTimeout("nextItem('imgRotating')", 3000);
	}	
}
function setValue(e, strDefault)
{
	if(e.value == strDefault)
	{
		e.value = "";
		e.style.color = "#333333";
	}
}
function resetValue(e, strDefault)
{
	if(e.value == "")
	{
		e.value = strDefault;
		e.style.color = "#999999";
	}
}
document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    
    if (!currentContext[0]){
    	return;
    }
    
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}
