 // This library will provide core functionality 
// for common javascript behaviors and functions 
// on the USN site

addLoadEvent(sfHover);
/**********FACEBOOK AND DELICIOUS LINKING ***/
function fbs_click() {
	var u=location.href;
	var t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}
function dls_click() {
	var url=encodeURI(location.href);
	var title=encodeURI(document.title);
	var uri = 'http://del.icio.us/post?url='+url+'&title='+title;
	window.open(uri,'delicious','toolbar=0,status=0,width=626,height=436');
	return false;
}
/***************** AD/ANALYTICS ************/
// Double Click
var site = "Uncategorized";
var zone = "Uncategorized";
var citation = "none";
var source = "none";
var keys;
var path = document.location.pathname;
var dirsArr = path.split("/");
var ord = Math.round(10000000*Math.random())
while (ord.length<9){
	ord="0"+ord
}
var metaSet=false;
var tile = 0;
var adPositions = {
leaderboard1 : {name:'leaderboard1',dim:'728x90',vendor:'dblclick'},
leaderboardA : {name:'leaderboardA',dim:'728x90',vendor:'dblclick'},
leaderboardB : {name:'leaderboardB',dim:'420x75',vendor:'dblclick'},
left1 : {name:'left1',dim:'120x90',vendor:'usnews'},
left2 : {name:'left2',dim:'120x240',vendor:'dblclick'},
badge1 : {name:'badge1',dim:'120x90',vendor:'dblclick'},
badgeA : {name:'badgeA',dim:'120x90',vendor:'dblclick'},
badgeB : {name:'badgeB',dim:'120x50',vendor:'dblclick'},
badgeC : {name:'badgeC',dim:'120x50',vendor:'dblclick'},
badgeD : {name:'badgeD',dim:'120x50',vendor:'dblclick'},
right1 : {name:'right1',dim:'120x90',vendor:'dblclick'},
right2 : {name:'right2',dim:'160x600',vendor:'dblclick'},
right3 : {name:'right3',dim:'160x600',vendor:'google'},
rectangleA : {name:'rectangleA',dim:'300x250',vendor:'dblclick'},
rectangleB : {name:'rectangleB',dim:'120x240',vendor:'dblclick'},
rectangle1 : {name:'rectangle1',dim:'300x250',vendor:'dblclick'},
rectangle2 : {name:'rectangle2',dim:'300x250',vendor:'dblclick'},
interstitial: {name:'interstitial',dim:'600x400',vendor:'dblclick'},
skyscraperA: {name:'skyscraperA',dim:'160x600',vendor:'dblclick'},
video1: {name:'video1',dim:'468x60',vendor:'dblclick'}

}

function dblclick(pos)
{
        if (!metaSet)
                setMetaValues();
        var posObj = adPositions[pos];
        if (!posObj)
                return ''; // need better error handling
        var adSrc = getAdSrc(posObj);
        renderAd(adSrc,posObj);
}

function setMetaValues()
{
        var metas = document.getElementsByTagName('meta');
        for (var i=0; i < metas.length; i++) {
                if (metas[i].name == "keys") {
                        keys = eval(metas[i].content);
                }
                if (metas[i].name == "site")  site = metas[i].content;
                if (metas[i].name == "zone")  zone = metas[i].content;
	        if (metas[i].name == "citation")  citation = metas[i].content;
        	if (metas[i].name == "source")  source = metas[i].content;
        }
	//deduce site and zone from path
	// this should go in the header since DoubleClick needs this info too
	numdirs = dirsArr.length - 1;
	if (site == "none" && numdirs > 1) {
	        //file is at least 2 levels down
	        site = dirsArr[numdirs-2];
	        zone = dirsArr[numdirs-1];
	}else if(site == "none") {
	        //file is in the top directory
	        site = dirsArr[numdirs-1];
	}else if(zone == "none") {
	        //site was specified so take zone name as zone
	        zone = dirsArr[numdirs-1];
	}
        metaSet = true;
}

function getAdSrc(posObj)
{
        if (!posObj.vendor)
                return ''; 
        switch (posObj.vendor) {
                case 'dblclick':
                        return getDblClickSrc(posObj);
                case 'usnews':
                        return getUsnSrc(posObj);
                case 'google':
                        return getGoogleSrc(posObj);
                default:
                        return ''; 
        }
}

function getDblClickSrc (posObj)
{
        var sz = posObj.dim;
       
        var dbkeyval='';
	if (keys) {
        	for (var j=0; j < keys.length; j++) {
        	        var key = keys[j].key;
        	        var val = keys[j].val;
        	        dbkeyval += key+"="+val+";";
        	}
	}
        tile++;

	var dbksite = site.toLowerCase();
	var dbkzone = zone.toLowerCase();
	dbksite = dbksite.substring(dbksite.lastIndexOf(":")+1);
	dbksite = dbksite.replace(/[ '"\?\=]/g,"");
	dbkzone = dbkzone.replace(/[ '"\?\=]/g,"");
	//can't start with numbers  ?needs testing
	dbksite = dbksite.replace(/^[0-9]+/g,"");
	dbkzone = dbkzone.replace(/^[0-9]+/g,"");
	//64 chars max, incl usn.
	dbksite = dbksite.substring(0,60);
	//zone length restriction?
	dbkzone = dbkzone.substring(0,64);
	var returnArray = new Array;
	returnArray[0] = "http://ad.doubleclick.net/adj/usn.";
	returnArray[1] = dbksite;
	returnArray[2] = "/";
	returnArray[3] = dbkzone;
	returnArray[4] = ";sz="
	returnArray[5] = sz;
	returnArray[6] = ";ptile=";
	returnArray[7] = tile;
	returnArray[8] = ";pos=";
	returnArray[9] = posObj.name;
	returnArray[10] = ";";
	returnArray[11] = dbkeyval;
	returnArray[12] = "ord=";
	returnArray[13] = ord;
	returnArray[14] = ";dcopt=ist;";	
	returnArray[15] = "?";
	return returnArray.join('');
	

}

function getUsnSrc (posObj)
{
        return '/usnews/biz/scripts/usn_house_ad.js';
}

function getGoogleSrc (posObj)
{
        google_ad_client = "pub-6095852326547760";
		google_ad_width = 160;
		google_ad_height = 600;
		google_ad_format = "160x600_as";
		google_ad_channel ="";
		google_ad_type = "text";
		google_color_border = "FFFFFF";
		google_color_bg = "FFFFFF";
		google_color_link = "B90000";
		google_color_url = "006699";
		google_color_text = "000000";
		return 'http://pagead2.googlesyndication.com/pagead/show_ads.js';

}

function renderAd (adSrc, posObj)
{
        document.write("<script type=\"text/javascript\" src=\""+adSrc+"\"><\/script>");

} 
//INTERSTITIAL AD CODE
function cookieTest() {
	var expy = new Date();
	expy.setTime(expy.getTime()+(5*60*1000));
	document.cookie = "Interstitial=False; expires=" + expy.toGMTString() + "; path=/";
	var testCookie = document.cookie;
    var index = testCookie.indexOf("Interstitial=");
   	if (index == -1){
		return false;
	} else {
   		index = testCookie.indexOf("=", index) + 1;
   		var endstr = testCookie.indexOf(";", index);
   		if (endstr == -1) endstr = testCookie.length;
		if (unescape(testCookie.substring(index, endstr)) == 'False'){
			return true;
		}
	}
}

function Interstitial() {
	var monster = document.cookie;
    var index = monster.indexOf("Interstitial=");
	if (document.referrer.indexOf('yahoo') != -1) {
		return false;
	}
	if (document.referrer.indexOf('google') != -1) {
		return false;
	}
	if (index == -1){
		if (cookieTest()) {
			var expy = new Date();
			expy.setTime(expy.getTime()+(24*60*60*1000));
			document.cookie = "Interstitial=False; expires=" + expy.toGMTString() + "; path=/"
			return true;
		} else {
			return false;
		}
	} else {
	    index = monster.indexOf("=", index) + 1;
    	var endstr = monster.indexOf(";", index);
		if (endstr == -1) endstr = monster.length;
		if (unescape(monster.substring(index, endstr)) == 'True'){
			return false;
		} else {
			return true;
		}
	}
}

if (window.RegExp) {
	var reg = /([0-9][0-9])([0-9][0-9])([0-9][0-9])/;
	var urlDate;
	if (urlDate = reg.exec(window.location)) {
		var issueYear = RegExp.$1;
		issueYear = (issueYear >= 90) ? '19' + issueYear : '20' + issueYear
		var issueMonth = RegExp.$2 - 1;
		var issueDay = RegExp.$3;
		var curDate = new Date();
		var issueDate = new Date(issueYear, issueMonth, issueDay);
		issueDate.setTime(issueDate.getTime() + (1000 * 60 * 60 * 24 * 7));
		if (curDate > issueDate) {
			if (!title) {
				if (document.title) {
					var title = document.title;
					var new_loc;
					var reg = /usnews.com: /i;
					if (new_loc = reg.exec(title)) title = title.substring(new_loc.index + 12);
					var reg = /(\([0-9][0-9]\/[0-9][0-9]\/[0-9][0-9]\))/;
					if (new_loc = reg.exec(title)) title = title.substring(0, new_loc.index - 1);
				} else {
					var title = '';
				}
			}
			title = escape(title).replace(/\+/g, '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27');
			//yj commented for Bridget Feb23 07
			//if (Interstitial()) window.location.href = "/usnews/biz/interstitials/int.php?title=" + title + "&pageURL=" + location.href;
		}
	}
}



/* PREMIUM COLLEGE AND GRAD FUNCTIONS */ 

function getCookie(name) {
	var cstring = document.cookie;
	var index = cstring.indexOf(name + "=");
	if (index == -1) return null;
	index = cstring.indexOf("=", index) + 1;
	var endstr = cstring.indexOf(";", index);
	if (endstr == -1) endstr = cstring.length;
	return unescape(cstring.substring(index, endstr));
}

function nameMap(disc) {
	if (disc == "MBA") {discipline = "business school";}
	if (disc == "EDU") {discipline = "education school";}
	if (disc == "ENG") {discipline = "engineering school";}
	if (disc == "MED") {discipline = "medical school";}
	if (disc == "LAW") {discipline = "law school";}
	return discipline;
}

function mySchoolsText(disc,linkClass) {
	var text = "";
	if(getCookie("my")) {
		var discs = getCookie("my").split(":");
		var schoolsexist = 0;
  		for(i=0;i<discs.length;i++) {
			var toks = discs[i].split("-");	
			if (toks[0] == disc) {
				var discipline = nameMap(disc);
				if (toks[1] > 1) {discipline+="s";}
				text += 'You have ' + toks[1] + ' ' + discipline + ' stored in <a href="/servlets/myschools.jsp" class="' + linkClass + '">My Schools</a>. Review or update your list <a href="/servlets/myschools.jsp" class="' + linkClass + '">here</a>.';	
				text += "<br>";
				schoolsexist = 1;
			}
		}
		if (schoolsexist == 0) {
			discipline = nameMap(disc);
			discipline += "s";
			var l_disc = disc.toLowerCase();
			var dir_link = "/usnews/edu/grad/directory/dir-" + l_disc + "/dir" + l_disc + "index.php";
			var search_link = "/usnews/edu/grad/tools/premium/" + l_disc + "_srch_advanced.php";
			text += 'You have no ' + discipline + ' saved. Use the <a href="' + search_link + '" class="' + linkClass + '">School Search</a> or the <a href="' + dir_link + '" class="' + linkClass + '">A-Z Directory</a> to find and add schools.';
			text += ' ';
			text += '<br>';
		}
	} else {
		text = 'We are unable to access your saved schools at this time. Please visit <a href="/servlets/myschools.jsp" class="' + linkClass + '">My Schools</a> to review your list.';
	}
	return text;
}

function MM_preloadImages() { //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

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_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/**************** USN GUI ********************/

// This function makes the USN navbar menus work in IE
// This code is only required for legacy version of the header (v2 or lower)
function sfHover() {
	if (!document.getElementById("primaryNav")) return;
	var sfEls = document.getElementById("primaryNav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
// Poll pop-up code
function popUpWindow(mode) {
	var pollId,optionId,expiration;
	pollId = document.pollForm.pollId.value;
	expiration = document.pollForm.expiration.value;	
	var opt = document.pollForm.pollOption;
	for (var i=0; i < opt.length;i++) {
		if (opt[i].checked) {
			optionId = opt[i].value;
			opt[i].checked = false;
		}
	}	
	if (mode == 'nv') {
		optionId = '';
	}
	window.open("http://"+location.hostname+"/poll/pollResults.php3?pollId="+pollId+"&optionId="+optionId+"&expiration="+expiration,"poll","scrollbars=0,resizable=0,width=500,height=350");
	return false;
}

//Photo gallery popup code
function gallery_popup()
{
	var url = this.href
	newwindow=window.open(url,'name','height=685,width=850');
	if (window.focus) {newwindow.focus()}
	return false;
}
/************ EVENT HANDLING ******************/

// This function registers multiple function to the onload event
// @param func is the name of a function you wish to register to the onload event.
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
/************ REMOTE DATA ACCESS ******************/
// This library provides the core functionality 
// for acquiring html, xml and javascript data from 
// sites outside the usnews domain. 
// ***********************************************
// This libarary uses (a modified version of) 
// Protoype Framework v1.4.0.
// located here: http://prototype.conio.net/
/*
* @param href	location of data
* @param type	type of data (js, html, xml)
* @param onError what do on failure ("nothing" or null string, "debug" or custom function)
* @param target (optional) ID of a container in which to insert acquired data
*/

function data(href, type, onError) {
	this.handlerURL = 'http://'+window.location.hostname+'/usnews/general_ssi/scripts/libraries/remoteDataAccess.php?href=';
	this.originalHref = href;
	this.href = this.handlerURL+href;
	this.type = type;
	this.onError = onError;
	if (arguments.length > 3) {
		this.target = arguments[3];
	}
}

connection=data.prototype;
connection.acquire=function() {
	if (!connection.test()) { 
		connection.failure();
	}
	else{
		connection.target = this.target;
		connection.failure = this.failure;
		connection.originalHref = this.originalHref
		var dataHandler;
		switch (this.type) {
			case "js":
				dataHandler = connection.handleJS;
				break;
			case "xml":
				dataHandler = connection.handleXML;
				break;
			case "html":
				dataHandler = connection.handleHTML;
				break;
			default:
				dataHandler = connection.failure;
				break;
		}
			var request = new Ajax.Request(
				this.href,
				{method: 'get', onComplete: dataHandler, onFailure: connection.failure}
			);
	}
}
// Make sure Ajax is available to user
connection.test = function() {
	try {
		xmlhttp = window.XMLHttpRequest?new XMLHttpRequest():
		new ActiveXObject("Microsoft.XMLHTTP");
	}
	catch (e) {
		return false;
	}
	return true;
}
connection.failure = function() {
	
}
connection.handleJS = function(request) {
	if (connection.target) {
		document.write = function(text) {
			$(connection.target).innerHTML = text;
		}
		eval(request.responseText)
	}
	else { alert("please specify a target.") }
	
}
connection.handleXML = function(request) {
	alert(request.responseText);
}

connection.handleHTML = function(request) {
	if (connection.target) {$(connection.target).innerHTML = request.responseText;	}
	else { alert("please specify a target.") }
}




/************ PROTOTYPE FRAMEWORK ******************/
// Don't modify below this line.
// ***********************************************
/*  Prototype JavaScript framework, version 1.4.0
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.4.0',
  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',

  emptyFunction: function() {},
  K: function(x) {return x}
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.inspect = function(object) {
  try {
    if (object == undefined) return 'undefined';
    if (object == null) return 'null';
    return object.inspect ? object.inspect() : object.toString();
  } catch (e) {
    if (e instanceof RangeError) return '...';
    throw e;
  }
}

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this;
  return function(event) {
    return __method.call(object, event || window.event);
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback();
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}

/*--------------------------------------------------------------------------*/

function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1)
      return element;

    elements.push(element);
  }

  return elements;
}
Object.extend(String.prototype, {
  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(eval);
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
  },

  toQueryParams: function() {
    var pairs = this.match(/^\??(.*)$/)[1].split('&');
    return pairs.inject({}, function(params, pairString) {
      var pair = pairString.split('=');
      params[pair[0]] = pair[1];
      return params;
    });
  },

  toArray: function() {
    return this.split('');
  },

  camelize: function() {
    var oStringList = this.split('-');
    if (oStringList.length == 1) return oStringList[0];

    var camelizedString = this.indexOf('-') == 0
      ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
      : oStringList[0];

    for (var i = 1, len = oStringList.length; i < len; i++) {
      var s = oStringList[i];
      camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
    }

    return camelizedString;
  },

  inspect: function() {
    return "'" + this.replace('\\', '\\\\').replace("'", '\\\'') + "'";
  }
});

String.prototype.parseQuery = String.prototype.toQueryParams;

var $break    = new Object();
var $continue = new Object();

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },

  detect: function (iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.collect(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (value >= (result || value))
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (value <= (result || value))
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.collect(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.collect(Prototype.K);
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      iterator(value = collections.pluck(index));
      return value;
    });
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}

Object.extend(Array.prototype, Enumerable);

Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0; i < this.length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != undefined || value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0; i < this.length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  shift: function() {
    var result = this[0];
    for (var i = 0; i < this.length - 1; i++)
      this[i] = this[i + 1];
    this.length--;
    return result;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});
var Hash = {
  _each: function(iterator) {
    for (key in this) {
      var value = this[key];
      if (typeof value == 'function') continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject($H(this), function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  toQueryString: function() {
    return this.map(function(pair) {
      return pair.map(encodeURIComponent).join('=');
    }).join('&');
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  }
}

function $H(object) {
  var hash = Object.extend({}, object || {});
  Object.extend(hash, Enumerable);
  Object.extend(hash, Hash);
  return hash;
}
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    do {
      iterator(value);
      value = value.succ();
    } while (this.include(value));
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
    ) || false; 
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responderToAdd) {
    if (!this.include(responderToAdd))
      this.responders.push(responderToAdd);
  },

  unregister: function(responderToRemove) {
    this.responders = this.responders.without(responderToRemove);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (responder[callback] && typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },

  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      parameters:   ''
    }
    Object.extend(this.options, options || {});
  },

  responseIsSuccess: function() {
    return this.transport.status == undefined
        || this.transport.status == 0
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  responseIsFailure: function() {
    return !this.responseIsSuccess();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    var parameters = this.options.parameters || '';
    if (parameters.length > 0) parameters += '&_=';

    try {
      this.url = url;
      if (this.options.method == 'get' && parameters.length > 0)
        this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;

      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.options.method, this.url,
        this.options.asynchronous);

      if (this.options.asynchronous) {
        this.transport.onreadystatechange = this.onStateChange.bind(this);
        setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
      }

      this.setRequestHeaders();

      var body = this.options.postBody ? this.options.postBody : parameters;
      this.transport.send(this.options.method == 'post' ? body : null);

    } catch (e) {
      this.dispatchException(e);
    }
  },

  setRequestHeaders: function() {
    var requestHeaders =
      ['X-Requested-With', 'XMLHttpRequest',
       'X-Prototype-Version', Prototype.Version];

    if (this.options.method == 'post') {
      requestHeaders.push('Content-type',
        'application/x-www-form-urlencoded');

      /* Force "Connection: close" for Mozilla browsers to work around
       * a bug where XMLHttpReqeuest sends an incorrect Content-length
       * header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType)
        requestHeaders.push('Connection', 'close');
    }

    if (this.options.requestHeaders)
      requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);

    for (var i = 0; i < requestHeaders.length; i += 2)
      this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState != 1)
      this.respondToReadyState(this.transport.readyState);
  },

  header: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) {}
  },

  evalJSON: function() {
    try {
      return eval(this.header('X-JSON'));
    } catch (e) {}
  },

  evalResponse: function() {
    try {
      return eval(this.transport.responseText);
    } catch (e) {
      this.dispatchException(e);
    }
  },

  respondToReadyState: function(readyState) {
    var event = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (event == 'Complete') {
      try {
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      if ((this.header('Content-type') || '').match(/^text\/javascript/i))
        this.evalResponse();
    }

    try {
      (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + event, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
    if (event == 'Complete')
      this.transport.onreadystatechange = Prototype.emptyFunction;
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.containers = {
      success: container.success ? $(container.success) : $(container),
      failure: container.failure ? $(container.failure) :
        (container.success ? null : $(container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, object) {
      this.updateContent();
      onComplete(transport, object);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.responseIsSuccess() ?
      this.containers.success : this.containers.failure;
    var response = this.transport.responseText;

    if (!this.options.evalScripts)
      response = response.stripScripts();

    if (receiver) {
      if (this.options.insertion) {
        new this.options.insertion(receiver, response);
      } else {
        Element.update(receiver, response);
      }
    }

    if (this.responseIsSuccess()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
document.getElementsByClassName = function(className, parentElement) {
  var children = ($(parentElement) || document.body).getElementsByTagName('*');
  return $A(children).inject([], function(elements, child) {
    if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      elements.push(child);
    return elements;
  });
}

/*--------------------------------------------------------------------------*/

if (!window.Element) {
  var Element = new Object();
}

Object.extend(Element, {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      Element[Element.visible(element) ? 'hide' : 'show'](element);
    }
  },

  hide: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      element.style.display = 'none';
    }
  },

  show: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      element.style.display = '';
    }
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
  },

  update: function(element, html) {
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
  },

  getHeight: function(element) {
    element = $(element);
    return element.offsetHeight;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).include(className);
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).add(className);
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).remove(className);
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    for (var i = 0; i < element.childNodes.length; i++) {
      var node = element.childNodes[i];
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        Element.remove(node);
    }
  },

  empty: function(element) {
    return $(element).innerHTML.match(/^\s*$/);
  },

  scrollTo: function(element) {
    element = $(element);
    var x = element.x ? element.x : element.offsetLeft,
        y = element.y ? element.y : element.offsetTop;
    window.scrollTo(x, y);
  },

  getStyle: function(element, style) {
    element = $(element);
    var value = element.style[style.camelize()];
    if (!value) {
      if (document.defaultView && document.defaultView.getComputedStyle) {
        var css = document.defaultView.getComputedStyle(element, null);
        value = css ? css.getPropertyValue(style) : null;
      } else if (element.currentStyle) {
        value = element.currentStyle[style.camelize()];
      }
    }

    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
      if (Element.getStyle(element, 'position') == 'static') value = 'auto';


    return value == 'auto' ? null : value;
  },

  setStyle: function(element, style) {
    element = $(element);
    for (name in style)
      element.style[name.camelize()] = style[name];
  },

  getDimensions: function(element) {
    element = $(element);
    if (Element.getStyle(element, 'display') != 'none')
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = '';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = 'none';
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element._overflow = element.style.overflow;
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
  },

  undoClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element.style.overflow = element._overflow;
    element._overflow = undefined;
  }
});

var Toggle = new Object();
Toggle.display = Element.toggle;

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        if (this.element.tagName.toLowerCase() == 'tbody') {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
  }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
  }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
  }
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set(this.toArray().concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set(this.select(function(className) {
      return className != classNameToRemove;
    }).join(' '));
  },

  toString: function() {
    return this.toArray().join(' ');
  }
}

Object.extend(Element.ClassNames.prototype, Enumerable);
var Field = {
  clear: function() {
    for (var i = 0; i < arguments.length; i++)
      $(arguments[i]).value = '';
  },

  focus: function(element) {
    $(element).focus();
  },

  present: function() {
    for (var i = 0; i < arguments.length; i++)
      if ($(arguments[i]).value == '') return false;
    return true;
  },

  select: function(element) {
    $(element).select();
  },

  activate: function(element) {
    element = $(element);
    element.focus();
    if (element.select)
      element.select();
  }
}
var newwindow;
function poptastic(url)
{
	newwindow=window.open(url,'name','height=600,width=300,scrollbars=yes');
	if (window.focus) {newwindow.focus()}
}
function def_pop(page)
{
	var path = '/usnews/Javascript/popup/'
	window.open(path + page,"glossary_pop","scrollbars=1,resizable=0,width=850,height=500");
	return false;
}


