Features_class = function() {
this.mode = "client";
this.features = {};
this.requests = {};
}
Features_class.prototype.getAllowed = function(section) {
this.requests[section] = (this.features[section] || false);
return this.requests[section];
}
Features_class.prototype.toString = function(section) {
console.log("Features");
console.dir(this.features);
console.log("Requests");
console.dir(this.requests);
}
Features = new Features_class()

Features.features = {"isInternal":false,"isProduction":true,"isProduction2":false,"isAcceptance":false,"isDevelopment":false,"All.isProduction":true,"All.isNotProduction":false,"All.isDevAcc":false,"isWSODQA":false,"isQA":false,"isAPPROVED":false,"VendorCookie":false,"All.NewSPSymbols":false,"Markets.NewExchangeTotalSymbols":false,"Markets.OverviewRedesign":true,"ETF.Screener.Benchmarks":false,"All.PublicMultiQuote":true,"Screener.fieldErrorHandling":true,"Stocks.GoldmanSachs":true,"Markets.GoldmanSachs":true,"Screener.KeyUp":true,"Screener.CurrentPriceFiveDollar":true,"All.DynamicCSS":true,"All.MarketWatchNews":true,"Alerts.MarketWatchNews":true,"All.PublicDelayed":true,"All.BoldTickerSymbol":true,"MutualFunds.Header.ClosedToNew":true,"MutualFunds.Header.InTDUniverse":true,"Funds.ScreenerPTileFix":true,"Funds.ExcludeMoneyMarket":true,"Alerts.HistoryV2":true,"Alerts.SymbolInSubject":true,"Alerts.DirectUnsubscribe":true,"Stocks.DelayedBidAsk":true,"Charts.AdvancedChartEnhancements":true,"MutualFunds.CompareToolResults.ClickFundSymbolsDisclaimer":true,"Funds.DataAsOfDate":true,"Funds.BondStatisticsStyleBox":true,"All.NewsDisableOneMonthRestriction":true,"Alerts.CompressedHistory":true,"Markets.IndicesHistoricalQuotes":true,"ETF.Overview.TDAXIndependence":true,"PredictWallStreet":true,"Funds.CommentaryNewTypes":true,"ALL.WSODCompany":true,"ETF.Marketedge":true,"MorningstarDataDefinitions":true,"Funds.RedemptionFeedDisclaimer":true,"Funds.MorningstarPremierListUpdates":true,"Funds.MstarRatingModule":true,"Markets.Seminars":true,"Markets.MarketHuddleToWebcasts":true,"FixedIncome.WizardLadders":true,"issueNameLookupXREF5":true,"Ideas.WeeklyCompass":true,"Stocks.NewPeersRequest":true,"Maintenance.2008-02-19":true,"Funds.MorningstarOnDemand":true,"Screener.Enhancements":true,"All.SecondaryHeaderColor":true,"All.FastLookup":true,"Maintenance.2008-03-04":true,"Funds.FundFamilies":true,"Maintenance.2008-04-08":true,"FixedIncome.YieldCenter":true,"FixedIncome.UTF8":true,"Stocks.Valuation.RevertBackToGrowth":true,"Stocks.navigationTabs":true,"Stocks.removeScreenerLink":true,"Stocks.MiniOverview":false,"All.SessionSeedSessionTimeout":true,"FixedIncome.MarketCommentaryPublicGroup":true,"Markets.MarketMonitorFF":true,"All.DelayedMinutes15":true,"Stocks.OverviewComingSoonLink":true,"ETF.OverviewRedesign":true,"Symbol.HeaderRedesign":true,"Stocks.OverviewRedesign":true,"FixedIncome.ToolsAndCalculators":true,"Stocks.CalendarEstimatesChange":true,"thirdPartyPopupProcessFile":true,"Markets.HideWebCastLink":false,"Funds.SnapShotExpenseRatio":true,"All.RemoveGoldmanTab":true,"Stocks.AdhesionTracking":true,"All.PopupMoreIconFix":true,"GoldmanSachs.ResearchTeamMessage":true,"FixedIncome.RemoveTreasuryAuctions":true,"FixedIncome.NewIssuesLink":true,"Stocks.HeaderIndustryLink":true,"News.DisplayNewMarketwireLogo":true,"Screener.Options":true,"Stocks.MarketEdgeDaily":true,"MF.Prospectus":true,"Screener.QuoteCounting":true,"ETF.Header.QuoteIIV":true,"Ideas.StandardPoorsEnhancment":true,"Stocks.Screener.ResearchTeam":true,"FixedIncome.Reports":true,"MF.Screener.BondMutualFunds":true,"Options.InvestorTools":true};


/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */



// ------------------------------------------------------------------------------------------------------------
/*
Documentation: http://barney.wallst.com/wsodwiki/index.php/Content_Buffer

ContentBuffer()
generic data buffering object

usage:

var c = new ContentBuffer();
c.load({
	url: "data.asp",
	method: "get",
	onload: a,
	debug: true
});

function a (connection) {
	alert("x:" + connection.getResult());
};

*/
// ------------------------------------------------------------------------------------------------------------

if (typeof Controller == "undefined")
{
	if (typeof dbg != "function")
	{
		var dbg = function () {};
	};
}
else
{
	Controller.require("/includes/jslib/debug.js");
};

function ContentBuffer ()
{
	this.connections = [];
	this.connectionsMax = 100;
	this.connectionsActive = 0;
	this.connectionsPending = [];
	this.debug = false;
	this.context = window;
	this.connectionId = 0;

	if (arguments.length && typeof arguments[0] == "object")
	{
		this.context = arguments[0];
	};
};


// ------------------------------------------------------------------------------------------------------------
// load(contentPackge)
/*

contentPackge:
	.url: page to load in the hidden buffer
	.onload: function reference that gets called on a successful buffer load [optional]
	.onerror: function reference that gets called on an unsuccessful buffer load [optional]
	.method: get|post [optional]
	.postdata: synonym for .data [deprecated]
	.data: {name: value} list [optional]
	.[arbitrary]: optional arbitrary parameters that get passed to .callback; allows for state management with an asynch request

*/
// ------------------------------------------------------------------------------------------------------------
ContentBuffer.prototype.load = function (contentPackage)
{
	if (typeof Controller == "undefined")
	{
		//dbg("Missing Dependency", "Controller.js", "ff0000");
	};


	// data validation
	try
	{
		contentPackage.method = contentPackage.method.toLowerCase();

		if (contentPackage.method != "get" && contentPackage.method != "post")
		{
			contentPackage.method = "get";
		};
	}
	catch (e)
	{
		contentPackage.method = "get";
	};

	if (contentPackage.postdata && !contentPackage.data)
	{
		contentPackage.data = contentPackage.postdata;
	}
	else if (!contentPackage.data)
	{
		contentPackage.data = {};
	};

	// enable cache flushing
	if (document.location.search.match(/\.\.nocache\.\.=on/i))
	{
		contentPackage.data["..nocache.."] = "on";
	};

	// pass debugchartsrv
	var dbgChartSrv = document.location.search.match(/\.\.debugchartsrv\.\.=([a-zA-Z]+)/i);
	if (dbgChartSrv) {
		contentPackage.data["..debugchartsrv.."] = dbgChartSrv[1];
	}

	return new Connection(this, this.connectionId++, contentPackage);
};

// ------------------------------------------------------------------------------------------------------------
// loadXMLHTTP()
// ------------------------------------------------------------------------------------------------------------
ContentBuffer.prototype._loadXMLHTTP = function (connection) {

    var thisConnection = connection;
    var contentPackage = thisConnection.contentPackage;

	function stateMonitor () {
		thisBuffer._monitorConnectionState(thisConnection);
	};

	this.connectionsActive++;

    /*
	if (!this.connections.length) {
		if (!this.initConnection()) {
			if (this.debug || contentPackage.debug) {
				dbg("ContentBuffer initialization error", "unsupported", "red");
			};
			return;
		};
	};
    */

	var dataPackage = null;
	var thisBuffer = this;

	thisConnection.active = true;
	//contentPackage.connectionId = this.connectionId++; // necessary?

	if (typeof contentPackage.contentType == "string") {
		contentPackage.data["..contenttype.."] = contentPackage.contentType;
	};

	// uniquely identify contentbuffer requests
	contentPackage.data["..requester.."] = "ContentBuffer";

	if (contentPackage.method == "post") {

		dataPackage = "";

		for (var i in contentPackage.data) {
			dataPackage += (dataPackage.length ? "&" : "") + this.encode(i) + "=" + this.encode(contentPackage.data[i]);
		};

		if (this.debug || contentPackage.debug) {
			dbg("ContentBuffer post data", dataPackage);
		};

	} else {
		for (var i in contentPackage.data) {
			contentPackage.url += (contentPackage.url.indexOf("?") == -1 ? "?" : "&") + this.encode(i) + "=" + this.encode(contentPackage.data[i]);
		};
	};

	if (this.debug || contentPackage.debug) {
		dbg("ContentBuffer loading [" + thisConnection.connectionId + "]", contentPackage.url + " [" + contentPackage.method + "]");
	};

	if (this.debug || contentPackage.debug) {

		var debugUrl = contentPackage.url;

		if (dataPackage) {
			debugUrl += (debugUrl.indexOf("?") == -1 ? "?" : "&") + dataPackage;
		};

		debugUrl = debugUrl.replace(/\&?\.\.[^\=\&]*\.\.\=[^\&]*/g, "");

		if (debugUrl.indexOf("/") != 0 && debugUrl.indexOf("http") != 0) {
			var path = String(window.location).replace(/https*:\/\//, "");
			debugUrl = path.substr(path.indexOf("/"), path.lastIndexOf("/") + 1 - path.indexOf("/")) + debugUrl;
		}

		dbg("ContentBuffer URL", "<a href=\"" + debugUrl + "\"  target=\"_blank\">" + debugUrl + "</a>");
	};

	try {
		// netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    	thisConnection.c.open(contentPackage.method.toUpperCase(), contentPackage.url, true);
		thisConnection.c.onreadystatechange = stateMonitor;
	} catch (e) {
		// alert(e);
	};

	if (contentPackage.method == "post") {
		thisConnection.c.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	};

	//thisConnection.contentPackage = contentPackage;
	//dbg(thisConnection.c.send(), "trying connectionId");

	thisConnection.c.send(dataPackage);

	//return thisConnection;
};

// ------------------------------------------------------------------------------------------------------------
// monitorConnectionState()
// ------------------------------------------------------------------------------------------------------------
ContentBuffer.prototype._monitorConnectionState = function (connection) {

	try {

		if (connection.c.readyState == 4) {

			if (connection.c.status != 200) {

				if (this.debug || connection.contentPackage.debug) {
					dbg("ContentBuffer load error", connection.c.status, "red");
					dbg("ContentBuffer result [" + connection.connectionId + "]", connection.c.responseText);
				};

				try {
					var result = connection.c.responseText;
				} catch (e) {
					var result = null;
				};

				connection.contentPackage.result = result;

				if (typeof connection.contentPackage.onerror == "function") {
					connection.contentPackage.onerror.apply(connection.context, [connection]);
				};

				return;
			};

			var responseType = connection.contentPackage.contentType || connection.c.getResponseHeader("Content-Type");
			var result = null;

			if (responseType == "text/html" || responseType == "text/plain") {
				result = connection.c.responseText;
			} else if (responseType == "text/xml") {
				result = connection.c.responseXML;
			} else if (responseType == "text/javascript") {
				try {
					result = connection.c.responseText;

					if (!connection.contentPackage.preventEval) {

                       connection.context.__evalBuffer = function() {
                           eval(result);
                       }

                       connection.context.__evalBuffer();

					};

				} catch (e) {
					if (this.debug || connection.contentPackage.debug) {
						dbg("ContentBuffer javascript eval error", e.message, "red");
						if (typeof dbgObject != "undefined"){ dbgObject(e); }
					};
				};
			};

			connection.contentPackage.result = result;

			if (this.debug || connection.contentPackage.debug) {
				// dbg("ContentBuffer result [" + connection.contentPackage.connectionId + "]", result.replace(/\</g, "&lt;").replace(/\>/g, "&gt;"));
			};

			if (typeof connection.contentPackage.onload == "function") {
				connection.contentPackage.onload.apply(connection.context, [connection]);
			};

			this.finishConnection(connection);
		};

	} catch (e) {
		if (this.debug || connection.contentPackage.debug) {
			dbg("state monitoring error", e.message, "red");
			if (typeof dbgObject != "undefined"){ dbgObject(e); }
		};

		this.finishConnection(connection);
	};
};

// ------------------------------------------------------------------------------------------------------------
// isActive
// ------------------------------------------------------------------------------------------------------------
ContentBuffer.prototype.isActive = function() {
	for (var i=0; i<this.connections.length; i++) {
		if (this.connections[i].active) {
			return true;
		}
	}

	return false;
}

// ------------------------------------------------------------------------------------------------------------
// abortRequests()
// ------------------------------------------------------------------------------------------------------------
ContentBuffer.prototype.abortRequests = function () {
	for (var i = 0; i < this.connections.length; i++) {
		this.connections[i].abort();
	};
}

// ------------------------------------------------------------------------------------------------------------
// abortRequests()
// ------------------------------------------------------------------------------------------------------------
ContentBuffer.prototype.abortRequests = function () {
	for (var i = 0; i < this.connections.length; i++) {
		this.connections[i].abort();
	};
}

// ------------------------------------------------------------------------------------------------------------
// encode()
// ------------------------------------------------------------------------------------------------------------
ContentBuffer.prototype.encode = function(str) {
	//return escape(str);

	/* escape() doesn't account for the + symbol, which Serializer() sometimes includes in its Base64 encoding.  encodeURIComponent() includes everything escape() does, and includes the + symbol */
	return encodeURIComponent(str);
}

ContentBuffer.prototype.finishConnection = function(connection)
{
	if(connection.active)
	{
		this.connectionsActive--;
		connection.active = false;
	}

	if(this.connectionsPending.length)
	{
		this._loadXMLHTTP(this.connectionsPending.shift());
	}

	for (var x=0; x < this.connections.length; x++){
		if (connection === this.connections[x]){
			this.connections.splice(x,1);
			break;
		}
	}
}


// ------------------------------------------------------------------------------------------------------------
// Connection class
// ------------------------------------------------------------------------------------------------------------
function Connection(contentBuffer, id, contentPackage) {
	this.active = false;
	this.parent = contentBuffer;
	this.connectionId = id;
	this.contentPackage = contentPackage;
	this.context = contentPackage.context || this.parent.context;
	this._init();
};

Connection.prototype._init = function() {
    var c = false;

	try {
		c = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			c = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (f) {
			c = false;
		};
	};

	if (!c && typeof XMLHttpRequest != "undefined") {
		c = new XMLHttpRequest();
	};

	if (c) {
		this.c = c;
	} else {
	   dbg("Content Buffer initialization error.", "Not supported by this browser", "red");
	};

    if (this.parent.connectionsActive < this.parent.connectionsMax) {
        this.parent.connections.push(this);
        this.parent._loadXMLHTTP(this);
    } else {
        dbg("queuing request");
        this.parent.connectionsPending.push(this);
    };
};

Connection.prototype.getResult = function() {
    return this.contentPackage.result;
};

Connection.prototype.status = function() {
	return (this.c.readyState == 4 && this.c.status == 200);
};

Connection.prototype.abort = function() {
	if (this.active) {
		try {
			this.c.onreadystatechange = function() {};
			this.c.abort();
		} catch (e) {
			dbg("connection abort failed", e, "red");
		};

		this.parent.finishConnection(this);
	};
};


/* -- Loaded:/includes/jslib/contentbuffer/contentBuffer.4.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


Function.getClassName = function() {
	return "Function";
};


/* Extend from another prototyped Function */
Function.prototype.Extend = function(superClass) {
	this.prototype = new superClass();

	this.prototype.getSuperClass = function() {
		return superClass;
	};
	this.getSuperClass = this.prototype.getSuperClass;
	return this;
};

/*
The Super method allows us to do the constructor (or any super call) chaining more easily.  It looks like this:

var A = function() {
  this.value = ["1"]
}

var B = function() {
  B.Super(this);
  this.value.push("2");
}

Super calls for non constructor methods look like:
Class.Super(this, "methodName", arguments);
*/

Function.prototype.Super = function(context, methodName, args) {
	if (null != methodName) {
		var method = this.getSuperClass().prototype[methodName];
	}
	else {
		var method = this.getSuperClass();
	}

	if (!args) {
		return method.call(context);
	}
	else {
		return method.apply(context, args);
	}
};

/*
Function.Implements
It takes either an instanciated object or a functor, and a list of properties/methods and add
them to the calling functor.  Be careful not to apply methods that call other methods/object in
the passed functor/object that do not exist in the calling functor.
*/
Function.prototype.Implements = function(obj, members) {
	if(typeof obj == "function") {
		obj = obj.prototype;
	}
	var tObj = {}
	for(var i = 0, len = members.length; i < len; ++i) {
		tObj[members[i]] = obj[members[i]] || null;
	}
	var o = WSDOM.Util.copyObject(tObj);
	for(var i in o) {
		this.prototype[i] = o[i];
	}
};

/* Used to be 'hitch'.  Now it works right. */
Function.prototype.Context = function(obj) {
	var fnReference = this;
	return function () {
		return typeof fnReference == "function" ? fnReference.apply(obj, arguments) : obj[fnReference].apply(obj, arguments);
	};
};
Function.prototype.EmptyFunction = function() {};

/* -- Loaded:/includes/jslib/Function/Function.1.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


var EventSource = function(type) {
	this.listeners = [];
	this.type = type;
};

EventSource.prototype.addListener = function(listener, context) {
	if (listener instanceof Function) {
		listener = {
			handler: listener,
			context: context
		}
	}
	
	if (!listener.context) {
		listener.context = window;
	}
	this.listeners.push(listener);
	return listener;
};

EventSource.prototype.removeListener = function(listener) {
	for (var i=0; i<this.listeners.length; i++) {
		if (listener == this.listeners[i]) {
			this.listeners.splice(i,1);
		}
	}
};

EventSource.prototype.removeAll = function() {
	this.listeners = [];
};

EventSource.prototype.fire = function() {
	Array.prototype.unshift.call(arguments, this.type);
	
	for (var i=0; i<this.listeners.length; i++) {
		this.listeners[i].handler.apply(this.listeners[i].context, arguments);
	}
};

var DOMEventSource = function(type) {
	DOMEventSource.Super(this, null, arguments);
	this.delayTimeouts = [];
	this.typeIE = "on" + this.type;
	this.elements = [];
};
DOMEventSource.Extend(EventSource);

DOMEventSource.prototype._getBrowserEventName = function() {
	switch (this.type) {
		case "load": 	case "change": 	case "reset":
		case "select":	case "submit": 	case "blur":
		case "focus": 	case "resize": 	case "scroll":
		case "abort":	case "error":	case "unload":
			return "HTMLEvents";
					
		case "mouseover": 	case "mouseout": 	case "click":
		case "dblclick":  	case "mouseup": 	case "mousedown":
		case "mouseenter": 	case "mouseleave":	case "mousemove":
		case "contextmenu": case "dragstart":	case "selectstart":
			return "MouseEvents";
		
		case "keypress": case "keydown": case "keyup":
			return "UIEvents";
		
		default:
			return null;
	}
};

DOMEventSource.prototype._validateEvent = function(e, listener){
	if (listener.keyCode && "UIEvents" == this._getBrowserEventName()) {
		return listener.keyCode == e.nativeEvent.keyCode;
	}
	
	return true;
};

DOMEventSource.prototype._createDOMHandlerClosure = function(listener, element) {
	var theDOMEventSource = this;
	for (var i=0, DOMHandler; i<element.length; i++) {
		DOMHandler = function() {
			var el = element[i].node;
			if (listener.delay) {
				return function() {
					var e = window.event || arguments[0];
					
					// because browsers rewrite values after event goes out of scope
					var newEvt = {};
					for (var i in e) {
						newEvt[i] = e[i];
					}
					
					e = new DOMEvent(newEvt);
					
					theDOMEventSource.clearDelayTimeouts();
					theDOMEventSource.delayTimeouts.push(window.setTimeout(
						function() {
							if(theDOMEventSource._validateEvent(e, listener)){
								listener.handler.call(listener.context, e, el, listener.data);
							}
						}
					, listener.delay));
				}
			}
			else {
				return function() {
					var e = new DOMEvent(window.event || arguments[0]);
					if(theDOMEventSource._validateEvent(e, listener)){
						listener.handler.call(listener.context, e, el, listener.data);
					}
				}
			}
		}();
		
		this._addEventListener(element[i].node, DOMHandler);
		element[i].registeredListeners.push({ DOMHandler: DOMHandler, listener: listener });
	}
};

DOMEventSource.prototype.addElement = function(element /* element or array of elements */, removeIfExisting) {
	if (!(element instanceof Array)) {
		element = [element];
	}
	
	if (removeIfExisting) {
		this.removeElement(element);
	}
	
	var elements = [];
	for (var i=0; i<element.length; i++) {
		elements.push({
			node: element[i],
			registeredListeners: []
		});
	}
	
	for (var i=0; i<this.listeners.length; i++) {
		this._createDOMHandlerClosure(this.listeners[i], elements);
	}
	
	this.elements = this.elements.concat(elements);
};

DOMEventSource.prototype.removeElement = function(element) {
	var element = [].concat(element);
	
	for (var i=0, elWrapper; i<this.elements.length; i++) {
		elWrapper = this.elements[i];
		
		if (!element.length) {
			break;
		}
		
		for (var j=0, el; j<element.length; j++) {
			el = element[j];
			
			if (elWrapper.node === el) {
				
				for (var k=0; k<elWrapper.registeredListeners.length; k++) {
					this._removeEventListener(el, elWrapper.registeredListeners[k].DOMHandler);
				}
				
				element.splice(j, 1);
				this.elements.splice(i, 1);
				
				j--;
				i--;
			}
		}
	}

};

DOMEventSource.prototype.removeAll = function() {
	this.removeAllElements();
	this.listeners = [];
};

DOMEventSource.prototype.removeAllElements = function() {
	for (var i=0, el; i<this.elements.length; i++) {
		el = this.elements[i];
		
		for (var j=0; j<el.registeredListeners.length; j++) {
			this._removeEventListener(el.node, el.registeredListeners[j].DOMHandler);
		}
	}
	this.elements = [];
};

DOMEventSource.prototype.addListener = function(listener, context, delay) {
	if (listener instanceof Function) {
		listener = {
			handler: listener,
			context: context,
			delay: delay
		}
	}
	
	if (!listener.context) {
		listener.context = window;
	}
	
	this._createDOMHandlerClosure(listener, this.elements);
	
	this.listeners.push(listener);
	return listener;
};

DOMEventSource.prototype.removeListener = function(listener) {
	for (var i=0, el; i<this.elements.length; i++) {
		el = this.elements[i];
		
		for (var j=0, rl; j<el.registeredListeners.length; j++) {
			rl = el.registeredListeners[j];
			
			if (rl.listener == listener) {
				this._removeEventListener(el.node, rl.DOMHandler);
				el.registeredListeners.splice(j, 1);
				break;
			}
		}
	}
	
	for (var i=0, listener; i<this.listeners.length; i++) {
		if (listener == this.listeners[i]) {
			this.listeners.splice(i, 1);
			break;
		}
	}
};

DOMEventSource.prototype.fire = function(element /* optional element or array of elements */) { 
	if (undefined == element) {
		// fire on all elements
		for (var i=0; i<this.elements.length; i++) {
			this._dispatchEvent(this.elements[i].node);					
		}
	}
	else {
		if (!(element instanceof Array)) {
			element = [element];
		}
		
		for (var i=0; i<element.length; i++) {
			this._dispatchEvent(element[i]);
		}
	}
};

DOMEventSource.prototype._addEventListener = function(el, handler) {
	if (document.attachEvent) {
		DOMEventSource.prototype._addEventListener = function(el, handler) {
			el.attachEvent(this.typeIE, handler);
		};
	}
	else if (document.addEventListener) {
		DOMEventSource.prototype._addEventListener = function(el, handler) {
			el.addEventListener(this.type, handler, false);
		};
	}
	this._addEventListener = DOMEventSource.prototype._addEventListener;
	this._addEventListener(el, handler);
};

DOMEventSource.prototype._removeEventListener = function(el, handler) {
	if (el.detachEvent) {
		DOMEventSource.prototype._removeEventListener = function(el, handler) {
				el.detachEvent(this.typeIE, handler);
		};
	}
	else if (el.removeEventListener) {
		DOMEventSource.prototype._removeEventListener = function(el, handler) {
			el.removeEventListener(this.type, handler, false);
		};
	}
	this._removeEventListener = DOMEventSource.prototype._removeEventListener;
	this._removeEventListener(el, handler);
};

DOMEventSource.prototype._dispatchEvent = function(el) {
	if (document.createEventObject) {
		DOMEventSource.prototype._dispatchEvent  = function(el) {
			var event = document.createEventObject();
				event.srcElement = el;
				event.type = this.type;
				
			el.fireEvent(this.typeIE, event);
		};
	}
	else {
		DOMEventSource.prototype._dispatchEvent = function(el) {
			var event = document.createEvent(this._getBrowserEventName(this.type));
				event.initEvent(this.type, true, true);
				
			el.dispatchEvent(event);
		};	
	}
	this._dispatchEvent = DOMEventSource.prototype._dispatchEvent;
	this._dispatchEvent(el);
};

DOMEventSource.prototype.clearDelayTimeouts = function() {
	for (var i=0; i<this.delayTimeouts.length; i++) {
		window.clearTimeout(this.delayTimeouts[i]);
	}
	this.delayTimeouts = [];
};


var DOMEvent = function(nativeEvent) {
	this.nativeEvent = nativeEvent;
};

DOMEvent.prototype.cancel = function() {
	if (this.nativeEvent.stopPropagation) {
		this.nativeEvent.stopPropagation();
	} 
	else {
		try { this.nativeEvent.cancelBubble = true; } catch(e) {}
	}
	if (this.nativeEvent.preventDefault) {
		this.nativeEvent.preventDefault();
	} 
	else {
		try { this.nativeEvent.returnValue = false; } catch(e) {}
	}
	
	
	return this.nativeEvent;
};

DOMEvent.prototype.getTarget = function() {
	var target = this.nativeEvent.srcElement || this.nativeEvent.target;
	
	this.getTarget = function() {
		return target;
	}
	return this.getTarget();
};

var EventManager = function() {
	this.events = [];
	this.add(window, "unload", this.removeAll, this);
};

EventManager.prototype.KEYCODES = {
	Backspace:8
	,TAB:9
	,ENTER:13
	,SHIFT:16
	,CTRL:17
	,ALT:18
	,CAPS:20
	,ESCAPE:27
	,PAGEUP:33
	,PAGEDOWN:34
	,END:35
	,HOME:36
	,LEFT:37
	,UP:38
	,RIGHT:39
	,DOWN:40
	,INSERT:45
	,DELETE:46
	,SPACE:32
	,COMMAND:224
}

EventManager.prototype.add = function(element /* | or object | or customType */, type, handler, context, data, delay, keyCode) {
	if (arguments.length > 1) {
		var inputs = {
			element: element,
			type: type,
			handler: handler,
			context: context,
			data: data,
			delay: delay,
			keyCode:keyCode
		}
	}
	else if (arguments[0] instanceof Object) {
		var inputs = arguments[0];
	}
	else {
		var inputs = {
			type: arguments[0]
		}
	}
	
	var listener = { handler: inputs.handler, context: inputs.context, delay: inputs.delay, data: inputs.data, keyCode:inputs.keyCode };
	
	if (this._isDomEventType(inputs.type)) {
		var e = this._addDOMEvent(inputs.type, listener, inputs.element);
	}
	else {
		var e = this._addCustomEvent(inputs.type, listener);
	}
	this.events.push(e);
	return e;
};

EventManager.prototype._isDomEventType = function (type) {
	if (null == DOMEventSource.prototype._getBrowserEventName.apply({type: type})) {
		return false;
	}
	return true;
};


EventManager.prototype._addDOMEvent = function(type, listener, element) {
	var e = new DOMEventSource(type);
	if (listener.handler) {
		e.addListener(listener);
	}
	if (element) {
		e.addElement(element);
	}
	return e;
};

EventManager.prototype._addCustomEvent = function(type, listener) {
	var e = new EventSource(type);
	if (listener.handler) {
		e.addListener(listener);
	}
	return e;
};

EventManager.prototype.remove = function(e /*element  or event */, listener /*listener or eventType*/) {
	/* Method refactored, as it supports 'new' mode (remove the event+listener) and 'old' mode (remove the event from the element by eventType)*/
	if (e instanceof EventSource) {
		this._removeEvent(e, listener);
	}
	else if (e.nodeName || e instanceof Array) {
		this._removeElement(e, listener);
	}
};

EventManager.prototype._removeEvent = function(e, listener) {
	if (undefined == listener) {
		e.removeAll();
	} else {
		e.removeListener(listener);
	}
	for (var i=0; i<this.events.length; i++) {
		if (e == this.events[i]) {
			this.events.splice(i, 1);
			break;
		}
	}
};
EventManager.prototype._removeElement = function(el, eventType) {
	for (var i=0, event; i<this.events.length; i++) {
		event = this.events[i];
		if (event instanceof DOMEventSource) {
			if (!eventType || (event.type == eventType)) {
				event.removeElement(el);
			}
		}
	}
};

EventManager.prototype.removeAll = function() {
	for (var i=0; i<this.events.length; i++) {
		this.events[i].removeAll();
	}
	this.events = [];
};

EventManager.prototype.cancel = function(e) {
	if(!e) { return; }
	
	if (e instanceof DOMEvent) {
		e.cancel();
	}
	else if (e.srcElement || e.target) {
		DOMEvent.prototype.cancel.apply({nativeEvent: e});
	}
};

if (window["WSDOM"]) {
	WSDOM.defineClass("Events", null, EventManager);
	WSDOM.loadSingleton("WSDOM.Events.3");
} else {
	var Events = new EventManager(); // backwards compatibility with Events.2
}


/* -- Loaded:/includes/jslib/Events/Events.3.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


/*------------------------------------
   Events.3.delegate
   Event Delegation for Events.3
   
   ****NOTE*********************
   	 Dependent on: Element.is()
   *****************************
   
   //Example:
   
   Events.delegate("#marketMovers", "click", {
   		 selector:"a.clickable"
   		,handler:this.notifyClick
   		,context:this
   		,data:myDataObject
   		,dynamicEvent:{
   			 type:'mouseout'
   			,handler:this.blurLink
   			,context:this
   			,data:myDataObject
   		}
   });
   
   arguments[0] - DOMElement || selector
   arguments[1] - eventType
   arguments[3] - object or array of objects with properties:
   		1. selector
   		2. handler
   		3. context
   		4. data
-------------------------------------*/



/*------------------------------------
	Delegate - 
	Object containing all our 
	delegate functionality 
-------------------------------------*/

EventManager.prototype.Delegation = {
	
	/*------------------------------------
		SuperClass - 
		EventManager Object instance
	-------------------------------------*/

	 SuperClass:null
	 
	 /*------------------------------------
		isDelegator - 
		Check to see if target Element is
		the element that has the delegation
		event assigned.
	-------------------------------------*/
	 
	,isDelegator:function( el, delegators ) {

		var len = delegators.length;

		while(len--) {
			if(el === delegators[len]) {
				return true;	
			}
		}
		return false;
	}
	
	/*------------------------------------
		prepArgs - 
	-------------------------------------*/

	,prepArgs:function( o ) {

		o.context = o.context || window;
		o.handler = String === o.handler.constructor? o.context[ o.handler ] : o.handler;

		if( o.dynamicEvent ) {

			var self = this;

			o.dynamicEvent    = this.prepArgs( o.dynamicEvent );
			o.dynamicEvent.fn = function( e, el, data ) {

				var d = o.dynamicEvent;
					d.handler.call( d.context, e, el, data );
				
				var evs = self.SuperClass.events;
				var len = evs.length;
				
				while(len--) {	/* Loop backwards b/c its more likely the event is at the end of the stack */
					
					if(evs[len].elements[0].node === el) {	/* there will always only be one element */

						evs[len].removeAll();
						evs.splice( len, 1 );
						break;
					}
				}
			}
		}
		return o;
	}
	
	/*------------------------------------
		assign - 
		Assign Event, prep arguments,
		create  function to give to 
		EventManager for delegation
		handling.
	-------------------------------------*/

	,assign:function( SuperClass, delegator, type, oArgs ) {
		
		this.SuperClass = this.SuperClass || SuperClass;
		
		delegator = Element.get(delegator) || Element.parseSelector(delegator);
		oArgs	  = Array.prototype.concat( oArgs );
		
		var len = oArgs.length;
		
		while(len--) {
			oArgs[len] = this.prepArgs( oArgs[len] );	
		}

		var self = this;
		var fn   = function(e, el, data){
			
			var target = e.getTarget();
		
			if( self.isDelegator(target, delegator) ) {
				return;
			}

			var  l = oArgs.length
				,cur;

			while(l--) {

				cur = oArgs[l];

				if(Element.is(target, cur.selector, el, true)) {

					if( cur.dynamicEvent ) {

						var de = cur.dynamicEvent;
			       		var ev = self.SuperClass.add( target, de.type, de.fn, de.context, de.data );
			       	}
			       	
					e.delegator = el;
					cur.handler.call(cur.context, e, target, cur.data);
				}
			}
		};
		
		return this.SuperClass.add( delegator, type, fn );
	}	
}

/*-----------------------------------
	delegate -
	Public method to adding
	the delegation events.
------------------------------------*/

EventManager.prototype.delegate = function( delegator, type, oArgs ) {
	
	return this.Delegation.assign( this, delegator, type, oArgs );
}

/* -- Loaded:/includes/jslib/Events/Events.3.delegate.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


/*

############################
Current Differences between WSDOM/Element and jslib/Element
Please maintain these when updating this file:

- WSDOM's Create references WSDOM.Events and looks for that as the property name
- WSDOM Create's children parameter is looped through, while jslib/Element only calls addChild 

############################

Element.3.js
A library to handle DOM Elements

Documentation at http://dev2.wallst.com/playground/docs/
	and 		 http://wiki.wsod.local/wsodwiki/index.php/Element.3.js_:Dev

Most functions take an element handle or an element's id as a string as the first parameter
"set" functions can also take an array of elements or ids.

Element.get - returns a handle on an element
Element.create - extension of document.createElement. 2nd parameter is properties, 3rd parameter is children.
Element.addChild - appends an element to an element
Element.remove - remove an element from the DOM
Element.setDisplay - sets display: property of element(s)
Element.setVisibility - sets visibility: property of element(s)
Element.remove - removes element(s) from DOM
Element.setHTML - set innerHTML value of element(s).  Optional 3rd parameter to append content
Element.parseSelector - returns list of elements that match CSS selector string
Element.forEach - accepts a CSS selector or array of elements and iterates on each element
Element.setStyle - an inline way to set multiple style properties of an element - example: Element.setStyle(el,"border:2px solid red;width:400px;background:#888;");
Element.removeChildNodes - remove all nodes within an element
Element.cloneNode - extension of el.cloneNode that strips all DOM events
Element.insertBefore - keeps the Element syntax in your code
Element.insertAfter - because the DOM only offers insertBefore
Element.nextElement - returns next sibling of indicated tagname
Element.previousElement - returns previous sibling of indicated tagname
Element.getParent - returns the first parent element of a certain tag name
Element.getXY - returns an {x:,y:} object of an element's position relative to the html body
Element.setXY - set an element(s) position
Element.getSize - returns an {width:,height:} object of an element's total size
Element.getSizeXY  - returns an {x:,y:} object of an element's total size
Element.setSize - set the size of an element(s)
Element.setWidth - set the width of an element(s)
Element.setHeight - set the height of an element(s)
Element.getBorderSize - returns the current border size

Element.addClass  - adds a class attribute
Element.removeClass - removes a class attribute
Element.toggleClass - reverses a class attribute
Element.switchClass - takes a 3rd parameter boolean to turn on/off a class attribute
Element.hasClass - returns if an element is part of a class
Element.getStyle

//////////////////////////
Element Extras (separate file Element.3extras.js)
Element.isInsideOf
Element.isInsideOfNS
Element.isInsideOfEW
Element.debug
Element.setOpacity
Element.setDisabled
Element.setAttribute - same functionality as el.setAttribute but accepts an array of elements
Element.setProperty - sets a JavaScript property to a single or array of elements
Element.getParentBySelector - like getParent but with CSS Selector support
Element.isOnScreen - returns if an element is rendered on the screen.  Traverses up the DOM and checks .display and .visibility
*/

/**
 * @class Element contains functions for working with the DOM in a cross-browser way.  
 * See also: <a href="http://wiki.wsod.local/wsodwiki/index.php/Element.3.js_:Dev">http://wiki.wsod.local/wsodwiki/index.php/Element.3.js_:Dev</a>
 * @static 
 */
var Element_class = function() {

}

// -------------------------------------------------------
// 	DOM Helpers
// -------------------------------------------------------

/**
 * Returns a handle on an element with the specified ID
 * @param {String|| Number} el 
 * @return {element} Native DOM element if found
 */
Element_class.prototype.get = function(el) {
	if (typeof el == "string" || typeof el == "number") el = document.getElementById(el);
	return el;
};

/**
 * Element.create can be used in a variety of ways to create a new HTML element and (optionally) insert it into the DOM
 * @example var el = WSDOM.Element.create("div",{className:"primary",style:"color:red;font-weight:bold;"},"Default Text",document.body) 
 * 
 * @param {String} tag Element tag name such as 'div'
 * @param {Object} [attributes] Element attributes object literal, such as {id:'container3',className:'container'}  Note that 'class' is a reserved word, 
 * 		   be sure to use 'className' to set CSS classes
 * @param {Object || String} [children] Element or String text node to add as children
 * @param {Object} [parent] Element to append newly created node to (optional)
 * @param {Object} [ElementObjectInstance]
 * @return {element} Newly created native DOM element
 */
Element_class.prototype.create = function (tag, attributes, children, parent, ElementObjectInstance) {

	var element = document.createElement(tag);

	// mapping for IE specific attributes
	var attributeMap = {
		"for":["htmlFor"],
		"colspan":["colSpan"],
		"usemap":["useMap"]
	}

	for (var i in attributes)
	{
		if (i == "className" || i == "class")
		{
			element.className = attributes[i];
		}
		else if (document.all && attributeMap[i])
		{
			for (var j = 0; j <attributeMap[i].length; j++) {
				element.setAttribute(attributeMap[i][j], attributes[i]);
			}
			element.setAttribute(i, attributes[i]); // retain original
		}
		else if (i == "style")
		{
			this.setStyle(element,attributes[i]);
		}
		else if (i == "Events")
		{
			if (typeof Events != "undefined") {
				var elEvents = attributes[i];
				if (!this.isArray(elEvents)) {
					elEvents = [elEvents]
				}

				for (var j = 0; j < elEvents.length; j++) {
					elEvents[j].element = element;
					Events.add(elEvents[j]);
				}
			}
			else {
				alert(":: DEV ERROR :: \n Location: Element.3.js -- Element_class.prototype.create \n Type: Dependency \n Message: Expecting Events Lib for use of Events in Element.create")
			}
		}
		else
		{
			element.setAttribute(i, attributes[i]);
		};
	};

	// <map> also needs an ID to work correctly
	if (tag.match(/^map$/i) && attributes && attributes.name && !attributes.id) {
		element.setAttribute("id", attributes.name);
	}

	if (arguments.length > 2 && children != undefined && children !== "") {
		this.addChild(element, children);
	};

	if (parent) {
		this.addChild(parent,element);
	}

	return (ElementObjectInstance) ? new ElementObject(element) : element;
};

/**
 * Append an element to another element
 * @param {element} el Parent
 * @param {element || string} child Element or text to append
 */
Element_class.prototype.addChild = function (el, child) {
	el = this.get(el);

	if (!this.isArray(child)) {
		child = [child]
	}
	for (var i=0; i<child.length; i++) {
		if (typeof child[i] == "object") {
			el.appendChild(child[i]);
		}
		else if (typeof child[i] == "string" || typeof child[i] == "number") {
			// element.appendChild(document.createTextNode(children));
			el.innerHTML += child[i];
		};
	}

};



/**
 * Remove an element(s) from the DOM
 * @param {element || string} el Element handle or ID to remove
 */
Element_class.prototype.remove = function(el) {
	el = this.get(el);

	if (!this.isArray(el)) {
		el = [el]
	}
	for (var i=0; i<el.length; i++) {
		el[i].parentNode.removeChild(el[i])
	}
};

/**
 * Sets the display property of an element to the specified value
 * @param {element || array || string} el Element, array of elements, or ID of desired element
 * @param {Object} d 
 */
Element_class.prototype.setDisplay = function(el,d) {

	el = this.get(el);

	if (!this.isArray(el)) {
		el = [el]
	}
	for (var i=0; i<el.length; i++) {
		el[i].style.display = d;
	}
};

/**
 * Sets the visibility property of a desired element
 * @param {element || array || string} el Element, array of elements, or ID of element
 * @param {Object} d
 */
Element_class.prototype.setVisibility = function(el,d) {
	el = this.get(el);

	if (!this.isArray(el)) {
		el = [el]
	}
	for (var i=0; i<el.length; i++) {
		el[i].style.visibility = d;
	}
};


/**
 * Remove all nodes under a specified element
 * @param {element || string} el Element handle or ID of element
 */
Element_class.prototype.removeChildNodes = function(el) {

	el = this.get(el);

	while (el.childNodes.length) {
		el.removeChild(el.firstChild);
	}
	return el;

};

/**
 * An extension of the native cloneNode() which also strips DOM events
 * @param {element} el Element(s) to clone
 * @param {Object} cloneChildren
 */
Element_class.prototype.cloneNode = function(el, cloneChildren) {
	//prevents IE from cloning events
	var cloneChildNodes = (cloneChildren) ? cloneChildren : false;

	if (document.all) {

		var node = el.outerHTML;

		if (cloneChildNodes && el.innerHTML) {
			node.innerHTML = el.innerHTML;
		}

		var container = document.createElement("DIV");
		container.innerHTML = node;

		node = container.firstChild;

	} else {
		var node = el.cloneNode(cloneChildNodes);
	}

	return node;

};

/**
 * Find the first parent with a given tag name
 * @param {Object} el
 * @param {Object} tag
 * @param {Object} includeSelf
 */
Element_class.prototype.getParent = function(el, tag, includeSelf) {

	var el = this.get(el);

	if (!tag) { tag = el.tagName; }

	if (!includeSelf && el.parentNode) { // grab immediate parent
		el = el.parentNode;
	}

	if (el.tagName && el.tagName.match(/^BODY$/i) && !tag.match(/^BODY$/i)) {
		return null;
	}

	if (el.nodeType == 1 && el.tagName.toLowerCase() == tag.toLowerCase()) {
		return el;
	}
	else {
		return this.getParent(el.parentNode, tag, true);
	}
}



/**
 * Set the innerHTML of a node, the optional third parameter allows you to append rather than overwrite
 * @param {element} el Parent node to set 
 * @param {string} v innerHTML string
 * @param {boolean} [appendV] If true, append, else overwrite 
 */
Element_class.prototype.setHTML = function(el,v,appendV) {
	el = this.get(el);

	if (!this.isArray(el)) {
		el = [el]
	}
	for (var i=0; i<el.length; i++) {
			el[i].innerHTML = (appendV) ? (el[i].innerHTML+v) : v;
	}
};

/**
 * parseSelector finds and elements based on the selector string.  You can match based on tag name, attributes, and styles, as well as stack selectors.
 * See <a href="http://wiki.wsod.local/wsodwiki/index.php/Element.parseSelector:Dev">http://wiki.wsod.local/wsodwiki/index.php/Element.parseSelector:Dev</a> 
 * for much more info. 
 * @example Element.parseSelector('tr.highlight', myTable);             // returns all TRs belonging to class highlight within myTable
Element.parseSelector('input[type="checkbox"]', myForm);    // returns all check boxes
Element.parseSelector('div[position=..'absolute'] ', myDiv);   // returns all divs with absolute positioning
 * @param {string} selector The selector string to search for
 * @param {element} [node] The parent element to search under.  It is important to try and specify as small a subset of the DOM as possible by 
 * 		   setting this parent element, as running parseSelector on the entire DOM can get quite slow
 * @param {string || number} [specific] This will allow you to return a specific element from the matched list, 
 * 		   valid options are "first", "last", or any number for the nth match
 */
Element_class.prototype.parseSelector = function() {

	var context = this;
	var SEPERATOR = /\s*,\s*/;
	
	function parseSelector(selector, node, num) {

		node = node || document.documentElement;
		node = this.get(node);

		var argSelectors = selector.split(SEPERATOR);
		var result = [];
		
		for(var i = 0; i < argSelectors.length; i++) {

			// if the selector starts with #, we can use getElementById to improve performance
			// only do this if we're searching from the root (selectors like '.myDiv #myEl' don't make much sense,
			// but should still work as expected).
			if(node == document.documentElement) {
				var matches = argSelectors[i].match(/^\s*#([^\s.:@[~+>]*)\s+(.*)$/); // check for simple #id
				if(matches) {
					node = document.getElementById(matches[1]) || [];
					argSelectors[i] = matches[2];
				}
			}

			var stream = toStream(argSelectors[i]), prevToken;

			if (this.isArray(node)) {
				var nodes = node;
				// remove * and " " put in by toStream if it starts with a non alphanumeric
				if (!argSelectors[i].match(/^[A-Za-z1-9]/)) {
					while (stream[0] && stream[0].match(/[* ]/)) { stream.shift(); }
				}
			}
			else {
				var nodes = [node]
			}

			for(var j = 0;j < stream.length;) {

				var token = stream[j++];

				var args = '';
				if (token == "[") {
					args = stream[j];
					while(stream[j++] != ']' && j < stream.length) { args += stream[j] };
					args = args.slice(0, -1);
					var filter = "";
				}
				else {
					var filter = stream[j++];
				}

				if(stream[j] == '(') {
					while(stream[j++] != ')' && j < stream.length) args += stream[j];
					args = args.slice(0, -1);
				}

				prevToken = token;
				nodes = select(nodes, token, filter, args);
			}
			result = result.concat(nodes);
		}
		
		// simple selection of an individual node
		  if (num != undefined) {

			if (result.length) {
				var REMatch;

				if (num == "first") {
					return result[0]
				}
				else if (num == "last") {
					return result[result.length-1]
				}
				else if (REMatch = String(num).match(/nth\((.*)\)/) || num == "even") { // even is the same as nth(2)
					if (num == "even") num = 2;
					else num = REMatch[1];

					var result2 = [];
					for (var i=0,len=result.length; i<len;i++) {
						if (i%num == 0) { result2.push(result[i]); }
					}
					return result2;
				}
				else if (num == "odd") {
					var result2 = [];
					for (var i=0,len=result.length; i<len;i++) {
						if (i%2 != 0) { result2.push(result[i]); }
					}
					return result2;
				}
				else if (!isNaN(num) && result.length >= num) {
					return result[num]
				}
				else {
					return null; // num passed, but no matches or unsupported type
				}
			}
			else {
				return null;
			}

		  }

		return result;
	}

	var WHITESPACE = /\s*([\s>+~(),]|^|$)\s*/g;
	var IMPLIED_ALL = /([\s>+~,]|[^(]\+|^)([#.:@])/g;
	var STANDARD_SELECT = /^[^\s>+~]/;
	var STREAM = /[\s#.:>+~[\]()@!]|[^\s#.:>+~[\]()@!]+/g;

	function toStream(selector) {
		var stream = selector
			.replace(WHITESPACE, '$1')
			.replace(IMPLIED_ALL, '$1*$2');
		if(STANDARD_SELECT.test(stream)) {
			stream = ' ' + stream;
		}
		return stream.match(STREAM) || [];
	}

	function select(nodes, token, filter, args) {
		return (selectors[token]) ? selectors[token](nodes, filter, args) : [];
	}

	var util = {
		toArray: function(enumerable) {
			var a = [];
			for(var i = 0; i < enumerable.length; i++) a.push(enumerable[i]);
			return a;
		},

		push: function(arr,val) {
			arr.push(val)
      		//for(var i = 1; i < arguments.length; i++) arr[arr.length] = arguments[i];
      		return arr.length;
    	}
	};

	var dom = {
		isTag: function(node, tag) {
			return (tag == '*') || (
				tag.toLowerCase() == node.nodeName.toLowerCase().replace(':html', '')
			);
		},

		previousSiblingElement: function(node) {
			do node = node.previousSibling; while(node && node.nodeType != 1);
			return node;
		},

		nextSiblingElement: function(node) {
			do node = node.nextSibling; while(node && node.nodeType != 1);
			return node;
		},

		hasClass: function(name, node) {
			return (node.className || '').match('(^|\\s)'+name+'(\\s|$)');
		},

		getByTag: function(tag, node) {
			/*	IE5.x does not support document.getElementsByTagName("*")
				therefore we're falling back to element.all */
			if(tag == '*') {
			  var nodes = node.getElementsByTagName(tag);
			  if(nodes.length == 0 && node.all != null) return node.all
			  return nodes;
		  }
			return node.getElementsByTagName(tag);
		}
	};

	var selectors = {
		'#': function(nodes, filter) {
			for(var i = 0; i < nodes.length; i++) {
				if(nodes[i].getAttribute('id') == filter) return [nodes[i]];
			}
			return [];
		},

		' ': function(nodes, filter) {
			var result = [];
			for(var i = 0; i < nodes.length; i++) {
				result = result.concat(util.toArray(dom.getByTag(filter, nodes[i])));
			}
			return result;
		},

		'>': function(nodes, filter) {
			var result = [];
			for(var i = 0, node; i < nodes.length; i++) {
				node = nodes[i];
				for(var j = 0, child; j < node.childNodes.length; j++) {
					child = node.childNodes[j];
					if(child.nodeType == 1 && dom.isTag(child, filter)) {
						result.push(child);
					}
				}
			}
			return result;
		},

		'.': function(nodes, filter) {
			var result = [];
			for(var i = 0, node; i < nodes.length; i++) {
				node = nodes[i];
				if(dom.hasClass([filter], node)) result.push(node);
			}
			return result;
		},

		'!': function(nodes, filter) {
			var result = [];
			for(var i = 0, node; i < nodes.length; i++) {
				node = nodes[i];
				if(!dom.hasClass([filter], node)) result.push(node);
			}
			return result;
		},

		':': function(nodes, filter, args) {
			return (pseudoClasses[filter]) ? pseudoClasses[filter](nodes, args) : [];
		},


		'+': function(nodes, filter) {
			var result = [];
			for(var i = 0, node; i < nodes.length; i++) {
				node = nodes[i];
				var sibling = parseSelector.dom.nextSiblingElement(node);
				if(sibling && parseSelector.dom.isTag(sibling, filter)) {
					result.push(sibling);
				}
			}
			return result;
		},
		'~': function(nodes, filter) {
			var result = [];
			for(var i = 0, node; i < nodes.length; i++) {
				node = nodes[i];
				var sibling = parseSelector.dom.previousSiblingElement(node);
				if(parseSelector.dom.isTag(sibling, filter)) result.push(sibling);
			}


			return result;
		},
		'[': function(nodes, filter, args) { // CSS Attribute
			args = args.replace(/'/g,'"'); // allow single quotes

			var attributeProps = [];
			if (!/[<>=]/.test(args)) { // has operator test
				attributeProps = ["",args,"",""];
			}
			else {
				var params = args.match(/([^!^$*\/.<>=]*)(!\*=|\*=|\$=|!\$=|\^=|\/=|!\/=|<=|>=|<|>|!=|=)(\.*)(i?)(["'`])([^\5]*)(\5)/);
									//   (attName)       (operator)                                 (type)   (caseinsenstive)[quote](value)[quote]
				if (params) { attributeProps = params; }
			}

			//alert(attributeProps )
			attributeProps = {name:attributeProps[1],operator:attributeProps[2],isStyle:attributeProps[3]=="..",isProperty:attributeProps[3]==".",casei:attributeProps[4]?true:false,value:attributeProps[6],isValue:(attributeProps[5]=="`")};

			// Leave this line for debuging purposes
			//alert(args + "\n att: " + attributeProps.name + "\n operator: " + attributeProps.operator + "\n val: "  + attributeProps.value + "\n isStyle: " + attributeProps.isStyle + "\n isProperty: " + attributeProps.isProperty + "\n isValue: " + attributeProps.isValue + "\n casei: "  + attributeProps.casei)

			if (attributeProps.casei) { attributeProps.value = attributeProps.value.toLowerCase(); }

			var result = [];
			for(var i = 0, node, att, val, el; i < nodes.length; i++) {
				node = el = nodes[i];

				if (attributeProps.isStyle) {
					att = context.getStyle(node,attributeProps.name);
					if (!att) continue;
				}
				else if (attributeProps.isProperty) {
					if (node[attributeProps.name] != undefined) {
						var att = node[attributeProps.name];
					}
					else {
						continue;
					}
				}
				else {
					att = node.getAttribute(attributeProps.name);
					if (!att) continue;
				}

				if (/[*^$\/]/.test(attributeProps.operator)) { // so .match complies
					att = String(att)
				}

				if (attributeProps.casei) { att = att.toLowerCase(); }

				val = attributeProps.value;

				//alert("Tag: " + el.tagName + ", ID: " + el.id + " , Att: " + att + ", Operator: " + attributeProps.operator + ", Val: " + val);
				if (attributeProps.isValue) { val = eval(val.replace(/`/g,"'")); }

				if (!attributeProps.operator) {
					result.push(nodes[i])
				}
				else {


					switch(attributeProps.operator){
						case '=': if (att == val) result.push(node); break;
						case '!=': if (att != val) result.push(node); break;
						case '*=': if (att.match(val)) result.push(node); break;
						case '!*=': if (!att.match(val)) result.push(node); break;
						case '^=': if (att.match('^'+val)) result.push(node); break;
						case '!^=': if (!att.match('^'+val)) result.push(node); break;
						case '$=': if (att.match(val+'$')) result.push(node); break;
						case '!$=': if (!att.match(val+'$')) result.push(node); break;
						case '/=': if (att.match(val)) result.push(node); break;
						case '!/=': if (!att.match(val)) result.push(node); break;
						case '>=': if (att >= val) result.push(node); break;
						case '>': if (att > val) result.push(node); break;
						case '<=': if (att <= val) result.push(node); break;
						case '<': if (att < val) result.push(node); break;
					}
				}
			}
			return result;

		}

	};

	parseSelector.selectors			= selectors;
	var pseudoClasses = { };
	parseSelector.pseudoClasses 			= pseudoClasses;
	parseSelector.util 				  = util;
	parseSelector.dom 				  = dom;
	return parseSelector.apply(this,arguments);
};

/*---------------------------------
	is -
	Is an element a selector?
----------------------------------*/

Element_class.prototype.is = function( domNode, selector, parent, propagate ) {

	parent = parent || domNode.parentNode;
	
	var queriedEls = this.parseSelector(selector, parent);
		
	var  i
		,l = queriedEls.length;
	
	while(domNode && domNode !== parent) {
		
		for(i = 0; i < l; i++) {
			if(domNode === queriedEls[i]) {
	
				return true;
			}
		}
		if(propagate) {
			domNode = domNode.parentNode;
			continue;
		}
		break;
	}
	return false;
};


Element_class.prototype.forEach = function(el, callback, context) {

	var returnEls = [];

	if (typeof el == "string") {
		el = this.parseSelector(el);
	}
	else if (!this.isArray(el)) {
		el = [el]
	}

	var success;

	for (var i=0,elLen = el.length; i<elLen; i++) {
		success = context ? callback.call(context,el[i],i,el) : callback(el[i],i,el)
		if (success === false) {
			break;
		}
		returnEls.push(el[i]);
	}

	return returnEls;
}

/**
 * Insert an element before another
 * @param {Object} el
 * @param {Object} sibling
 */
Element_class.prototype.insertBefore = function (el, sibling) {

	el = this.get(el);	if (!el) return;

	sibling = this.get(sibling);

	if (!el || !sibling || !sibling.parentNode)
	{
		return null;
	};

	sibling.parentNode.insertBefore(el, sibling);
};

/**
 * Insert an element after another
 * @param {element} el
 * @param {Object} sibling
 */
Element_class.prototype.insertAfter = function (el, sibling) {

	el = this.get(el);	if (!el) return;

	sibling = this.get(sibling);

	if (!el || !sibling || !sibling.parentNode)
	{
		return null;
	};

	return sibling.nextSibling ? sibling.parentNode.insertBefore(el, sibling.nextSibling) : sibling.parentNode.appendChild(el);
};

//2006-02-16 AR - fixed this so that an null tagName would return the next element
/**
 * Returns the next sibling of a given tagname
 * @param {element} el
 * @param {string} tagName
 * @return {element} The next sibling
 */
Element_class.prototype.nextElement = function(el, tagName) {
	tagName = tagName ? String(tagName).toLowerCase() : null;

	var sibling = this.get(el);
	while(sibling = sibling.nextSibling) {
		if (sibling.nodeType == 1 && ( tagName == null || sibling.tagName.toLowerCase() == tagName ) ) {
			return sibling;
		}
	}
	return null;
}

//2006-02-16 AR - added previousElement
/**
 * Returns the previous sibling of a given tagname
 * @param {element} el
 * @param {string} tagName
 * @return {element} The previous sibling
 */
Element_class.prototype.previousElement = function(el, tagName) {
	tagName = tagName ? String(tagName).toLowerCase() : null;
	var sibling = this.get(el);
	while(sibling = sibling.previousSibling) {
		if (sibling.nodeType == 1 && ( tagName == null || sibling.tagName.toLowerCase() == tagName ) ) {
			return sibling;
		}
	}
	return null;
}

/**
 * Gets the {x: , y: } pair of coordinates for the element relative to the body
 * @param {Object} el
 * @return {Object} {x: , y: } object coordinate position
 */
Element_class.prototype.getXY = function(el) {

	el = this.get(el);	if (!el) return;

	var x = 0, y = 0;

	while (el.offsetParent) {
		x += el.offsetLeft;
		y += el.offsetTop;
		el = el.offsetParent;
	}

	return { x: x, y: y };
};

/**
 * Sets the position of an element relative to the body
 * @param {element} el
 * @param {number} x
 * @param {number} y
 */
Element_class.prototype.setXY = function(el, x, y) {

	el = this.get(el);	if (!el) return;

	if (!this.isArray(el)) {
		el = [el]
	}
	for (var i=0; i<el.length; i++) {
		if (x !== null) el[i].style.left = x + "px";
		if (y !== null) el[i].style.top = y + "px";
	}
};

/**
 * Gets the {width:, height:} object of the element's total size
 * @param {element} el
 * @return {object} {width: height:} size object
 */
Element_class.prototype.getSize = function(el) {

	el = this.get(el);	if (!el) return;

	var height = el.offsetHeight;
	var width = el.offsetWidth;

	return { height: height, width: width };
};

// more useful if in same units as pos
/**
 * Gets the {x: width, y: height} representation of the element's total size
 * @param {element} el
 * @return {object} {x: , y:} size representation
 */
Element_class.prototype.getSizeXY = function(el) {
	var size = this.getSize(el);
	return {x: size.width, y: size.height};
};

/**
 * Sets the size of an element(s)
 * @param {element} el
 * @param {number} width pixel number
 * @param {number} height pixel number
 */
Element_class.prototype.setSize = function(el, width, height) {

	el = this.get(el);	if (!el) return;

	if (!this.isArray(el)) {
		el = [el]
	}
	for (var i=0; i<el.length; i++) {
		this.setWidth(el[i], width);
		this.setHeight(el[i], height);
	}
};

Element_class.prototype.setWidth = function(el, width) {

	el = this.get(el);	if (!el) return;

	if (!this.isArray(el)) {
		el = [el]
	}
	for (var i=0; i<el.length; i++) {
		el[i].style.width = width + "px";
	}
};

Element_class.prototype.setHeight = function(el, height) {

	el = this.get(el);	if (!el) return;

	if (!this.isArray(el)) {
		el = [el]
	}
	for (var i=0; i<el.length; i++) {
		el[i].style.height = height + "px";
	}
};

Element_class.prototype.getBorderSize = function(el) {

	el = this.get(el);

	var height = el.offsetHeight - el.clientHeight;
	var width = el.offsetWidth - el.clientWidth;

	return { height: height, width: width };
}


// -------------------------------------------------------
//  className modifications
// -------------------------------------------------------

/**
 * Changes the className of an element, the optional third parameter will allow you to remove the className
 * @param {element} el
 * @param {string} classname
 * @param {boolean} [b]
 */
Element_class.prototype.switchClass = function(el, classname, b) {

	el = this.get(el);	if (!el) return;

	if (!this.isArray(el)) {
		el = [el]
	}

	if (b) {
		this.addClass(el, classname);
	}
	else {
		this.removeClass(el, classname);
	}

	if (el.length) {
		return el[0].className;
	}

};

/**
 * Removes a CSS class and replaces it with a new class
 * @param {element} el 
 * @param {string} sClassNameOld Old class to remove
 * @param {string} sClassNameNew New class to add
 * @param {boolean} bConditional
 */
Element_class.prototype.replaceClass = function(el, sClassNameOld, sClassNameNew, bConditional) {

	el = this.get(el);	if (!el) return;

	if (!this.isArray(el)) {
		el = [el]
	}

	if(bConditional) {

		for(var i=0;i<el.length;i++) {

			if(this.hasClass(el[i],sClassNameOld)) {

				this.removeClass(el[i],sClassNameOld);
				this.addClass(el[i],sClassNameNew);

			}

		}

	} else{

		this.removeClass(el, sClassNameOld);
		this.addClass(el, sClassNameNew);

	}

	if (el.length) {
		return el[0].className;
	}

};

/**
 * Append a CSS class to an element
 * @param {element} el
 * @param {string} classname
 */
Element_class.prototype.addClass = function(el, classname) {

	el = this.get(el);	if (!el) return;

	if (!this.isArray(el)) {
		el = [el]
	}
	for (var i=0; i<el.length; i++) {
		if (!this.hasClass(el[i], classname)) {
    			el[i].className += (el[i].className?" ":"") + classname;
		}
	}

	if (el.length) {
		return el[0].className;
	}
};

/**
 * Remove a CSS class from an element
 * @param {element} el
 * @param {string} classname
 */
Element_class.prototype.removeClass = function(el, classname) {

	el = this.get(el);

	if (!this.isArray(el)) {
		el = [el]
	}

	var re = this._getClassnameRegEx(classname);

	for (var i=0; i<el.length; i++) {
			el[i].className = el[i].className.replace(re, "$1$3");
	}

	if (el.length) {
		return el[0].className;
	}

};

/**
 * Removes a CSS class if it already exists on an element, else it adds it in
 * @param {element} el 
 * @param {string} classname
 */
Element_class.prototype.toggleClass = function(el, classname) {
	el = this.get(el);
	//alert(el.id)

	if (!this.isArray(el)) {
		el = [el]
	}

	for (var i=0; i<el.length; i++) {
		if (this.hasClass(el[i], classname)) {
			this.removeClass(el[i], classname);
		} else {
			this.addClass(el[i], classname);
		}
	}

	if (el.length) {
		return el[0].className;
	}
};

/**
 * Checks to see if a CSS class exists on an element
 * @param {Object} el
 * @param {Object} classname
 * @return {boolean}
 */
Element_class.prototype.hasClass = function(el, classname) {

	el = this.get(el);

	return (el.className && el.className.match(this._getClassnameRegEx(classname)) != null);
};

Element_class.prototype._getClassnameRegEx = function(classname) {
	return new RegExp("(\\s|^)(" + classname + ")(\\s|$)", "g")
};

// -------------------------------------------------------
//  style gets and sets
// -------------------------------------------------------

/**
 * Gets the computed style
 * @param {element} el
 * @param {string} styleProp
 */
Element_class.prototype.getStyle = function (el, styleProp) {

	el = this.get(el);	if (!el) return;

	if (document.defaultView && document.defaultView.getComputedStyle) { // Mozilla and Safari

		var computedStyle = document.defaultView.getComputedStyle(el, null);
		return (computedStyle) ? computedStyle.getPropertyValue(styleProp) : null;

	} else if (el.currentStyle) { // IE

		styleProp = styleProp.replace(/\-(.)/g, function () {

			return arguments[1].toUpperCase();

		});

		return el.currentStyle[styleProp];

	}

	return null;

}

/**
 * Set the element's inline style with a css string
 * @param {element} el
 * @param {string} styles String style representation like 'width:200px; color: #CCC;'
 */
Element_class.prototype.setStyle = function (el, styles) {

	el = this.get(el);	if (!el) return;

	var pairs = [];
	styles = styles.split(";");
	for (var i=0; i<styles.length; i++) {
		//var nv = styles[i].split(":");
		var nv = styles[i].replace(":","{:}").split("{:}");
		if (nv.length > 1) {
			nv[0] = nv[0].replace(/\-(.)/g, function() {
				return arguments[1].toUpperCase();
			}).replace(/\s/g, "");
			pairs.push({n:nv[0],v:nv[1].replace(/^\s*|\s*$/g, "")});
		}
	}

	if (!this.isArray(el)) {
		el = [el]
	}

	var attributeMap = {
		"float":["cssFloat","styleFloat"]
	}

	for (var i=0; i<el.length; i++) {
		for (var j=0; j<pairs.length; j++) {
			if (attributeMap[pairs[j].n]) {
				for (var k = 0; k <attributeMap[pairs[j].n].length; k++) {
					pairs.push({n:attributeMap[pairs[j].n][k],v:pairs[j].v});
				}
			}
			el[i].style[pairs[j].n] = pairs[j].v;
		}
	}

}



// -------------------------------------------------------
// 	Element Helpers
// -------------------------------------------------------


Element_class.prototype.isArray = function(o) {
	return (o instanceof Array);
};


if (typeof WSDOM != "undefined") {
	WSDOM.using("WSDOM.Element.3", "WSDOM.Events.2");
	WSDOM.defineClass("Element", null, Element_class);
	WSDOM.loadSingleton("WSDOM.Element.3");
}
else {
	Element = new Element_class();
}


/* -- Loaded:/includes/jslib/Element/Element.3.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


/*
Element.extras.js
An extended library to handle DOM Elements
Works with Element 3+

Documentation at http://barney.wallst.com/wsodwiki/index.php/Element.2.js_:Dev

Element.isInsideOf 
Element.isInsideOfNS 
Element.isInsideOfEW 
Element.debug
Element.setOpacity 
Element.setDisabled

ElementObject (dom style syntax element commands)

*/




Element_class.prototype.getParentBySelector = function(el, selector, includeSelf) {

	el = this.get(el);
	var pNode = includeSelf ? el : el.parentNode; 

	selector = selector.replace(/\s+/," ").split(" ");
	var levels = selector.length;
	var level = 0;
	var selectorType, isMatch, isTag, isClass;

	function getSelectorType() {
		var sel = selector[level];
		
		selectorType = {tag:sel}; // assume tag selection if nothing below passes

		// id
		if (sel.match(/(\D*)\#(\D*)/)) { selectorType.tag = RegExp.$1; selectorType.id= RegExp.$2; }

		// css attribute
		else if(sel.match(/(.*)\[([^^$*]*?)((\*=|\$=|\^=|=)+["'](.*)["'])?]/)) {
			selectorType.tag = RegExp.$1; selectorType.attribute = RegExp.$2; selectorType.operator = RegExp.$4; selectorType.value = RegExp.$5;
		}

		// class
		else if (sel.match(/(\D*)\.(\D*)/)) { selectorType.tag = RegExp.$1; selectorType.className = RegExp.$2; }

	}

	getSelectorType();
	// loop through parent nodes checking for selector
	while (pNode && !pNode.tagName.match(/^BODY$/i)) {

		isMatch = false;
		isTag = pNode.tagName.match(new RegExp("^"+selectorType.tag.replace(/([*])/,"\\$1")+"$","i")) || selectorType.tag == "*" || selectorType.tag == "";
		isClass = selectorType.className && this.hasClass(pNode,selectorType.className);

		if (isTag && selectorType.attribute) {
			var att = pNode.getAttribute(selectorType.attribute);
			if (!selectorType.operator) {
				if (att) isMatch = true;
			}
			else { 
				switch(selectorType.operator){
					case '*=': ;if (att.match(selectorType.value)) isMatch = true; break;
					case '=': if (att == selectorType.value) isMatch = true; break;
					case '^=': if (att.match('^'+selectorType.value)) isMatch = true; break;
					case '$=': if (att.match(selectorType.value+'$')) isMatch = true;
				}	
			}
		}
		else if (isTag) {
			if (isClass) { isMatch = true; }
			else if (selectorType.tag && !selectorType.className) { isMatch = true; }
			else if (selectorType.id && pNode.getAttribute("id") == selectorType.id) { isMatch = true; }

		}
		else if (isTag  && isClass) { isMatch = true; }

		if (isMatch) {
			if (level == levels-1) {
				return pNode;
			}
			level++;
			getSelectorType();
		}

		pNode = pNode.parentNode || null;

	}

	return null; // no match

}



Element_class.prototype.isOnScreen = function(el,considerPosition) {

	el = Element.get(el); if (!el) { return false; }
	var pNode = el;
	while(pNode && pNode.tagName.toUpperCase() != "HTML") {
		//alert(pNode.style.display + " " + pNode.tagName + (pNode.id?("#"+pNode.id):"") + " + " + Element.getStyle(pNode,"display"))
		var curStyle = Element.getStyle(pNode,"display");
		if (curStyle == "none" || curStyle == null || Element.getStyle(pNode,"visibility") == "hidden") {
			return false;
		}
		pNode = pNode.parentNode;
	}

	if (considerPosition) {
		var elPos = Element.getXY(el);
		if (elPos.x < 0 || elPos.y < 0) {
			return false;
		}
	}

	return true;
}



Element_class.prototype.isInsideOf = function(pos, x, y, width, height) {
	if (this.isInsideOfEW(pos, width, x) && this.isInsideOfNS(pos, height, y)) {
		return true;
	}
	return false;
};

Element_class.prototype.isInsideOfEW = function(pos, width, x) {
	if (x > pos.x && x < pos.x + width) {
		return true;
	}
	return false;
};

Element_class.prototype.isInsideOfNS = function(pos, height, y) {
	if (y > pos.y && y < pos.y + height) {
		return true;
	}
	return false;
};


Element_class.prototype.setOpacity = function(el, opacity) {

	el = this.get(el); 	if (!el) return;


	if (!this.isArray(el)) {
		el = [el]
	}

	for (var i=0; i<el.length; i++) {	


		//try{
			//opacity = (opacity == 100) ? 99.999 : opacity;
			// IE/Win
			el[i].style.filter = "alpha(opacity:"+opacity+")";
	
			// Safari<1.2, Konqueror
			el[i].style.KHTMLOpacity = opacity/100;
	
			// Older Mozilla and Firefox
			el[i].style.MozOpacity = opacity/100;
	
			// Safari 1.2, newer Firefox and Mozilla, CSS3
			el[i].style.opacity = opacity/100;
		//}catch(e){
			//dbg("error setting opacity");
		//}

	}
};


Element_class.prototype.setProperty = function(el,prop,val) {

	el = this.get(el);

	if (!this.isArray(el)) {
		el = [el]
	}
	for (var i=0; i<el.length; i++) {
		el[i][prop] = val;
	}

};

Element_class.prototype.setAttribute = function(el,prop,val) {

	el = this.get(el);

	if (!this.isArray(el)) {
		el = [el]
	}
	for (var i=0; i<el.length; i++) {
		el[i].setAttribute(prop,val);
	}

};

Element_class.prototype.setDisabled = function(el, bool) {
	this.setProperty(el,"disabled",!!bool); // absolute boolean
};


Element_class.prototype.debug = function(el,ElementObjectInstance) {


	var output = [];
	output.push("---------------------------");
	if (ElementObjectInstance) { output.push("Selector: " + ElementObjectInstance.selector); }

	var els = (el instanceof Array) ? el : [el];
	var pos, size;

	for (var i=0; i<els.length;i++) {
		if (els.length > 1) { output.push(i + ": " + (els[i].tagName || "")); }

		pos = this.getXY(els[i]);

		size= this.getSize(els[i]);
		output.push("  x: " + pos.x + " y: " + pos.y + " / w: " + size.width + " h: " + size.height);

		//output.push("  Style: " + this.getStyle(els[i]));
		if (els[i].className) { output.push("  Class: " + (els[i].className)) };
		if (els[i].id) { output.push("  Id: " + (els[i].id )); }
		output.push("");
	}

	return output.join("\n")+"\n";
}




Element = new Element_class();




/*
	var eObj = new ElementObject("h2");
	eObj.setStyle("color:red");
*/
function ElementObject(el) {

	this.selector = (typeof el == "string") ? el : "element";
	this.elementInstance = new Element_class();

	this.el = this.elementInstance.isArray(el) ? el :this.elementInstance.get(el);

	if (!this.el) {
		this.el = this.elementInstance.parseSelector(arguments[0],arguments[1]||null,arguments[2]||null); // allow parseSelector parent/which to come through
	}

	var noChangeMethodsRE = new RegExp(/_getClassnameRegEx|isArray|isInsideOf/);
	var mName;
	for (var i in this.elementInstance) {
		mName = i;
		if (noChangeMethodsRE.test(i)) { // these don't take the element as an argument
			this[mName] = hitch(this.elementInstance,mName,false);	
		}
		else if (/parseSelector/.test(i)) { // these take parent as last param
			this[mName] = hitchAppend(this.elementInstance,mName,false,this.el);	
		}
		else if (/create|debug/.test(i)) {
			this[mName] = hitchAppend(this.elementInstance,mName,false,this.el,this)
		}
		else {
			this[mName] = hitchAppend(this.elementInstance,mName,true,this.el)
		}
	}

	//dwO(this.elementInstance.parseSelector)

	function hitch(obj, methodName) {
		return function() { 
			return obj[methodName].apply(obj, arguments);
		};
	}
	
	// appends or preappends additional arguments to method
	function hitchAppend(obj, methodName, bAppend) {
		//dwO(methodName + " - " +  bAppend)
		var args = [];
		for (var i = 3; i < arguments.length; i++) {
			args.push(arguments[i]);
		}
	
		return function() { 
			var args2 = [];
			for (var i = 0; i < arguments.length; i++) {
				args2.push(arguments[i]);
			}
			return obj[methodName].apply(obj, bAppend?args.concat(args2):args2.concat(args));
		};
	}
}

ElementObject.prototype.toString = function() {


	return this.debug();


}


/* -- Loaded:/includes/jslib/Element/Element.3extras.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


function browserObj() {
	this.platform = ''
	this.version = 0
	this.isNav4 = false
	this.isNav6 = false
	this.isIE4 = false
	this.isIE = false
	this.isMoz = false
	this.isSafari = false
	this.isMajor = false
	this.isMinor = false

	this.agent = navigator.appName.toLowerCase()
	

	if (navigator.appVersion.indexOf('Mac') != -1) {
		this.platform = "mac"
	} else {
		this.platform = "pc"
	}

	//if (this.platform == 'mac') { alert(navigator.appName + ',' + navigator.appVersion + ',' + navigator.userAgent) }

	//var isNav4, isNav6, isIE4, isMajor, isMinor;
	if (this.agent.indexOf('safari') != -1) {
		this.isMajor = true
		this.isSafari = true
	} else if (this.agent.indexOf('gecko') > -1) {
		if (this.agent.indexOf('netscape') > -1) {
			this.isNav6 = true
			this.isMajor = true
			this.isGood = true
		} else {
			this.isMajor = true
			this.isMoz = true
			this.isGood = true
		}
	} else if (this.agent.indexOf('netscape') > -1) {

		if (navigator.appVersion.charAt(0) > "4") {
			this.version = 6
			this.isNav6 = true
			this.isMajor = true
		} else {
			this.version = 4
			this.isNav4 = true;
			this.isMinor = true
		}
	} else {
		this.isIE = true

		var uA = navigator.userAgent.toLowerCase()
		var ind = uA.indexOf("msie")
		uA = uA.substr(ind, uA.length)
		ind = uA.indexOf(";")
		uA = parseFloat(uA.substr(0, ind).replace("msie", ""))
		if (uA >= 5) {
			this.version = uA
			this.isMajor = true
		} else {
			this.version = uA
			this.isIE4 = true;
			this.isMinor = true
		}
	}
}

var browserProps = new browserObj()

function getAbsolutePos (who, debug) {
	x = 0, y = 0

	if (!browserProps.isNav4) {
		while (who.offsetParent != null) {

			if (debug) { alert(who + ',' + who.id + ',' + who.offsetParent + ',' + who.offsetParent.tagName + ',' + who.offsetParent.offsetParent) }

			x += who.offsetLeft
			y += who.offsetTop
			who = who.offsetParent

		}

		x += who.offsetLeft
		y += who.offsetTop
	} else {
		x = who.x
		y = who.y
	}

	point = new pointObj(x, y)
	return point
}

function pointObj(x, y) {
	this.x = x
	this.y = y
	this.toString = function() {
		return 'point object\nx:' + this.x + ',y:' + this.y
	}
}

/* This mouse.js file doesn't invoke a mouse object inherently (as mouse.js does), but rather, provides a function to get to the mouse object */

var gbrowserProps; var gMouse;
function getMouse() {

	gBrowserProps = new browserObj()

	//Netscape 6

	if ( !document.all ) {
		if (window.addEventListener) {
			window.addEventListener("mousemove",watchMouseCoords,true)
		}
	}
	//IE 5+
	if (document.attachEvent) {
		document.attachEvent("onmousemove",watchMouseCoords)
	}
	//IE4
	if (gBrowserProps.isIE4) {
		document.onmousemove = watchMouseCoords
	}
	//Netscape 4
	if (gBrowserProps.isNav4) {
		window.onmousemove = watchMouseCoordsNN
		captureEvents(Event.MOUSEMOVE);
	}
	//Mac
	if (gBrowserProps.platform == "mac") {
		//alert("mac")
		document.onmousemove = watchMouseCoords
	}



	gMouse = new pointObj(0,0);

	return gMouse;

}

function mouseMove(e) {
	watchMouseCoordsNN(e)
}

var m_xOff, m_yOff, m_ev, m_isStandard;

function watchMouseCoords(e) {
	m_ev = (browserProps.isMajor) ? e : event
	if (browserProps.isNav6) {  // need to catch the various implementations of scrollTop
		m_yOff = window.pageYOffset;
		m_xOff = window.pageXOffset;
	} else {

		isStandard = (document.compatMode && document.compatMode == "CSS1Compat") ? true : false;

		/*if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollTop == 0)) {*/

		if (isStandard) {
			m_yOff = document.documentElement.scrollTop;
		} else {
			m_yOff = document.body.scrollTop;
		}
		if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollLeft == 0)) {
			m_xOff = document.documentElement.scrollLeft;
		} else {
			m_xOff = document.body.scrollLeft;
		}
	}
	if (browserProps.isSafari) { m_yOff = 0 };

	gMouse.x = m_ev.clientX + m_xOff
	gMouse.y = m_ev.clientY + m_yOff

	if (gMouse.callback) { gMouse.callback() }

	//window.status = mouse.x + ',' + mouse.y
}

function watchMouseCoordsNN(e) {
	gMouse.x = e.pageX
	gMouse.y = e.pageY
	if (gMouse.NNcallback) { gMouse.NNcallback() }
}

/* -- Loaded:/tdameritrade/common/scripts/mouse.2.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


/* thanks to PPK - http://www.quirksmode.org/viewport/compatibility.html */

function getWindowSize() {
	// returns innerHeight / innerWidth of window
	
	if (self.innerHeight) {
		
		// all except Explorer
		var width = self.innerWidth;
		var height = self.innerHeight;
		
	} else if (document.documentElement && document.documentElement.clientHeight) {
		
		// Explorer 6 Strict Mode
		var width = document.documentElement.clientWidth;
		var height = document.documentElement.clientHeight;
		
	} else if (document.body) {
		
		// other Explorers
		var width = document.body.clientWidth;
		var height = document.body.clientHeight;
		
	};
	
	return { width: width, height: height };
};
		
function getWindowScrollOffset() {
	// returns window's scroll offset
	
	if (typeof window.pageYOffset == 'number') {
		  
		//Netscape compliant
		var x = window.pageXOffset;
		var y = window.pageYOffset;
		
		
	} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
	  
		//DOM compliant
		var x = document.body.scrollLeft;
		var y = document.body.scrollTop;
		
	
	} else if (document.documentElement &&
	  (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
	  
		//IE6 standards compliant mode
		var x = document.documentElement.scrollLeft;
		var y = document.documentElement.scrollTop;
		
	};
	
	return { x: x||0, y: y||0 };
};

function getViewport() {
	// returns viewport boundaries and dimensions as top, left, bottom, right, height, width
	var windowSize = getWindowSize();
	var scrollOffset = getWindowScrollOffset();
	
	var top = scrollOffset.y;
	var bottom = scrollOffset.y + windowSize.height;
	
	var left = scrollOffset.x;
	var right = scrollOffset.x + windowSize.width;
	
	return { 
		top: top,
		left: left,
		bottom: bottom,
		right: right,
		width: windowSize.width,
		height: windowSize.height
	};
};

/* -- Loaded:/includes/jslib/viewport.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


function ArraySortable () {
	var newArraySortable = new Array();

	if (arguments.length) {

		for (var i = 0; i < arguments.length; i++) {
			newArraySortable[i] = arguments[i];
		}
	}

	newArraySortable.sortByField = Array_sortByField;

	return newArraySortable;
}

// ArraySortable.prototype = new Array;
// Array.prototype.sortByField = Array_sortByField

function Array_sortByField (field, order, caseInsensitive) {
	this.sortProperties = new Object();
	this.sortProperties.sortField = field;
	this.sortProperties.isAscending = (order > 0);
	this.sortProperties.caseInsensitive = caseInsensitive;

	for (var i in this) {

		if (typeof(this[i]) == "object") {
			this[i].sortProperties = new Object();
			this[i].sortProperties.parent = this;
		}
	}

	this.sort(Array_sortByFieldSort);
}

function Array_sortByFieldSort (a, b) {
	var sortField = a.sortProperties.parent.sortProperties.sortField;
	var isAscending = a.sortProperties.parent.sortProperties.isAscending;
	var aField = a[sortField];
	var bField = b[sortField];

	if (a.sortProperties.parent.sortProperties.caseInsensitive && typeof(aField) == "string") aField = aField.toLowerCase();
	if (b.sortProperties.parent.sortProperties.caseInsensitive && typeof(bField) == "string") bField = bField.toLowerCase();

	if (aField < bField) return (isAscending) ? -1 : 1;
	if (aField > bField) return (isAscending) ? 1 : -1;

	return 0;
}

function SortByField (arr, sortField, sortOrder, caseInsensitive) {

	function Sort (a, b) {

		var aField = a[sortField];
		var bField = b[sortField];

		if (caseInsensitive && typeof(aField) == "string") aField = aField.toLowerCase();
		if (caseInsensitive && typeof(bField) == "string") bField = bField.toLowerCase();

		if (aField < bField) return (sortOrder > 0) ? -1 : 1;
		if (aField > bField) return (sortOrder > 0) ? 1 : -1;
		return 0;
	}

	if (arguments.length < 2) return arr.sort();
	if (arguments.length < 3) sortOrder = 1;
	arr.sort(Sort);
	return arr;
}

/* -- Loaded:/includes/jslib/arrayFunctions.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


function CopyObj(obj) {

	var Copy;
	
	if (obj != null){

		Copy = new obj.constructor;

		for (var property in obj) {

			if (typeof(obj[property]) == "object") {
				Copy[property] = CopyObj(obj[property]);

			} else {
				Copy[property] = obj[property];
			}
		}
	}

	return Copy;
}

/* -- Loaded:/includes/jslib/CopyObj.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


// Yep, it slices, dices and serialices!
Serializer = function () {

	this._nameExclusions = {};
	this._typeExclusions = {};
	// client-side will encode by default unless you set this to false;
	this._encode = true;
	this._strictJson = true;
	this._safeDeserialize = false;

	this._sBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

};

// toss the object into an JS string
Serializer.prototype.serialize = function (o) {

	this._data = [];
	this._serializeNode([o], o, 0);
	this._data = this._data.join("");
	this._data = this._data.replace(/,}/g, "}");
	this._data = this._data.replace(/,]/g, "]");
	this._data = this._data.substr(0, this._data.length-1);

	if (this.allowEncoding()) {

		this._data = this.base64encode(this._data);

	}

	return this._data;

}

// exclude certain named elements from serialization
Serializer.prototype.addNameExclusion = function () {

	var l = arguments.length;

	for (var i=0; i<l; i++) {

		this._nameExclusions[arguments[i]] = true;

	}

}

// remove exclusion of named elements
Serializer.prototype.removeNameExclusion = function () {

	var l = arguments.length;

	for (var i=0; i<l; i++) {

		this._nameExclusions[arguments[i]] = false;

	}

}

// exclude certain data types from serialization
Serializer.prototype.addTypeExclusion = function () {

	var l = arguments.length;

	for (var i=0; i<l; i++) {

		this._typeExclusions[arguments[i].toLowerCase()] = true;

	}

}

// remove exclusion of data types
Serializer.prototype.removeTypeExclusion = function () {

	var l = arguments.length;

	for (var i=0; i<l; i++) {

		this._typeExclusions[arguments[i].toLowerCase()] = false;

	}

}

// getter/setter specifies whether to follow strict Json serialization
Serializer.prototype.requireStrictJson = function (value) {

	if (typeof(value) != "undefined") {

		this._strictJson = value;

	}

	return this._strictJson;

}

// getter/setter specifies whether we need to check for wellformedness before deserializing
Serializer.prototype.requireSafeDeserialize = function (value) {

	if (typeof(value) != "undefined") {

		this._safeDeserialize = value;

	}

	return this._safeDeserialize;

}

// getter/setter specifies if results should be encoded
Serializer.prototype.allowEncoding = function (value) {

	if (typeof(value) != "undefined") {

		this._encode = value;

	}

	return this._encode;

}

Serializer.prototype._unicodeEscape = function (str) {
	var dec = str.charCodeAt(0);
	var hexStr = "\\u";
	var hexVals = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ];

	var hexPlace;

	// Loop unrolled for speed
	hexPlace = 4096 // 16^3
	hexStr += hexVals[Math.floor(dec / hexPlace)];
	dec = dec % hexPlace;

	hexPlace = 256  // 16^2
	hexStr += hexVals[Math.floor(dec / hexPlace)];
	dec = dec % hexPlace;

	hexPlace = 16   // 16^1
	hexStr += hexVals[Math.floor(dec / hexPlace)];
	dec = dec % hexPlace;

	hexPlace = 1    // 16^0
	hexStr += hexVals[Math.floor(dec / hexPlace)];
	dec = dec % hexPlace;

	return hexStr;
}

// serialize each member of the object
Serializer.prototype._serializeNode = function (o, startObj, depth, parentType) {

	var t, f, d1, d2;

	// loop through all of the members
	for (var i in o) {

		if (o[i] === null) {
			t = "null";
		} else {
			t = typeof(o[i]);
		}


		f = t == "object" ? true : false;
		t = t == "object" && typeof(o[i].length) != "undefined" && o[i].constructor == Array ? "array" : t;

		if (!this._typeExclusions[t] && !this._nameExclusions[i] && !(this._strictJson && t == "function")) {

			switch (t) {

				case "string" :

					d1 = "\"";
					d2 = "\"";
					break;

				case "object" :

					d1 = "{";
					d2 = "}";
					break;

				case "array" :

					d1 = "[";
					d2 = "]";
					break;

				default :

					d1 = "";
					d2 = "";
					break;

			 }

			// build the JS string for this node
			if (isFinite(i) && !(parentType && parentType == "object")) {

				this._data.push(d1);

			} else {

				var n = typeof(i) == "string" ? "\"" + i + "\"" : i;
				this._data.push(n + ":" + d1);

			}

			if (f) {

				if (depth == 0 || o[i] !== startObj) {

					this._serializeNode(o[i],null,null,t);

				}

			} else {

				if (t == "string") {

				// Replace all non-printable, non-ASCII, ", and \ characters with their unicode encoding
					this._data.push(o[i].replace(/[^ -~]|[\"\\]/g, this._unicodeEscape));

				} else if (t == "undefined" || t == "null") {

					this._data.push(this._strictJson ? "null" : t);

				} else {

					this._data.push(o[i]);

				}
			}

			this._data.push(d2 + ",");

		}

	}
}

Serializer.prototype.deserialize = function (o) {

	try {

		if (this.hasEncodingLeader(o)) {

			o = this.base64decode(o);

		}

		// eval("var x = " + o);
		if (this._safeDeserialize) {
			return this.safeDeserialize(o);
		} else {
			return this.unsafeDeserialize(o);
		}

	} catch(e) {

		if (typeof(dbg) == "function") {

			dbg("Serializer.deserialize() error", "", "red");
			dbgObject(e);
			dbg("Serializer Source", o);

		}

		var x = "";

	}

	return x;

}
Serializer.prototype.safeDeserialize = function (o) {
	try {
		var p = new jsonParser();
		p.parse(o);
		eval("var x = " + o);
	} catch(e) {
		var x = null;
	}
	return x;
}
Serializer.prototype.unsafeDeserialize = function (o) {
	try {
		eval("var x = " + o);
	} catch(e) {
		var x = null;
	}
	return x;
}

Serializer.prototype.hasEncodingLeader = function (s) {

	return s.indexOf("B64ENC") == 0 ? true : false;

}

Serializer.prototype.stripLeader = function (s) {

	return s.substr(6, s.length);

}

Serializer.prototype.prependLeader = function (s) {

	return "B64ENC" + s;

}

// ripped from /includes/asplib/Base64
Serializer.prototype.base64decode = function (sIn) {

	var i;
	var iBits;
	var sOut = [];

	if (this.hasEncodingLeader(sIn)) {

		sIn = this.stripLeader(sIn);

	} else {

		return sIn;

	}

	sIn = sIn.replace(/=/g, "");

	for(i = 0; i < sIn.length; i += 4) {

		iBits = (this._sBase64.indexOf(sIn.charAt(i)) << 18) |
			(this._sBase64.indexOf(sIn.charAt(i + 1)) << 12) |
			((this._sBase64.indexOf(sIn.charAt(i + 2)) & 0xff) << 6) |
			(this._sBase64.indexOf(sIn.charAt(i + 3)) & 0xff);

		/* Removing the below += results in a 90% speed improvement on large objects/long strings */
		/*sOut += String.fromCharCode(iBits >> 16 & 0xff);
		sOut += (i > sIn.length - 3) ? "" : String.fromCharCode(iBits >> 8 & 0xff);
		sOut += (i > sIn.length - 4) ? "" : String.fromCharCode(iBits & 0xff);*/

		sOut.push(String.fromCharCode(iBits >> 16 & 0xff));
		sOut.push((i > sIn.length - 3) ? "" : String.fromCharCode(iBits >> 8 & 0xff));
		sOut.push((i > sIn.length - 4) ? "" : String.fromCharCode(iBits & 0xff));

	}

	return sOut.join("");

}

// ripped from /includes/asplib/Base64
Serializer.prototype.base64encode = function (sIn) {

	var i;
	var iBits;
	var sOut = [];

	for(i = 0; i < sIn.length; i += 3) {

		iBits = (sIn.charCodeAt(i) << 16) +
			((sIn.charCodeAt(i + 1) & 0xff) << 8) +
			(sIn.charCodeAt(i + 2) & 0xff);

		/* Removing the below += results in a 90% speed improvement on large objects/long strings */
		/*sOut += this._sBase64.charAt(iBits >> 18 & 0x3f);
		sOut += this._sBase64.charAt(iBits >> 12 & 0x3f);
		sOut += (i > sIn.length - 2) ? "=" : this._sBase64.charAt(iBits >> 6 & 0x3f);
		sOut += (i > sIn.length - 3) ? "=" : this._sBase64.charAt(iBits & 0x3f);*/

		sOut.push(this._sBase64.charAt(iBits >> 18 & 0x3f));
		sOut.push(this._sBase64.charAt(iBits >> 12 & 0x3f));
		sOut.push((i > sIn.length - 2) ? "=" : this._sBase64.charAt(iBits >> 6 & 0x3f));
		sOut.push((i > sIn.length - 3) ? "=" : this._sBase64.charAt(iBits & 0x3f));

	}

	sOut = this.prependLeader(sOut.join(""));

	return sOut;

}


// This is a validating JSON recursive descent parser.  It does not actually
// build a data structure; it merely tests the input string for validity
// according to the JSON grammar.  This greatly simplifies the parser, and also
// allows a few otherwise impossible performance tweaks.  For a description of
// the JSON grammer, see http:// json.org.  For a description of Recursive
// Descent parsers, how they work, and how to write one, see
// http://www.antlr.org/book/byhand.pdf

// The purpose of this parser is to ensure that calling eval() on a serialized
// string will not have any potentially nasty side effects.  This is an
// important safety measure when you don't know who has been serializing the
// strings you are about to deserialize...


function jsonParser () {
	this.lexer = null;
	this.tokens = [ ];
}

jsonParser.prototype.parse = function (str) {
	this.lexer = new jsonLexer(str);

	return this._json();
}

// not really necessary, since JSON seems to be parsable with an LL(1) grammar,
// but defining this now makes it far easier to extend in the future.
jsonParser.prototype.lookAhead = function (k) {
	while (this.tokens.length <= k) {
		this.tokens.push(this.lexer.nextToken());
	}
	return this.tokens[k].type;
}

// Remove a token from the token stream.  Since we are only parsing and not
// actually doing anything with the parsed string, we can merely remove the
// token from the stream here, and not worry about building a syntax tree.
jsonParser.prototype.consume = function (type) {
	if (this.tokens.length == 0) {
		this.tokens.push(this.lexer.nextToken());
	}

	if (this.tokens[0].type == type) {
		this.tokens.shift();
	} else {
		throw { message: 'JSON: invalid token encountered validating string; Expected '+type+', got '+this.tokens[0].type };
	}
}

// A JSON serialized string consists of exactly one value.
jsonParser.prototype._json = function () {
	this._value();
	this.consume('_EOF');
}

// A value can be one of
//   an object
//   an array
//   a string
//   a number
//   true, false, or null
jsonParser.prototype._value = function () {
	switch(this.lookAhead(0)) {
		case '_OBJ_OPEN':
			this._object();
			break;
		case '_ARR_OPEN':
			this._array();
			break;
		case '_DIGITS':
		case '_NEG':
			this._number();
			break;
		case '_STRING':
			this.consume('_STRING');
			break;
		case '_TRUE':
			this.consume('_TRUE');
			break;
		case '_FALSE':
			this.consume('_FALSE');
			break;
		case '_NULL':
			this.consume('_NULL');
			break;
	}
}

// An object consists of an open brace, zero or more comma separated
// string/value pairs, and a close brace
jsonParser.prototype._object = function () {
	this.consume('_OBJ_OPEN');
	if (this.lookAhead(0) != '_OBJ_CLOSE') {
		this._member();
	}
	while (this.lookAhead(0) != '_OBJ_CLOSE') {
		this.consume('_SEP');
		this._member();
	}
	this.consume('_OBJ_CLOSE');
}

jsonParser.prototype._member = function () {
	this.consume('_STRING');
	this.consume('_ASSIGN');
	this._value();
}

// An array consists of an open bracket, zero or more comma separated values,
// and a close bracket
jsonParser.prototype._array = function () {
	this.consume('_ARR_OPEN');
	if (this.lookAhead(0) != '_ARR_CLOSE') {
		this._value();
	}
	while (this.lookAhead(0) != '_ARR_CLOSE') {
		this.consume('_SEP');
		this._value();
	}
	this.consume('_ARR_CLOSE');
}

// A number consists of an optional leading '-', any number of digits, followed
// by an optional fractional component and an optional exponential component.
jsonParser.prototype._number = function () {
	if (this.lookAhead(0) == '_NEG') {
		this.consume('_NEG');
	}

	this.consume('_DIGITS');

	if (this.lookAhead(0) == '_DOT') {
		this.consume('_DOT');
		this.consume('_DIGITS');
	}

	if (this.lookAhead(0) == '_EXP') {
		this.consume('_EXP');
		if (this.lookAhead(0) == '_POS') {
			this.consume('_POS');
		} else if (this.lookAhead(0) == '_NEG') {
			this.consume('_NEG');
		}
		this.consume('_DIGITS');
	}
}

function jsonLexer (input) {
	// since we only care about validity and not the actual value, we can
	// easily reduce these multi-character tokens down to one character now
	// resulting in a significant gain in overall efficiency.
	input = input.replace(/"([^"\\]|\\"|\\)*"/g, 'S');
	input = input.replace(/[0-9]+/g, '0');

	this.input = input;
}

// Tokens represented by a single character
jsonLexer.prototype.charTokens = {
								'{': '_OBJ_OPEN',
								'}': '_OBJ_CLOSE',
								'[': '_ARR_OPEN',
								']': '_ARR_CLOSE',
								':': '_ASSIGN',
								',': '_SEP',
								'.': '_DOT',
								'-': '_NEG',
								'+': '_POS',
								'e': '_EXP',
								'E': '_EXP',
								'S': '_STRING',
								'0': '_DIGITS'
							};
// Other Tokens that are scanned for:
// 									 '_TRUE',
// 									 '_FALSE',
// 									 '_NULL',

jsonLexer.prototype.nextToken = function () {
	if (this.input.length == 0) {
		return new jsonToken("_EOF", null);
	}

	var first = this.input.substr(0,1);
	if (this.charTokens[first]) {
		this.input = this.input.substr(1);
		return new jsonToken(this.charTokens[first], first);
	}

	switch (first) {
		case 't':
		case 'T':
			if (this.input.substr(0,4).toLowerCase() == 'true') {
				this.input = this.input.substr(4);
				return new jsonToken('_TRUE', true);
			}
			break;

		case 'f':
		case 'F':
			if (this.input.substr(0,5).toLowerCase() == 'false') {
				this.input = this.input.substr(5);
				return new jsonToken('_FALSE', true);
			}
			break;

		case 'n':
			if (this.input.substr(0,4) == 'null') {
				this.input = this.input.substr(4);
				return new jsonToken('_NULL', true);
			}
			break;
	}

	throw { message: 'JSON: Unexpected character ('+first+') encountered validating string' };
}

// Simple representation of a lexer token
function jsonToken (type, value) {
	this.type = type;
	this.value = value;
}


/* -- Loaded:/includes/jslib/serializer/serializer.3.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


/*
Please note:
This is an exact duplicate of asplib/standardlib/recurseObject.asp
with the opening/closing tags stripped out.  Please remember to keep
the ASP and JS versions in sync.

*/

/*
recurseObject(myObject)
Displays formatted properties of an object either server side or client side

Optional properties when passing argument with Object notation
o - object to debug
n - name of object for reference
i - ignore ..showdebuginfo.. - true will still run even if show debug info is not on (Server Side Only).
l - levels to recurse down - int|true - default 15 - true sets no limit
f - show functions - true|false|text - text will show actual function text
t - true/false - to output raw text with no HTML - useful when using Firebug or other HTTP Response tools that don't render HTML
c - color for referencing multiple objects - examples: "red" or "#f00" or "random".
inline - client side only.  Will document.write rather than write to the popup
w/h - client side only. Width and height of popup window
dbg - client side only - true will use JS Debugger (debug.js) window for output rather than the recurseObject popup
firebug/console - output to firebug's consolue (requires Firebug 0.4 or later)
buffer - server side only - surrounds output in JavaScript block comments as to not interfere with Content Buffer ouput
textarea - server side only - surrounds output in <textarea> tags and forces raw text output. This combination is useful for reading output in both a buffered window, and in Firebug's "Response" tab. 
r|nowrite - return results only, don't write anything to the screen (useful for displaying at a later time)
autohide - shows only name of object.  Mouseover to expand.  Click to lock open
clear - clear popup or debug window first
autohide/collapse - wraps output in a click to expand/collapse container.

Example usage (server side or client side):

recurseObject(myObject); // no optional properties, use defaults
recurseObject({o:myObject,n:"My Object",l:5}); // 5 levels down
recurseObject({o:myObject,n:"My Object",c:"green"}); // highlight in green
recurseObject({o:myObject,f:true,t:1}); // show functions and display raw text output
recurseObject({o:myObject,i:1,buffer:1}); // ignore showdebuginfo and output buffer safe content

Use client side by first including this somewhere in your document (note: replace ! with % below)

<script type="text/javascript">
<! recurseObjectClientSide(); !>
</script>

*/

function recurseObject(props) {

	if (typeof props != "object") {
		return;
	}
	if (!props.o) {
		var obj = props;
		props = {o:obj};
	}

	var serverSide = (typeof document == "undefined");

	var showDebugInfoOn = !serverSide ? true : (User.Session("Secure.Flags.ShowDebugInfo") == "on");
	var ignoreShowDebugInfo = props.i || false;
	var objName = props.n || props.name || "Object";
	var bColor = props.c || props.color || "black";
	if (bColor == "random") {
		var colors = ["red","blue","black","green","orange"];
		bColor = colors[(Math.round(Math.random()*(colors.length-1)))];
	}
	var displayText = props.d || props.display || props.text || props.t || false;
	var obj = props.o || props.object || null;
	var showFunctions = props.f || props.functions || false;
	var recurseLevel = props.l || props.level || 15;
	var width = props.w || 500;
	var height = props.h || 500;
	var element = props.element || null;
	var inline = props.inline || false;
	var useDbg = props.debug || props.dbg || false;
	var useFireBug = props.firebug || props.console || false;
		if (useFireBug) { displayText = true; }
	var clearWindow = props.clear || false;

	var returnOnly = props.r || props.nowrite || false;
	var autoHide = (props.autohide && !displayText) || false;

	var contentBuffer = props.buffer || false;
	var textarea = props.textarea || false;
		if (textarea) {
			displayText = true;
			if (textarea === true || (isNaN(textarea) && !/%/.test(textarea))) { textarea = "400px"; }
			if (!isNaN(textarea)) { textarea += "px"; }
		}


	var rand = "Random"+Math.round(Math.random()*100000);


	var outputVals = [];

	function show(obj) {
 		outputVals = [];
		if (typeof obj == "undefined") { outputVals = "recurseObject: Object not defined"; }
		else { recurse(obj); }
		return output();

	}

	function recurse(obj,level) {
		var l = level || 0;
	
		if (l == 0 && typeof obj == "string") {
			displayText = true;
			outputVals.push(obj)
		}
		for (var i in obj) {

			if (typeof obj[i] == "function" && !showFunctions) {
				continue;
			}
			outputVals.push((displayText ?  (indention(l)+i) : ("<blockquote "+((l == 0) ? "style='margin-left:0px;' " : "")  + ">" + "<b>" + i + "</b>")) + " (" + (typeof obj[i]).charAt(0) + (obj[i] && (typeof obj[i] == "object" && obj[i] instanceof Array) ? (":Array("+obj[i].length+")"):"") + "): " + ((typeof obj[i] == "function" && showFunctions != "text") ? "Function" : (!typeof obj[i] == "function" && obj[i] instanceof Object || obj[i] instanceof Array)?"":obj[i])+"\n");
			if (obj[i] && typeof obj[i] != "string" && (recurseLevel === true || l < recurseLevel)) {
				recurse(obj[i],(l+1));
			}
			outputVals.push(displayText ? "" : "</blockquote>");
		}
	}

	function output() {

		var outputTitle = objName + ((!serverSide) ? " (Client Side) " : " (Server Side)");
		var outputS = (displayText) ? ((outputTitle+"\n"+outputVals.join(""))) : ("<hr /><style>div.recurseObject { background:#fefefe; font-size:11px; text-align:left;} pre.recurseObject { white-space:normal; } div.recurseObject blockquote {margin:0px;margin-left:35px;border-bottom:1px solid #EEE;padding-left:5px;} div#recurseObject"+rand+" blockquote {border-left:1px solid "+bColor+";} </style><div id='recurseObject"+rand+"' class='recurseObject'>\n<div style='background:#fcfcfc; padding:2px; border:2px solid "+bColor+"'>"+objName+((!serverSide) ? " (Client Side) " : " (Server Side)")+"</div>\n<pre class='recurseObject'>"+outputVals.join("")+"</pre></div>");

		if (textarea) {
			outputS = "<br /><textarea class='recurseObject' style='width:99%;height:"+textarea+"'>\n" + outputS + "</textarea><br />\n";
		}

		if (autoHide) {
			outputS = "<div style=\"padding:4px; border:1px dashed "+bColor+";\"><div style=\"overflow:hidden; height:1.2em;\">\
			 <div style='cursor:pointer;margin-right:5px;' title='Click to Expand/Collapse' onclick=\"var ROOpen = this.getAttribute('open'); this.parentNode.style.height = ROOpen?'1.2em':'auto'; this.parentNode.style.overflow=ROOpen?'hidden':'auto'; this.parentNode.parentNode.style.borderStyle = ROOpen?'dashed':'solid'; this.setAttribute('open',ROOpen?'':'yes'); \" />\
				"+outputTitle+"</div>\
				"+outputS+"\
			</div></div>";
		}

		if (contentBuffer) {
			outputS = "/*\n"+outputS+"\n*/";
		}

		if (!returnOnly) {
			if (serverSide) { // Server side JScript
				Response.write(outputS);
			}
			else { // Client side JavaScript
				if (inline) {
					document.write("<hr />"+outputS);
				}
				else if (element) {
					try {
						
						if (typeof element == "string") element = document.getElementById(element);
						element.innerHTML += "<hr />"+outputS;
					}
					catch(e) {}
				}
				else if (useDbg) {
					try {
						if (clearWindow) {
							Debug.debugWindow._sdb.clear(null,null,{ pane: "console" })
						}
						dbg(outputS);
					}
					catch(e) {}
				}
				else if (useFireBug) {
					try {
						console.log(outputS);
					}
					catch(e) {}
				}
				else {

					if (!window.dWindow || window.dWindow.closed) { // +Math.round(Math.random()*1000)
						dWindow = window.open('','recurseObject','width='+width+',height='+height+',top=0,left=0,scrollbars=1,resizable=1');
					}
					if (clearWindow) {
						dWindow.document.close();
						dWindow.document.open()
					}
					dWindow.rand = rand;

					//	dWindow.document.write("<a style='position:absolute;top:0px;right:0px;background:#fff;border:1px solid black;font-size:12px;padding:3px;' href='javascript:void(0);' onclick='document.body.innerHTML = \"\";'>Clear Window</a>");
					dWindow.document.write("<hr />"+(new Date)+outputS);
					
					try {
						// scroll to object div
						var dTop = dWindow.document.getElementById("recurseObject"+rand).offsetTop;dWindow.window.scrollTo(0,1000000);
						dWindow.window.scrollTo(0,dTop-40);
					}
					catch(e) {
						dWindow.window.scrollTo(0,1000000)
					}
				}
			}
		}
		return outputS;
		outputVals = [];
		
	}

	function indention(level) {
		var indents = [];
		for (var i=0;i<level;i++) { indents.push("\t") }
		//for (var i=0;i<level;i++) { indents.push("    ") }
		return indents.join("");
	}


	if (serverSide && (ignoreShowDebugInfo || showDebugInfoOn)) { // Server side JScript
		return show(obj)
	}	
	else if (!serverSide && (ignoreShowDebugInfo || showDebugInfoOn)) { // Client side JavaScript
		return show(obj);
	}

	return "";

}

function recurseObjectClientSide() {

	var recurseObjectFunction = recurseObject.toString();

	if (User.Session("Secure.Flags.ShowDebugInfo") == "on") {
		recurseObjectFunction = recurseObjectFunction.replace("var showDebugInfoOn = false;","var showDebugInfoOn = true;");
		Response.write("\n"+recurseObjectFunction+"\n\n");
	}
	else {
		Response.write("\nfunction recurseObject() { \n\/\/please turn on debug or include client side version\n }\n\n");
	}

}

/* -- Loaded:/includes/jslib/recurseObject.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


function msToJsDate(msDate){var jO=new Date(((msDate-25569)*86400000));var tz=jO.getTimezoneOffset();var jO=new Date(((msDate-25569+(tz/(60*24)))*86400000));return jO;}
function jsToMsDate(jsdate) {
	var timezoneOffset=jsdate.getTimezoneOffset()/(60*24);
	var msDateObj=(jsdate.getTime()/86400000)+(25569 - timezoneOffset);
	return msDateObj;
}

/* -- Loaded:/includes/jslib/date.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	WCH.js - Windowed Controls Hider v3.10
	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	(c) Copyright 2003, Aleksandar Vacic, aleck@sezampro.yu, www.aplus.co.yu
	## This work is licensed under the Creative Commons Attribution-ShareAlike License.
	## To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/1.0/ or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA
	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	Credits: Mike Foster for x functions (cross-browser.com)
	Credits: Tim Connor for short and sweet way of dealing with IE5.0 - dynamic creation of style rule (www.infosauce.com)
	- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	Based on idea presented by Joe King. Works with IE5.0+/Win
	IE 5.5+: place iFrame below the layer to hide windowed controls
	IE 5.0 : hide/show all elements that have "WCHhider" class
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
var WCH_Constructor = function() {
	//	exit point for anything but IE5.0+/Win
	if ( !(document.all && document.getElementById && !window.opera && navigator.userAgent.toLowerCase().indexOf("mac") == -1) ) {
		this.Apply = function() {};
		this.Discard = function() {};
		return;
	}

	//	private properties
	var _bIE55 = false;
	var _bIE6 = false;
	var _oRule = null;
	var _bSetup = true;
	var _oSelf = this;

	//	public: hides windowed controls
	this.Apply = function(vLayer, vContainer, bResize) {

		if (_bSetup) _Setup();

		if ( _bIE55 && (oIframe = _Hider(vLayer, vContainer, bResize)) ) {
			oIframe.style.visibility = "visible";
		} else if(_oRule != null) {
			_oRule.style.visibility = "hidden";
		}

	};

	//	public: shows windowed controls
	this.Discard = function(vLayer, vContainer) {
		if ( _bIE55 && (oIframe = _Hider(vLayer, vContainer, false)) ) {
			oIframe.style.visibility = "hidden";
		} else if(_oRule != null) {
			_oRule.style.visibility = "visible";
		}
	};

	//	private: returns iFrame reference for IE5.5+
	function _Hider(vLayer, vContainer, bResize) {
		var oLayer = _GetObj(vLayer);
		var oContainer = ( (oTmp = _GetObj(vContainer)) ? oTmp : document.getElementsByTagName("body")[0] );
		if (!oLayer || !oContainer) return;
		//	is it there already?
		var oIframe = document.getElementById("WCHhider" + oLayer.id);

		//	if not, create it
		if ( !oIframe ) {
			//	IE 6 has this property, IE 5 not. IE 5.5(even SP2) crashes when filter is applied, hence the check
			var sFilter = (_bIE6) ? "filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0);" : "";
			//	get z-index of the object
			var zIndex = oLayer.style.zIndex;
			if ( zIndex == "" ) zIndex = oLayer.currentStyle.zIndex;
			zIndex = parseInt(zIndex);
			//	if no z-index, do nothing
			if ( isNaN(zIndex) ) return null;
			//	if z-index is below 2, do nothing (no room for Hider)
			if (zIndex < 2) return null;
			//	go one step below for Hider
			zIndex--;
			var sHiderID = "WCHhider" + oLayer.id;
			oContainer.insertAdjacentHTML("afterBegin", '<iframe class="WCHiframe" src="javascript:false;" id="' + sHiderID + '" scroll="no" frameborder="0" style="position:absolute;visibility:hidden;' + sFilter + 'border:0;top:0;left;0;width:0;height:0;background-color:#ccc;z-index:' + zIndex + ';"></iframe>');
			oIframe = document.getElementById(sHiderID);
			//	then do calculation
			_SetPos(oIframe, oLayer);
		} else if (bResize) {
			//	resize the iFrame if asked
			_SetPos(oIframe, oLayer);
		}

		return oIframe;
	};

	//	private: set size and position of the Hider
	function _SetPos(oIframe, oLayer) {
		//	fetch and set size
		oIframe.style.width = oLayer.offsetWidth + "px";
		oIframe.style.height = oLayer.offsetHeight + "px";
		//	move to specified position
		oIframe.style.left = oLayer.offsetLeft + "px";
		oIframe.style.top = oLayer.offsetTop + "px";
	};

	//	private: returns object reference
	function _GetObj(vObj) {
		var oObj = null;
		switch( typeof(vObj) ) {
			case "object":
				oObj = vObj;
				break;
			case "string":
				oObj = document.getElementById(vObj);
				break;
		}
		return oObj;
	};

	//	private: setup properties on first call to Apply
	function _Setup() {
		_bIE55 = (typeof(document.body.contentEditable) != "undefined");
		_bIE6 = (typeof(document.compatMode) != "undefined");

		if (!_bIE55) {
			if (document.styleSheets.length == 0)
				document.createStyleSheet();
			var oSheet = document.styleSheets[0];
			oSheet.addRule(".WCHhider", "visibility:visible");
			_oRule = oSheet.rules(oSheet.rules.length-1);
		}

		_bSetup = false;
	};
};
var WCH = new WCH_Constructor();



/* -- Loaded:/includes/jslib/wch.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


var agt=navigator.userAgent.toLowerCase();
var is_ie=(agt.indexOf("msie")!=-1);
/**********
 * Changes the css style and events for buttons
 **************************/
//button class name constants
var OUTER = "Outer";
var MIDDLE = "Middle";
var INNER = "Inner";
var PRIORITY = "Priority";
function btnOn(id){
	var linkRef = document.getElementById(id);
	if (linkRef){
		var pClass = (linkRef.getAttribute("priority")=="true") ? PRIORITY : ""; //if priority, change class
		changeBtnClass(id,pClass+"On");
		linkRef.onfocus = function(){ changeBtnClass(id,pClass+"Over");} ;
		linkRef.onblur = function(){ changeBtnClass(id,pClass+"On");} ;
		linkRef.onmouseover = function(){ changeBtnClass(id,pClass+"Over");};
		linkRef.onmousedown = function(){//need to also clear onfocus and blur on mousedown for mozilla/firefox conflicts
			if (!is_ie){
				document.getElementById(id).onfocus=null;
				document.getElementById(id).onblur=null;
			}
			changeBtnClass(id,pClass+"Down");
		};
		linkRef.onmouseup = function(){ 
			changeBtnClass(id,pClass+"On") 
		};
		linkRef.onmouseout = function(){ //need to also reset onfocus and blur on mousedown for mozilla/firefox conflicts
			changeBtnClass(id,pClass+"On");
			if (!is_ie){
				document.getElementById(id).onfocus = function(){changeBtnClass(id,pClass+"Over");};
				document.getElementById(id).onblur= function(){changeBtnClass(id,pClass+"On");};	
			}
		};
		linkRef.onclick = linkRef.inlineonclick; 
	}
 };
 
 function btnOff(id) {
	var linkRef = document.getElementById(id);
	if (linkRef){
		var pClass = (linkRef.getAttribute("priority")=="true") ? PRIORITY : ""; //if priority, change class
		changeBtnClass(id,pClass+"Off");
		linkRef.onfocus = null;
		linkRef.onblur = null;
		linkRef.onclick = function(){return false;};
		linkRef.onmouseover = null;
		linkRef.onmousedown = null ;
		linkRef.onmouseup = null;
		linkRef.onmouseout = null;	
	}
 };
 
function changeBtnClass(id,state){
	var btn = document.getElementById(id + OUTER);
	if (btn){
		 btn.className = "btn" + state + OUTER;
		 var middleBtn = document.getElementById(id+MIDDLE);
		 if (middleBtn) middleBtn.className = "btn" + state + MIDDLE;
		 var innerBtn = document.getElementById(id+INNER);
		 if (innerBtn) innerBtn.className = "btn" + state + INNER;
		 innerBtn.style.padding="0";
	}
};

function btnInit(id,priority,on,setwidth,setheight,iconPre,iconPost,smallsize,mini){
	var linkRef = document.getElementById(id); //get a tag link
	var iconImg = "";//for icons
	if (iconPre || iconPost) {
		iconImg = document.createElement("img");
		iconImg.src = (iconPre) ? iconPre: iconPost;
		iconImg.border = "0";
		iconImg.hspace = "4";
		iconImg.style.paddingTop = "2px"
		//iconImg.width = 10;
		//iconImg.height = 10;
	}
	
	if (linkRef){
		var txt = linkRef.firstChild.nodeValue; //get text in link
		var oswidth = linkRef.offsetWidth; //buttons may need to be same width for design, if so, pass width size
		var padding = (smallsize) ?  16 : 21; //add extra width padding
		padding = (mini) ? 0 : padding;
		var width = (setwidth) ? setwidth : oswidth + padding; //get width of link, and add padding
		var height = (setheight) ? setheight : false; //get width of link, and add padding
		linkRef.firstChild.nodeValue = " "; //erase text link
		linkRef.className = "btnLink"; 
		linkRef.style.width = width; //reset link width
		if(height) linkRef.style.height = height;

		if (iconPre || iconPost) {
			width += 11; //size of icon image + buffer
		}
		
		//writing out this structure <a href="#"><div><div></div><div></div></div></a>
		//triple divs for additional borders
		var outerDiv = document.createElement("div"); 
		outerDiv.id = id + OUTER;
		outerDiv.style.width = width + "px";
		if(height) outerDiv.style.height = height + "px";
		
		var middleDiv = document.createElement("div"); 
		middleDiv.id = id + MIDDLE;
		middleDiv.style.width = (width - 2) + "px";
		if(height) middleDiv.style.height = (width - 2) + "px";
		
		var innerDiv = document.createElement("div");
		innerDiv.id = id + INNER;
		innerDiv.style.width = (width - 4) + "px";
		if(height) innerDiv.style.height = (width - 4) + "px";
		if (smallsize) {innerDiv.style.fontSize = "11px";innerDiv.style.lineHeight = "13px";}
		if(mini){innerDiv.style.fontSize = "9px"; innerDiv.style.lineHeight = "9px";}
		
		outerDiv.appendChild(middleDiv);
		middleDiv.appendChild(innerDiv);
		if (iconPre) {
			innerDiv.appendChild(iconImg);
		}
		innerDiv.appendChild(document.createTextNode(txt));
		if (iconPost) {
			innerDiv.appendChild(iconImg);
		}		
		linkRef.appendChild(outerDiv);
						
		if (priority) { //priority setting
			/* IE 5.5 was choking on document.createAttribute
			var newAttr = document.createAttribute("priority");
			newAttr.nodeValue="true";
			linkRef.setAttributeNode(newAttr);
			*/
			linkRef.setAttribute("priority","true");

		}
		
		//hold on to inline onclick on the original link
		if (linkRef.inlineset!=true) {
			linkRef.inlineonclick = linkRef.onclick; 
			linkRef.inlineset = true;
		}
		on ? btnOn(id) : btnOff(id); //set button states
	}
	return linkRef;
};



/* -- Loaded:/tdameritrade/common/scripts/buttons.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */



Common_class = function() {

}

Common_class.prototype.setEnviron = function(env) {
	this.env = env;
}

Common_class.prototype.getEnviron = function() {
	
	return this.env || null;	
}

Common_class.prototype.getEnvironment = function() {
	return gEnvironment;
}

Common_class.prototype.scrollToTop = function() {
	window.scrollTo(0,0);
}

Common_class.prototype.fixXSS = function(s) {
	s = unescape(s);
	return s.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"');
}

Common_class.prototype.getContentBuffer  = function() {
	if (!this.gContentBuffer) {
		this.gContentBuffer = new ContentBuffer();
	}
	return this.gContentBuffer;
}

Common_class.prototype.contentBufferAbortRequests  = function() {
	if (!this.gContentBuffer) {
		this.gContentBuffer = new ContentBuffer();
	}
	this.gContentBuffer.abortRequests();
}

Common_class.prototype.toggleDefinitionPopUp = function( who ) {
	
	who = Element.get( who );
	
	if( Element.hasClass( who, "none" ) ) {
		Element.removeClass( who, "none" );	
	} else {
		Element.addClass( who, "none" );
	};
	return;
}

Common_class.prototype.loadContentBuffer = function(argsObj) {
	var cb = this.getContentBuffer();

	//dbgObject(argsObj.data);
	//dbg(DataFunctions.serialize(argsObj.data));

	var conn = cb.load({
		debug: true,
		url: argsObj.page,
		method: "post",
		contentType: argsObj.contentType || "text/javascript",
		context:argsObj.context,
		evalInContext:(argsObj.context)?true:false,
		preventEval:(argsObj.preventEval)?true:false,
		data:{
			data:DataFunctions.serialize(argsObj.data)
		},
		onload: argsObj.onload,
		onerror: argsObj.onerror
	});
}


Common_class.prototype.loadTab = function(args) {

	Common.scrollToTop();

	if (!args.tab) { args.tab = defaultTab; }
	if (args.tabNumber === undefined) { args.tabNumber = ""; }
	if (args.section === undefined) { args.section = "NULL"; }

	if (args.selectTab) {
		selectTab(args.tab,'0');
	}
	
	if (args.clear) {
		for (var i = 0; i < args.clear.length; i++) {
			Element.setHTML(args.clear[i], "");
		}
	}
	
	var loadPage = args.tab + "Buffer.asp";
	
	Common.contentBufferAbortRequests();

	Element.setHTML(args.tab,"");
	Common.loadContentBuffer({
		page:loadPage,
		contentType:"text/html",
		data:{
			tabSection:args.section
			,tabNumber:args.tabNumber
		},		
		onload:function() {
			var resultHTML = arguments[0].getResult();
			Common.handleContentBufferHTML(args.tab,resultHTML);
		},			
		onerror: function() { }
	});
};

Common_class.prototype.assignTabEvents = function() {
	
	var tabs = Element.parseSelector( "div[id='TabNav'] li,div[id='subtabsContainer'] li" );

	Events.add( { element:tabs, type:"mouseover", handler:this.mouseOverTabs, context:this, data:true } )	
	Events.add( { element:tabs, type:"mouseout", handler:this.mouseOverTabs, context:this, data:false } )	
	
};

Common_class.prototype._pagingObj = {};

Common_class.prototype.createPaginationTooltip = function( el, text , isHidden ) {
	
	var displayString =  isHidden? "display:block;" : "display:none;";
	
	if( this._pagingObj[ text ] ) {

		Element.setStyle( this._pagingObj[ text ], displayString  );
		return;
	};
	
	if( !text ) return;
	
	var tooltip = Element.create( "div", { className:"tooltip" }, [
					Element.create( "div", { className:"tooltip-top" }, text )
					,Element.create( "div", {className:"tooltip-arrow"} )
	], document.body );
	
	
	this._pagingObj[ text ] = tooltip;
	
	
	var pos = Element.getXY( el );
	
	Element.setXY( tooltip, pos.x - 30,  ( pos.y - ( tooltip.offsetHeight/2 + 15 ) ) );
	
	Element.setStyle( tooltip, displayString );
	return;
};



Common_class.prototype.mouseOverTabs = function( e, el, over ) {

	if( Element.hasClass( el, "current" ) ) {
 		over = false;
	}

	Element.switchClass(el, "highlight", over );

};


loadBuffer.add( function( ){ 
			Common.assignTabEvents()
} );


Common_class.prototype.handleContentBufferHTML = function(targetObj,resultHTML) {
	Element.setHTML(targetObj,resultHTML);

	loadBuffer.buffer = []; 	// clear previous load functions and

	Common.contentBufferParseResult(resultHTML); // parse and evaluate JS
	sizeFullWidths.init(); // grab and full width images

	loadBuffer.load(); 
}


Common_class.prototype.createChartElement = function ( oArgs ) {
	
	var path  = oArgs.path;
	var id    = oArgs.id;
	var img;
	
	var ret =  {
		format:Element.create("div", {className:"sparkChart"}, [
			img = Element.create("img", {src:path, className:"c"+id})
		])
		,raw:""
	};
	
	Events.add({
		 element:img
		,type:'error'
		,handler:function(e, el){Element.addClass(el, 'none');}
	});
	
	return ret;
};

Common_class.prototype.fifty2Week = {
	
	 fifty2WeekData:{}
		
	,create52WeekGraphic:function( oArgs ){
	
		var val = Math.round((oArgs.last - oArgs.fifty2WeekLow)/(oArgs.fifty2WeekHigh - oArgs.fifty2WeekLow) * 100);
		var klass = "";
	
		if(val > 100 ){
			val = 100;
			klass = " hidden";
		} 
		else if(val < 0 || isNaN(val)) {
			val = 0;
			klass = " hidden";
		}
		
		var symbol = oArgs.symbol;
		var rt     = oArgs.rt;
		
		var el = Element.create("div", {rt:rt, symbol:symbol, className:"moduleHasIcon scaleGraphic" + klass}, [
					Element.create("div", {rt:rt, symbol:symbol, className:"equalizer"}, [
				  		Element.create("div", {rt:rt, symbol:symbol, className:"moduleHasIcon scalePoint", style:"left:"+val+"%"})
				  	])
		]);
		
		if(!this.fifty2weekHoverEvent) {
			
			Events.add({
				 element:document.body
				,type:'mouseover'
				,handler:this.show52WeekPopup
				,context:this
				,delay:400
			});
			
			this.fifty2weekHoverEvent = true;
		}
	
		return  {
			 format:el
			,raw:val
		};
	}
	
	
	,show52WeekPopup:function(e, el) {
	
		var elem = e.getTarget();
		
		if(elem.className && elem.className.match(/(equalizer|scalePoint)/)) {
			
			Events.add({
				 element:elem
				,type:'mouseout'
				,handler:this.hide52WeekPopup
				,context:this	
			});
		
			if(!this.graphic52week) {
		
				this.graphic52week = {
					 element:null
					,heading:''
					,low:''
					,high:''
					,title:''
					,isOpen:false	
				};
				
				var t;
				var low;
				var high;
				var lowDate;
				var highDate;
				var title;
				var frame;
				
				var element = Element.create('div', {className:'hidden fifty2WeekPopUp hasLayout'}, [
								 frame = Element.create("iframe", {src:"javascript:false;", frameborder:"0"})
								,Element.create('div', {className:'fullcontainer'}, [
									Element.create('div', {className:'fleft container'}, [
										Element.create('div', {className:'hasLayout'}, [
											 t = Element.create('strong', {className:'symbol'})
											,Element.create('br', {})
											,title = Element.create('div', {className:'smaller'})
										])
										,Element.create('div', {className:'hasLayout margTop10'}, [
											 Element.create('div', {className:'fleft'}, [
											 		 Element.create('div', {className:'delayedDisclaimer'}, 'Low')
											 		,low = Element.create('strong', {className:'smaller'})
											 		,Element.create('br')
											 		,lowDate = Element.create('div', {className:'delayedDisclaimer'})
											 ] )
											,Element.create('div', {className:'fright'}, [
												 Element.create('div', {className:'delayedDisclaimer'}, 'High')
												,high = Element.create('strong', {className:'smaller'})
												,Element.create('br')
											 	,highDate = Element.create('div', {className:'delayedDisclaimer'})
											])
										])
									])
									,Element.create('div', {className:'fleft shadowleft'})
									,Element.create('br', {className:'clear'})
									,Element.create('div', {className:'shadowbottom'})
								])
				]);
				
				element.style.position = 'absolute';
				
				Element.addChild(document.body, element);
	
				this.graphic52week.element = element;
				this.graphic52week.heading = t;
				this.graphic52week.low = low;
				this.graphic52week.high = high;
				this.graphic52week.lowDate = lowDate;
				this.graphic52week.highDate = highDate;
				this.graphic52week.title = title;
				this.graphic52week.frame = frame;
			}
			
			e = e.nativeEvent;
			
			this.clientX = e.clientX;
			this.clientY = e.clientY;
			this.target  = elem;
			
			if(this.graphic52week.isOpen) {
				this.hide52WeekPopup();	
			}
			
			var sy = elem.getAttribute('symbol');
			var rt = elem.getAttribute('rt');

			var data = this.fifty2WeekData[ sy ];
			
			if(!data) {
				
				this.get52WeekData( sy, rt );
				return;	
			}
			this.insert52WeekData( data );
			
		}
	}
	
	
	,hide52WeekPopup:function(e, el) {
	
		if(this.timer) {
			clearTimeout(this.timer);
			this.timer = null;	
		}
		
		this.buffer.abortRequests();
	
		var graphic = this.graphic52week;
		
		if(graphic && graphic.isOpen) {
			
			Element.addClass(graphic.element, "hidden");
			
			graphic.element.style.left = '-1000px';
			graphic.isOpen = false;
		}
		
		if(el) {
			Events.remove(el, this.hide52WeekPopup);
		}
	}
	
	,insert52WeekData:function( data, ev ) {
		
		var elem = this.target;
		
		this.timer = setTimeout(function(){
		
			this.fifty2WeekData[data.symbol] = data;
			
			this.graphic52week.frame.style.height = "0px";
		
			Element.setHTML(this.graphic52week.heading, data.symbol_format.replace(/^(.{25})(.*?)$/, '$1...'));
			Element.setHTML(this.graphic52week.low, data.low);
			Element.setHTML(this.graphic52week.high, data.high);
			Element.setHTML(this.graphic52week.lowDate, data.lowDate);
			Element.setHTML(this.graphic52week.highDate, data.highDate);
			Element.setHTML(this.graphic52week.title, data.title);
			
			this.graphic52week.frame.style.height = this.graphic52week.element.offsetHeight + "px";
			this.graphic52week.frame.style.width = this.graphic52week.element.offsetWidth + "px";
			
			
			var posx = this.clientX + 5;
			var posy = ((this.clientY - 8) + document.body.scrollTop) - this.graphic52week.element.offsetHeight;
	
			this.graphic52week.element.style.left = posx + 'px';
			this.graphic52week.element.style.top  = posy + 'px';
			
			Element.removeClass(this.graphic52week.element, "hidden");
			this.graphic52week.isOpen = true;
			
		}.Context( this ), 300);
	}
	
	,get52WeekData:function ( sy, rt ) {

		if(!this.buffer) {
			this.buffer = new ContentBuffer();	
		}

		this.buffer.abortRequests();
		
		this.buffer.load({
			 url:buildAbsolutePath('/common/widgets/fifty2week.data.asp')
			,context:this
			,data:{symbol:sy, rt:rt}
			,onload:this.setData
			,contentType:'text/javascript'
		});
	}
	
	,setData:function( buffer ) {
		
		var data = buffer.getResult();
			data = DataFunctions.serializer.deserialize( data );

		this.fifty2WeekData[data.symbol] = data;
		this.insert52WeekData( data );
	}
};

Common_class.prototype.create52WeekGraphic = function ( oArgs ) {
	
	return this.fifty2Week.create52WeekGraphic( oArgs );
};





Common_class.prototype.__issueMaps = function() {
	
	var ims = {
	 	 "CS":buildAbsolutePath("/stocks/overview/overview.asp?")
		,"ETF":buildAbsolutePath("/etfs/profile/profile.asp?")
		,"MF":buildAbsolutePath("/mutualfunds/profile/profile.asp?")
	};
	
	this.__issueMaps = function () {
		return ims;	
	}
	
	return ims;
};

Common_class.prototype.createSymbolLink = function ( oArgs ) {
	
	var ims  = this.__issueMaps();
	var path = ims[oArgs.issueType] || ims["CS"];
	
	var link = Element.create("div", {}, [
			Element.create("a", {href:path+"symbol="+oArgs.symbol, symbol:oArgs.symbol, issue:oArgs.WSODIssue}, oArgs.symbol)
	]);
	
	if(oArgs.extras == "checkbox") {

		Element.insertBefore(Element.create("input", {type:"checkbox", name:"watchlistItem_"+oArgs.symbol}), link.firstChild);
	}
	
	if(oArgs.portfolio) {
		Element.addChild(link, [Element.create("span", {},'&nbsp;&nbsp;'),Element.create("span", {className:'portfolioKey moduleHasIcon'}, '')]);
	}
	
	if(oArgs.watchlist) {
		Element.addChild(link, [Element.create("span", {},'&nbsp;&nbsp;'),Element.create("span", {className:'watchlistKey moduleHasIcon'}, '')]);
	}

	return {
		 format:link
		,raw:oArgs.symbol
	};
};
	

Common_class.prototype.contentBufferParseResult = function(content) {


	// ---------------------------------------------------------------
	// scripts
	// ---------------------------------------------------------------
	var scriptRegEx = /<script([^>]*)>([\s\S]*?)<\/script>/;
	var scripts = content.match(scriptRegEx);

	while (scripts) {
		var attribs = scripts[1];
		var code = scripts[2];

		var src = /src="([^"]*)"/.exec(attribs);

		if (src && src[1]) {

/*
			if (!this.desktop.manager.isFileLoaded(src[1])) {
				// external script
				dbg("script src", src[1]);
				this._activeRequests ++;

				this._bufferedRequests.push(
					this.buffer.load({
						url: src[1] + "?now=" + new Date().getTime(),
						contentType: "text/javascript",
						onload: this._setActiveRequestOnLoad(src[1]),
						context: this
					})
				);
			}

*/

		} else if (code) {

			eval(scripts[2]);

		}

		content = content.replace(scriptRegEx, "");
		scripts = scriptRegEx.exec(content);

	}

	return content;
};


// short cut for remembering that encodeURIComponent() escapes additional characters such as + and ,
// please remember to update the client side version if you make updates
Common_class.prototype.encode = function(s, encodeHTML) {
	var returnString = s;
	if (encodeHTML) { returnString = this.encodeHTML(returnString); }
	returnString = encodeURIComponent(returnString)

	return returnString;
}

Common_class.prototype.encodeHTML = function(s) {
	var returnString = s;
	returnString = returnString.replace(/\</g, "&lt;")
	returnString = returnString.replace(/\>/g, "&gt;")
	returnString = returnString.replace(/\"/g, "&quot;")
	
	return returnString;
}

Common_class.prototype.decode = function(s, decodeHTML) {
	var returnString = s;
	returnString = decodeURIComponent(returnString)
	if (decodeHTML) { returnString = this.decodeHTML(returnString); }
	
	return returnString;
}

Common_class.prototype.decodeHTML = function(s) {
	var returnString = s;
	returnString = returnString.replace(/\&lt;/g, "<")
	returnString = returnString.replace(/\&gt;/g, ">")
	returnString = returnString.replace(/\&quot;/g, "\"")
	
	return returnString;
}

Common_class.prototype.openParentURL = function(url) {
	try {
		window.opener.location.href = buildAbsolutePath(url);
	} catch(e) {
		window.location.href = gSessionSeedDomain + "/amer/html/fatal.html";
	}
}

Common_class.prototype.openLinkInParent = function( el ) {
	
	window.opener.location = el.href;
};

Common_class.prototype.openExternal = function(url) {
	if (window.opener) {
		window.opener.location.href = url;
	} else {
		window.location.href = url;
	}
}

/*
Popup page to hold common messages/disclaimers
Pass page name and modify infopopup.asp
OR
Pass URL to use with buildAbsolutePath
*/

Common_class.prototype.popups = {};

Common_class.prototype.openInfoPopup = function(page) {
	var URL = /\./.test(page) ? buildAbsolutePath(page) : buildAbsolutePath('/common/infopopup.asp?page='+page);
	window.open(URL,'','width=705,height=500,scrollbars=yes')
}


//Centered popup, there can be only one!
Common_class.prototype.openCenteredPopup = function(type, noButtons, tabnum, fromPage) {
	
	var popup = this.getPopup(type, noButtons, tabnum, fromPage);
	
	if(popup) {
		popup.show(type, noButtons, tabnum, fromPage);
	}
}

Common_class.prototype.getPopup = function(type, noButtons, tabnum, fromPage){
	
	if(this.popups[type]) {
		return null;	
	}
	return new WSODPopup(type, noButtons, tabnum, fromPage);
}

Common_class.prototype.popReport = function(e, el, data) {
	
	Events.cancel(e);
	
	this.popCustomWindow({
		path: el.getAttribute("href")
		,name: "pdf_window"
		,width: 700
		,height: 450
		,scrollbars: "yes"
		,menubar: "no"
		,toolbar: "no"
		,status: "yes"
		,resizable: "yes"
	});
}

Common_class.prototype.focusField = function(e,el,data) {
	try {
		if (e) {
			Element.removeClass(el, "lighter");
			if (el.value == el.getAttribute("defaultText")) {
				el.value = "";
			}	else {
				setTimeout(function() { el.select(); },1);
			}
		} else if (data && data.selectText) {
			el.focus();
			setTimeout(function() { el.select(); },1);
			Element.removeClass(el, "lighter");
		} else if (el && el.value != el.getAttribute("defaultText")) {
			Element.removeClass(el, "lighter");
		}
	} catch(e) {}
}

Common_class.prototype.blurField = function(e,el,data) {
	try {
		if (el.value == "" || el.value == el.getAttribute("defaultText")) {
			Element.addClass(el, "lighter");
			el.value = el.getAttribute("defaultText")
		}
	} catch(e) {}
}

// args is an array of objects in the form:
// {path: "/path/", fileName: "fileName.gif"}
Common_class.prototype.preLoadImages = function(args) {
	for (var i = 0, img = []; i < args.length; i++) {
		img[i] = new Image();
		img[i].src = args[i].path + args[i].fileName;
	}	
}

Common_class.prototype.arrayIndexOf = function(arr, val) {
	for (var i = 0; i < arr.length; i++) {
		if (arr[i] == val) {
			return true;
		}
	}
	return false;
}

Common_class.prototype.stringToArray = function(str, allowSpaces) {
	str = str.replace(/^\s+/g, '').replace(/\s+$/g, ''); // remove leading and trailing spaces
	if (str == "") {
		return [];
	}

	if (allowSpaces) str = str.replace(/\s+/g, ",");

	str = str.split(",");
	var str2 = [];
	for (var i = 0; i < str.length; i++) { 	// add to output array if not empty
		str[i] = str[i].replace(/^\s+/g, '').replace(/\s+$/g, '');
		if (str[i] != "" && !this.arrayIndexOf(str2, str[i])) {
			str2.push(str[i]);
		}
	}
	return str2;
}

//inline error messages within rounded-corner modules
Common_class.prototype.drawInlineMsg = function(msgType, msg) {
	var msgType = msgType || "errStandard";
	var template = Element.get(msgType);
	var msgNode = Element.parseSelector("span.errMsgText", template, "first");

	if (msgType == "errStandard" && msg) Element.setHTML(msgNode, msg);

	var errNode = Element.parseSelector("div.errMsg", null, "first");
	Element.removeChildNodes(errNode);

	var inlineErr = template.cloneNode(true);
	errNode.appendChild(inlineErr);
	Element.setDisplay(inlineErr, "block");
	Element.setDisplay(errNode,"block");
}

//Loads a page that loggs the user off if they aren't logged in through TDAM
Common_class.prototype.tempAccessLogoff = function() {
	Common.loadContentBuffer({
		page:buildAbsolutePath("/common/tempAccessLogoff.asp"),
		contentType:"text/html",
		data:{
		},		
		onload:function() {
		},			
		onerror: function() { }
	});
}

Common_class.prototype.showInfoHover = function(el,content,over) {	
	if (moduleContainer = Element.get("infoHoverModule")) {
		Element.remove(moduleContainer);
	}
	else {
		var moduleContainer = Element.create("div",{id:"infoHoverModule"},null);
		var size = Element.getSize(el);
		var pos = Element.getXY(el);
		Element.setHTML(moduleContainer, content);
		Element.addChild(document.body,moduleContainer);
		var x, y;
		try {
			x = pos.x + size.width + 5;
			y = pos.y - 50;
		}
		catch(err){
			Element.remove(moduleContainer);
			return;
		}		

		var pageSize = Element.getSize(document.body);
		var moduleSize = Element.getSize(moduleContainer);

		if (x + moduleSize.width > pageSize.width) {
			x = pos.x - moduleSize.width - 10;
		}

		// move over if too far left
		if (x < 5) {
			x = 5;
		}

		// move below if won't fit above
		if (y < 5) {
			y = 5;
		}

		Element.setXY(moduleContainer,x,y);
	}

}




Common_class.prototype.showMstarRatingModule = function(el,symbol,over) {
	if (!Features.getAllowed("Funds.MstarRatingModule")) {
		
		return;
	}

	if (window.showMstarRatingModule_TIMER) {		
		clearTimeout(window.showMstarRatingModule_TIMER);
		window.showMstarRatingModule_TIMER = null;
	}

	if (!over) {
		Common.contentBufferAbortRequests();
		if (moduleContainer = Element.get("mStarRatingsModule")) {
			Element.remove(moduleContainer);
		}
	}
	else {
		var el = Element.getParent(el,"span",true);
		if (!el) { return; }
		showMstarRatingModule_TIMER = setTimeout(function() { Common.showMstarRatingModuleDelay(el,symbol,over) },50);
	}

}

Common_class.prototype.showMstarRatingModuleDelay = function(el,symbol) {

	Common.contentBufferAbortRequests();
	Common.loadContentBuffer({
		page:buildAbsolutePath("etfs/buffer_mStarRatingsModule.asp"),
		context:this,
		contentType:"text/html",
		data:{
			symbol:symbol
		},
		onload:function(cb) {
		
			var moduleContainer = Element.create("div",{id:"mStarRatingsModule"},null);
			var size = Element.getSize(el);
			var pos = Element.getXY(el);
			var HTML = cb.getResult();
			if (/error/.test(HTML)) { return; }
			Element.setHTML(moduleContainer,HTML);
			Element.addChild(document.body,moduleContainer);
			var x = pos.x+size.width+5;
			var y = pos.y-50;

			var pageSize = Element.getSize(document.body);
			var moduleSize = Element.getSize(moduleContainer);

			// move over if too far right
			if (x + moduleSize.width > pageSize.width) {
				x = pos.x - moduleSize.width - 10;
			}

			// move over if too far left
			if (x < 5) {
				x = 5;
			}

			// move below if won't fit above
			if (y < 5) {
				y = 5;
			}

			Element.setXY(moduleContainer,x,y);

		},
		onerror:null
	});


}

Common_class.prototype.popWindow = function(e, el, data)
{
	Events.cancel(e);
	
	this.popCustomWindow(data);
}

Common_class.prototype.popCustomWindow = function(props)
{	
	if (!props.path) { return; }
	if (!props.name) { 
		props.name = "Popup" + Math.random(1); 
		props.name = props.name.replace(/\./g, "");
	}
	
	var attributes = [];
	if (props.width) { attributes.push("width="+props.width); }
	if (props.height) { attributes.push("height="+props.height); }
	if (props.top) { attributes.push("top="+props.top); }
	if (props.left) { attributes.push("left="+props.left); }
	if (props.location) { attributes.push("location="+props.location); }
	if (props.menubar) { attributes.push("menubar="+props.menubar); }
	if (props.resizable) { attributes.push("resizable="+props.resizable); }
	if (props.scrollbars) { attributes.push("scrollbars="+props.scrollbars); }
	if (props.status) { attributes.push("status="+props.status); }
	if (props.toolbar) { attributes.push("toolbar="+props.toolbar); }
	
	window.open(props.path, props.name, attributes.join(","))
}

Common_class.prototype.addTopLink = function(el, text)
{
	var timestampBar = Element.get("timestampBarRight");

	if (timestampBar) {
		if (this.hasTopLink) {
			Element.create("div",{className:"headerHelpBarSpacer"},"|",timestampBar);
		}
		Element.addChild(timestampBar, el);
		
		if(text) {
			Element.addChild(timestampBar, Element.create("span", {className:"fleft black"}, '&nbsp;' + text + '&nbsp;'));
		};
		
		this.hasTopLink = true;
	};
}

Common_class.prototype.addTedToolLink = function() {
	
	var tedLink = Element.create("a", {id:"Header_TedTool", className:"iconBackground", href:"javascript://-tedTool"}, [
					Element.create("span", {style:"color:#EEE;text-decoration:underline"}, [
						,Element.create("span", {className:"newFeature"}, "*NEW*")
					])
					,"Question? Ask Ted"
	]);
	
	Events.add({element:tedLink, type:"click", handler:this.openTedTool, context:this})
	
	this.addTopLink( tedLink, null );
};


Common_class.prototype.openTedTool = function(ev, el, data) {
	
	el.blur();
	
	
	var windowHeight = screen.height > 800? 647 : 530;
	var optionsString = "height=" + windowHeight + ",width=250, 0";
	
	window.open("https://wwws.ameritrade.com/activeagentwebui/Agent.aspx", "TedTool", optionsString);
};

Common_class.prototype.renderTDAMButtons = function(container) {
	container = container ? Element.get(container) : document.body;
	var buttonLinks = Element.parseSelector('a[tdbutton]',container);
	// Create TDAM buttons from links
	for (var i=0; i<buttonLinks.length; i++) {
		if (/#$/.test(buttonLinks[i].getAttribute("href"))) {
			buttonLinks[i].setAttribute("href","javascript:void(0)");
		}
		btnInit(buttonLinks[i].id,buttonLinks[i].getAttribute("tdbutton") == "green",buttonLinks[i].getAttribute("stateoff")?false:true,buttonLinks[i].getAttribute("width")||null);
	}
}

//////////////////////////////////////////////////////////////
// TDAM Provided Script
Common_class.prototype.attemptShowFrames = function(e, el, data)
{
	Events.cancel(e);

	var label = data.label || "";
	var symbol = data.symbol || "";

    // Trigger a reload of the new tda child frame passing in the button label and the symbol.

    this.chfr(label, symbol);
}

Common_class.prototype.chfr = function(label, symbol) {
	
	Element.get("tda").setAttribute("src", gSessionSeedDomain+'/cgi-bin/apps/u/PLoad?pagename=research/thirdPartyPopupProcess.html&target=' + label + '&param=' + symbol);
}

Common_class.prototype.initSymbolHover = function() {
	
	Events.add({
		 element:document.body
		,type:'mouseover'
		,handler:this.detectSymbolElement
		,context:this
		,delay:400
	});
};

Common_class.prototype.detectSymbolElement = function(e, el, data) {
	
	var elem = e.getTarget();
	
	if(elem.tagName && elem.tagName == "A") {
		
		var sy = elem.getAttribute('symbol');
		var isBridge = isNaN( parseFloat(sy) );
		
		if(sy && isBridge) {
			
			Events.add({
				 element:elem
				,type:'mouseout'
				,handler:this.hideSymbolHover
				,context:this
				,data:'removeHandler'
			});
			
			this.showSymbolHover(e, elem, sy);
		}
	}
};

Common_class.prototype.showSymbolHover = function(e, el, data) {

	var sy = data || el.innerHTML;

	if (!this["symbolHover" + sy]) {
		this.loadContentBuffer({
			 page: buildAbsolutePath("/modules/SymbolHover/SymbolHover.asp")
			,context: this
			,preventEval: true
			,data: {
				 symbol: sy
				,wsodIssue: el.getAttribute("issue")
			}
			,onload: function(data) {
				this.renderSymbolHover(e, el, data);
			}
		});
	} else {
		this.renderSymbolHover(e, el);
	}
};

Common_class.prototype.renderSymbolHover = function(e, el, data) {
	var symbolData = data ? DataFunctions.deserialize(data.getResult()) : {};
	var symbol = symbolData.DisplaySymbol || el.getAttribute('symbol') || el.innerHTML;
	var realtime = symbolData.realtime;

	if (!this["symbolHover"+symbol]) {
		this["symbolHover"+symbol] = Element.create("div", {"class":"symbolHover hide", "style":"display:block;"}, [
			Element.create("div", {"class":"symbolHoverInner"}, [
				 Element.create("h3", {"class":"symbolHoverHeader"}, [
					 symbolData.CompanyName || symbolData.AltCompanyName
					,Element.create("span", {}, [
						" ("+symbolData.Exchange+":"
						,Element.create("strong", {}, symbol)
						,")"
					])
				 ])
				,Element.create("div", {"class":"symbolInfo"}, [
					Element.create("label", {}, symbolData.Category? "" : "Sector:")
					,Element.create("span", {}, symbolData.Category? "" : symbolData.Sector)
				])
				,Element.create("div", {"class":"symbolInfo"}, [
					Element.create("label", {}, symbolData.Rating != undefined? "" : "Industry:")
					,Element.create("span", {}, symbolData.Rating != undefined? "" : symbolData.Industry)
				])
				,Element.create("div", {"class":"symbolInfo"}, [
					Element.create("label", {}, "Last:")
					,Element.create("span", {"class":"lastPrice"}, symbolData.Last)
					,symbolData.ChangeArrow
					,symbolData.Change
					,"&nbsp;"
					,symbolData.ChangePercent
				])
				,Element.create("img", {"src":symbolData.fileName, "class":"hoverChart"})
				,Element.create("div", {"class":"lastTradeTime"}, realtime?"Based on last trade at " + symbolData.LastTradeTime + " ET" : "Based on last delayed trade at " + symbolData.LastTradeTime + " ET")
			])
		], document.body);
		
		var elLoc = Element.getXY(el);
		var elSize = Element.getSize(el);
		var hoverSize = Element.getSize(this["symbolHover"+symbol]);
		
		Element.setXY(this["symbolHover"+symbol], elLoc.x + elSize.width, elLoc.y - (hoverSize.height / 2) + (elSize.height / 2))
	}
	/* reposition element if exists */
	var elLoc = Element.getXY(el);
	var elSize = Element.getSize(el);
	var hoverSize = Element.getSize(this["symbolHover"+symbol]);
	
	Element.setXY(this["symbolHover"+symbol], elLoc.x + elSize.width, elLoc.y - (hoverSize.height / 2) + (elSize.height / 2))

	Element.removeClass(this["symbolHover"+symbol], "hide");
}

Common_class.prototype.hideSymbolHover = function(e, el, data) {

	this.contentBufferAbortRequests();
	
	Element.addClass(Element.parseSelector("div.symbolHover"), "hide");
	
	if(data && "removeHandler" == data) {
		
		Events.remove(el, this.hideSymbolHover);
	}
}


Common_class.prototype.displayDefinition = function(e, el, data) {

	data = data || {};

	var defTitle = el.getAttribute("defTitle");
	var defText = el.getAttribute("defText");


	if (this.definitionModule) {
		// remove the module
		Element.remove(this.definitionModule);
		this.definitionModule = null;
	}
	if (data.close || defTitle == this.defTitle) {
		// Close if explicit or same definition
		this.defTitle = null;
		return;
	}

	this.definitionModule = Element.create("div",{className:"definitionModule"},[
		Element.create("div",{className:"definitionBody"},[
			Element.create("img",{className:"definitionClose",src:"https://tdameritrade.cache.wallst.com/images/charts/ico-close.gif",Events:{type:"click",handler:this.displayDefinition,context:this,data:{close:true}}})
			,Element.create("div",{className:"definitionTitle"},defTitle)
			,Element.create("div",{className:"definitionText"},defText)
		])
	],document.body);


	// Postion under the link
	var pos = Element.getXY(el);
	Element.setXY(this.definitionModule,pos.x,pos.y+16);

	// set reference for above logic
	this.defTitle = defTitle;

}

//
//////////////////////////////////////////////////////////////


Common = new Common_class();

 

/* -- Loaded:/tdameritrade/common/scripts/Common_class.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


function newCSS() {
	lk=document.getElementsByTagName("link");for (i in lk) {if (lk[i].href) { void(nl = lk[i].href.replace(".css","new.css")); void(lk[i].href = nl) } }
}
/* Common Javascript functionality goes in here */

/* Globals */
var b;

/*
iframe buffer support */
var gContentFrameId = false;
var gOnLoadHandler;

function loadContent (contentURL, contentFrameId, loadingBuffer, onLoadHandler) {
	if (loadingBuffer) {
		document.getElementById(contentFrameId).innerHTML = document.getElementById(loadingBuffer).innerHTML;
	}
	//frames["contentBufferFrame"].document.location.replace(contentURL);
	//window.status = frames["contentBufferFrame"].location

	//document.getElementById("contentBuffer").src = contentURL;

	frames["contentBufferFrame"].document.location.replace(contentURL);
	//contentBuffer.document.location.replace(contentURL);

	gContentFrameId = contentFrameId;

	if (onLoadHandler) {
		gOnLoadHandler = onLoadHandler;
	}
}

function handleContentLoadComplete (content) {
	if (gContentFrameId) {
		document.getElementById(gContentFrameId).innerHTML = content;
	}
	gContentFrameId = false;
	if (gOnLoadHandler) {
		gOnLoadHandler();
	} else {
		onLoadContent();
	}
}

function onLoadContent () { } /* Override this function to provide further behavior after the buffer has loaded */

/* End iframe Buffer */


function buildAbsolutePath(stub) {
	if (stub) {
		if (stub.charAt(0) == "/") { stub = stub.substring(1, stub.length) }
		return gGlobalPath + stub;
	}
}

function buildSymbolLink(symbol) {
		return buildAbsolutePath('/stocks/overview/overview.asp?symbol=')+Common.encode(symbol);
}

function getPageSize() {
	var size = new sizeObj();
	var b = new browserObj();
	size.width = (b.isMajor && b.isIE) ? document.body.clientWidth : window.innerWidth;
	size.height = (b.isMajor && b.isIE) ? document.body.clientHeight : window.innerHeight;
	return size;
}
function getElementSize(obj) {
	var size = new sizeObj();

	size.width = obj.offsetWidth;
	size.height = obj.offsetHeight;

	return size;
}
function sizeObj(w, h) {
	this.width = w;
	this.height = h;

	this.toString = function() {
		return 'width: ' + this.width + ', height: ' + this.height;
	}
}


function getCurrPageWidth() {
	gCurrPageWidth = getPageSize().width;

}

var gResizeInitialized = false;
var columnOffsets = [false, .3, 389, 196, .4] // column 4 is actually 1.5
function initContent() {

	resizeContent();
	if (gContent) {
		//gContent.style.visibility = 'visible';
	}


	if (gSiteContainer) {
		// show content after it has rendered itself
		gSiteContainer.style.visibility = "visible";
	}

	if (gTopNavIframe) {
		// load header iframe url
		//gTopNavIframe.src = gTopNavIframe.getAttribute("newsrc");
		//alert(topNavIframe.location)

		// This method doesn't add to the history
		topNavIframe.location.replace(topNavIframeSRC);
	}

	for (var x = 0; x < gStretchable.length; x++) {
		//alert(gStretchable[x].getAttribute("newsrc"))
		if (gStretchable[x].type == "element") {
			gStretchable[x].el.setAttribute("src", gStretchable[x].el.getAttribute("newsrc"))
		}

	}
	setWidescreen();
	gResizeInitialized = true;
	
	var smartFocusInputs = Element.parseSelector("input[smartFocus]");
	for (var i = 0; i < smartFocusInputs.length; i++) {
		Element.addClass(smartFocusInputs[i], "lighter");
		if (smartFocusInputs[i].getAttribute("id") == "symbol") {
			var a = smartFocusInputs[i];
			Common.focusField(null, smartFocusInputs[i], {selectText: true});
			setTimeout(function() {
				Events.add({element: a, type: "focus", context: Common, handler: Common.focusField, data: {selectText: true}});
				Events.add({element: a, type: "click", context: Common, handler: Common.focusField, data: {selectText: true}});
			},5)
		} else {
			Common.focusField(null, smartFocusInputs[i]);
			Events.add({element: smartFocusInputs[i], type: "focus", context: Common, handler: Common.focusField});
		}
		Events.add({element: smartFocusInputs[i], type: "blur", context: Common, handler: Common.blurField});
	}
	
	if (window.opener && Element.get("right")) {
		var buySellLinks = Element.parseSelector("a[target='vendorLinks']!tradeLink", Element.get("right"));
		var regExCheck, label, symbol;
		for (var i = 0; i < buySellLinks.length; i++) {
			regExCheck = buySellLinks[i].getAttribute("href").match(/target=(.*)&param=(.*)/);
			if (regExCheck) {
				buySellLinks[i].setAttribute("href", "javascript:void(0)");
				label = RegExp.$1;
				symbol = RegExp.$2;
				
				Events.add({element:buySellLinks[i], type: "click", context: Common, handler: Common.attemptShowFrames, data: {label: label, symbol: symbol}});
			}
		}
	}

	// add a refresh title to the images	
	var refreshIcons = Element.parseSelector("img[src*='icn_refresh']", document.body);
	if (refreshIcons) { Element.setAttribute(refreshIcons, "title", "Refresh"); }

	var fastLookup = new FastLookup('symbolSearch');
	
	fastLookup.setRequestor(new CrossDomainRequestor());
	fastLookup.setRequestURL(buildAbsolutePath("/common/fastlookup/buffer_fastlookupresults.asp"));
	fastLookup.setFinderURL(buildAbsolutePath("/symbollookup/symbollookup.asp"));
	fastLookup.requestor.setGlobalContext("window._wsodFastLookup");	

	window._wsodFastLookup = fastLookup;


}

function resizeHandler() {
	closeRecentSymbols();
	resizeContent();
	sizeFullWidths.onResize(); // resize chart images to 100% width
}


function resizeContent() {

	//window.status = 'resized' + new Date().getTime();

	//alert("tempTest resize");

	if (!gContent) {
		gContent = document.getElementById("content");
	}
	if (!gDisclaimer) {
		gDisclaimer = document.getElementById("disclaimer");
	}
	if (!gLeftNav) {
		gLeftNav = document.getElementById("left");
	}
	if (gContent) {

		getCurrPageWidth();
		lNewContentWidth = (gCurrPageWidth) - 50;

		lNewContentWidth = Math.max(lNewContentWidth, gMinContentWidth);
		lNewContentWidth = Math.min(lNewContentWidth, gMaxContentWidth);


		if (gSiteContainer) {
			Element.setWidth(gSiteContainer,lNewContentWidth);
		}


		//dbg(lNewContentWidth);
		//gContent.style.width = lNewContentWidth + "px";
		//window.status = lNewContentWidth + ',' + gContent.style.width + ',' + gContent.offsetWidth;

		if (b && b.isMajor /*&& b.isIE*/ ) {

			for (var x = 0; x < gStretchable.length; x++) {

				var columnOffset = 0;
				if (gStretchable[x].type == "element") {
					if (gStretchable[x].el.getAttribute("columns")) {
						columnOffset = columnOffsets[parseInt(gStretchable[x].el.getAttribute("columns"))]

					}
					if (gStretchable[x].el.getAttribute("snapping") == "true") {

						//var potentialChartWidth = lNewContentWidth - columnOffset;

						var diff = gMaxContentWidth - gMinContentWidth;
						var snaps = 10;

						var snapSize = diff / snaps
						//window.status = snapSize;

						//dbg(lNewContentWidth + ',' + gMinContentWidth + ',' + gMaxContentWidth);

						for (var z = 0; z < snaps + 1; z++) {
							var currSnap = gMinContentWidth + Math.floor(snapSize * z);

							//dbg(currSnap + ',' + (snapSize * z) + ',' + snapSize + ',' + z);

							//alert(currSnap + ',' + (diff / z));

							if (lNewContentWidth <= currSnap) {
								lNewContentWidth = gMinContentWidth + Math.floor((diff / snaps) * (z - 1));
								break;
							}

							//window.status = lNewContentWidth + ',' + ((diff / snaps) * (z - 1)) + ',' + currSnap;
						}

						//window.status = (lNewContentWidth);
						gStretchable[x].el.style.width = lNewContentWidth - columnOffset;

					} else if (columnOffset < 1) { // switch to percentage-based
						gStretchable[x].el.style.width = (lNewContentWidth * columnOffset) - 40;
					} else {
						gStretchable[x].el.style.width = lNewContentWidth - columnOffset;
					}
					//dbg(gStretchable[x].el.style.width + ',' + lNewContentWidth + ',' + columnOffset);
					gStretchable[x].el.style.height = gStretchable[x].el.origHeight;

			// added JH: needed for valuation page to work correctly
				} else if (gStretchable[x].type == "other") {

					var minWidth = gStretchable[x].minWidth;
					var maxWidth = gStretchable[x].maxWidth;

					var tWidth = (gCurrPageWidth - 20) * gStretchable[x].pctOf;

					if (tWidth < minWidth) {
						var nWidth = minWidth;
					} else if (tWidth > maxWidth) {
						var nWidth = maxWidth;
					} else {
						var nWidth = tWidth;
					}
					gStretchable[x].newWidth = nWidth

				} else {

					if (gStretchable[x].columns) {
						columnOffset = columnOffsets[gStretchable[x].columns];
					}
					if (columnOffset < 1) { // switch to percentage-based
						gStretchable[x].newWidth = (lNewContentWidth * columnOffset) - 40;
					} else {
						gStretchable[x].newWidth = lNewContentWidth - columnOffset  //- 196 - 389;
					}

				}
			}

			if (gTimeoutId) {
				clearTimeout(gTimeoutId);
			}
			if (lNewContentWidth >= gMaxContentWidth && gResizeInitialized) {
				gTimeoutId = setTimeout('setWidescreen(true)', gPause);
			} else {
				gTimeoutId = setTimeout('setWidescreen(false)', gPause);
			}
		}
	}
}
function setWidescreen(wide) {
//alert("i am wide");
	//dbg(gIsWidescreen + ',' + wide);
	if (wide && !gIsWidescreen) {
		gIsWidescreen = true;
		for (var x = 0; x < gStretchable.length; x++) {
			widenElement(gStretchable[x], true);
		}
	} else if (!wide /* && gIsWidescreen*/) {
		gIsWidescreen = false;
		for (var x = 0; x < gStretchable.length; x++) {
			widenElement(gStretchable[x], false);
		}
	}
}
function widenElement(elObj, wide) {

	if (elObj.type == "element") {
		var maxWidth = 0;
		if (wide) {
		maxWidth = elObj.el.getAttribute("maxWidth");
		} else if (getElementSize(elObj.el).width) {
			maxWidth = parseInt(elObj.el.style.width);
		} else if (elObj.el.style.width) {
			maxWidth = parseInt(elObj.el.style.width);
		}
		elObj.el.style.visibility = "visible";
		changeUrl(elObj, maxWidth);

	} else if (elObj.type == "script") {

		//var w = (wide) ? elObj.newWidth : elObj.minWidth;
		//dbg(elObj.newWidth + "!");
		var w = elObj.newWidth;
		//dbg(elObj.script + '(' + w + ')')
		eval(elObj.script + '(' + w + ')')

	} else if (elObj.type == "other") {

		// JH: Handles a custom resize
		var w = elObj.newWidth
		eval(elObj.script + '(' + w + ')');

	} else if (elObj.type == "manual") {
		var w = elObj.el.getAttribute("newWidth");
		//dbg(w + "!");
		if (elObj.el.getAttribute("newsrc") != "") {  // switch the manuals here to prevent double-loading
			elObj.el.setAttribute("src", elObj.el.getAttribute("newsrc"));
			elObj.el.setAttribute("newsrc", "");
		}
		changeUrl(elObj, w);
	}

	function changeUrl(elObj, w) {
		var url = elObj.el.getAttribute("src");
		if (url.indexOf('/gif/x.gif') == -1) {
			var qs = url.split('?')[1].split('&');
			for (var y = 0; y < qs.length; y++) {
				if (qs[y].split('=')[0].toLowerCase().indexOf('width') > -1) {
					qs[y] = qs[y].split('=')[0] + '=' + w;
				}
			}
			url = url.split('?')[0] + '?' + qs.join('&');
			elObj.el.src = url;
		}
	}

}


var gContent = null;
var gLeftNav = null;
var gRuler = null;
var gDisclaimer = null;
var gMinContentWidth = 750;
var gMaxContentWidth = 984;
var gCurrPageWidth; var lNewContentWidth;
var gIsWidescreen = false;
var gTimeoutId;
var gPause = 500;

var gStretchable = [];
var gSiteContainer = null;
var gTopNavIframe = null;

function registerStretchableElements() {


	gSiteContainer= document.getElementById("siteContainer");

	gTopNavIframe= document.getElementById("topNavIframe");


	var els = document.getElementsByTagName("IMG");
	for (var x = 0; x < els.length; x++) {

		if (els[x] && els[x].className && els[x].className.toLowerCase().indexOf("stretchy") > -1) {
			//dbg("!" + getElementSize(els[x]).height + "!");
			var htCheck = els[x].getAttribute("newsrc").toString().match(/\&height=([^\&]*)/gi);
			var ht = RegExp.$1;
			if (ht) ht = parseInt(ht);
			els[x].origHeight = (getElementSize(els[x]).height) ? getElementSize(els[x]).height : ht;

			gStretchable[gStretchable.length] = {el:els[x], type:'element'};
		}
	}
}
function addStretchableElement(el) {
	el.origHeight = el.clientHeight;
	gStretchable[gStretchable.length] = {el:el, type:'element'};
	return true;
}
function addStretchableScript(sc, minWidth, maxWidth, columns) {
	gStretchable[gStretchable.length] = {script:sc, minWidth:minWidth, maxWidth:maxWidth, columns:columns, type:'script'};
}

// Custom or other - this one is more based on a percentage
function addStretchableOther(sc, minWidth, maxWidth, pctOf) {

	// pctOf = percent of page - constrainted by min/max
	gStretchable[gStretchable.length] = {script:sc, minWidth:minWidth, maxWidth:maxWidth, pctOf:pctOf, type:'other'};
}


/* Initializations */

function initBrowserObj() {
	b = new browserObj();
}
loadBuffer.add(initBrowserObj);
loadBuffer.add(registerStretchableElements);
loadBuffer.add(initContent);
loadBuffer.add('initHelp()');
resizeBuffer.add(resizeHandler);
resizeBuffer.add("resizeHelp()");
loadBuffer.add(function() { sizeFullWidths.init(); })
loadBuffer.add(function(){ Common.assignTabEvents(); });






/* Pop Wins */

var messageWindow = false;
function launchPDF(pageFile,rptInfo,rptName) {
	//rptInfo  = RptCusip, RptNumber, RptData
	//RptNumber indicates imageserver report
	//RptData is either doc tag or tran id
	if ((!messageWindow) || (messageWindow.closed)) {
		messageWindow = window.open(buildAbsolutePath('/common/reports/get_report.asp') + '?RptName=' + rptName + '&' + rptInfo,pageFile,"width=700,height=450,status=no,menubar=no,toolbar=no,scrollbars=auto,resizable=yes");
		messageWindow.focus();
	} else {
		messageWindow.focus();
		messageWindow = window.open(buildAbsolutePath('/common/reports/get_report.asp') + '?RptName=' + rptName + '&' + rptInfo,pageFile,"width=700,height=450,status=no,menubar=no,toolbar=no,scrollbars=auto,resizable=yes");
	}
}

var newWin = false
function keyPopUp(type,content) {
	var w=517, h=300 //defaults to legal size since this is the only type we have so far
	if ((!newWin) || (newWin.closed)) {
		newWin = window.open(buildAbsolutePath('/common/popWin/popWin.asp') + '?type=' + type +'&content=' + content, 'newWin','width='+w+',height='+h+',status=no,menubar=no,toolbar=no,scrollbars=yes,resizable=yes');
		newWin.focus()
	} else {
		newWin.focus()
		window.open(buildAbsolutePath('/common/popWin/popWin.asp') + '?type=' + type +'&content=' + content, 'newWin','width='+w+',height='+h+',status=no,menubar=no,toolbar=no,scrollbars=yes,resizable=yes');
	}
}

function launchExternal(pageFile,url) {   // Launches external URLs
	//eval('windowname = ' + pageFile + 'Window')
	windowname = newWin
	if (pageFile == 'gsLegal' || pageFile == 'chartHelp') {
		extra = 'toolbar=no,scrollbars=yes,resizable=yes,status=no,menubar=no,titlebar=no,location=no,width=645,height=400'
	} else if (pageFile == "marketMonitor") {
		extra = 'toolbar=no,scrollbars=yes,resizable=yes,status=no,menubar=no,titlebar=no,location=no,width=800,height=600'
	} else if (pageFile == "ideas") {
		extra = 'toolbar=no,scrollbars=yes,resizable=yes,status=no,menubar=no,titlebar=no,location=no,width=925,height=600'
	} else if (pageFile == "marketHuddle" || pageFile == "webcasts") {
		extra = 'toolbar=no,scrollbars=yes,resizable=yes,status=no,menubar=no,titlebar=no,location=no,width=900,height=700'
	} else {
		extra = 'toolbar=yes,scrollbars=yes,resizable=yes,status=yes,menubar=yes,titlebar=yes,location=yes,width=645,height=400'
	}
	if ((!windowname) || (windowname.closed)) {
		windowname=window.open(url,pageFile,extra);
		windowname.focus();
	} else {
		windowname.focus();
		windowname=window.open(url,pageFile,extra);
	}
}

var gMarketMonitorWindow;
function launchMarketMonitor(s) {
	if (arguments.length == 0) { s = '' }

	// not available to the public
	var url = buildAbsolutePath('/markets/marketmonitor/?symbol=' + s);

	gMarketMonitorWindow = window.open(url, 'mktmon_window', "width=785,height=630,scrollbars=no,menubar=no,status=yes,resizable=no");
	try {
		gMarketMonitorWindow.focus();
	} catch(e) {}
}

var gSymbolLookupWindow;
function launchSymbolLookup(path, wide) {

	var props = "toolbars=no,scrollbars=yes,resizable=yes";
	if (wide) {
		props += ",width=570,height=500";
	} else {
		props += ",width=400,height=400";
	}
	gSymbolLookupWindow = window.open(path, 'symbollookup_window', props);
	try {
		gSymbolLookupWindow.focus();
	} catch(e) {}
}



/* Help functionality */

function pageHelp() {
	window.status = 'Toggle Page Help'
	// stubbed for future authoring
}

var gChartHelp;
function showChartHelp() {
	gChartHelp = window.open('http://custom.marketwatch.com/custom/tdwaterhouse/help2/index/default.asp', 'charthelp_window', "height=475,width=600,resizable=1,scrollbars=1,toolbar=1");
	try {
		gChartHelp.focus();
	} catch(e) {}
}

function selectTab(who,s){
	
	
	document.getElementById(defaultTab).style.display = "none";
	document.getElementById(who).style.display = "block";


	/* TDAM change */
	document.getElementById("tab_"+defaultTab).className = "";
	document.getElementById("tab_"+who).className = "current";
	
	document.getElementById("tab_"+who).firstChild.blur();
	defaultTab = who;

	return;

	if (s == 2) {
		document.getElementById("tab_"+defaultTab).style.backgroundColor = "#ffffff";
		document.getElementById("a_"+defaultTab).style.color = "#2E5C3E";
		document.getElementById("a_"+defaultTab).style.textDecoration = "underline";
	} else {
		document.getElementById("tab_"+defaultTab).style.backgroundColor = "#ffffff";
		document.getElementById("a_"+defaultTab).style.color = "#2E5C3E";
		document.getElementById("a_"+defaultTab).style.textDecoration = "underline";
	}

	if (s == 2) {
		document.getElementById("tab_"+who).style.backgroundColor = "#618D6E";
		document.getElementById("a_"+who).style.color = "#ffffff";
		document.getElementById("a_"+who).style.textDecoration = "none";
	} else {
		document.getElementById("tab_"+who).style.backgroundColor = "#ddebde";
		document.getElementById("a_"+who).style.color = "#000000";
		document.getElementById("a_"+who).style.textDecoration = "none";
	}

	//document.getElementById("tab_"+defaultTab).style.borderBottom = "1px solid #2D5C3D";
	//document.getElementById("tab_"+defaultTab).style.zIndex = 1;
	
}


/* --------------------------------------------------------------------------------
storing into User.Preference()*/

function storePref(n, v, v2){
	
	if (n && v !== undefined){

		// Frame Method - replace() doesn't affect browser history
		frames["contentBufferFrame"].document.location.replace(buildAbsolutePath("/common/storePref.asp") + "?n="+n+"&v="+v+((v2)?"&v2="+v2:""));

		/*
		// AJAX Method - not used for now because of onload call backs

		var contentBuffer = new ContentBuffer();
		contentBuffer.load({
			url: buildAbsolutePath("/common/storePref.asp"),
			data: {
				n: n,
				v: v,
				v2: v2
			},
			contentType: "text/javascript",
			method: "post",
			debug: true
		});
		*/

	}
	Common.assignTabEvents();
}

function storePrefComplete(storeSuccessful, v, v2) {
	// NOW CALLED FROM CONTENT BUFFER
	// called when IFRAME onload is complete.
	// overwrite this function locally to customize for your page.
	//
	// storeSuccessful is t/f
	// v and v2 (optional) are passed back from the storing page for you to use in your functions.

	//alert("Pref Storage Complete. "+((v)?"v = " + v:"")+((v2)?"   v2 = " + v2:""));
}

var gPDFWindow;
function pdf(url) {
	gPDFWindow = window.open(url, 'pdf_window', "width=700,height=450,scrollbars=yes,menubar=no,toolbar=no,status=yes,resizable=yes");
	try {
		gPDFWindow.focus();
	} catch(e) {}
}

var modalDiv;
function initModalDialog() {
	if (!modalDiv) {
		var d = document.createElement("DIV");
		d.id = "modalDialog";
		var di = document.createElement("DIV");
		di.id = "modalDialog_inner";
		d.appendChild(di);

		if (document.body) {
			document.body.appendChild(d);
		} else {
			document.documentElement.appendChild(d);
		}
		modalDiv = di;
	}
	return modalDiv;
}
function displayModalDialog() {
	var d = initModalDialog();
	var currPageSize = getPageSize();
	var dialogSize = getElementSize(d);

	d.parentNode.style.top = ((currPageSize.height / 2) - dialogSize.height / 2) + "px";
	d.parentNode.style.left = ((currPageSize.width / 2) - dialogSize.width / 2) + "px";

	d.parentNode.style.visibility = 'visible';
}





function closeModalDialog() {
	var d = initModalDialog();
	d.parentNode.style.visibility = 'hidden';
	try {
		gEditIndicesEnabled = false;
	} catch(e) {
		//
	}
}

function editIndices() {
	gEditIndicesEnabled = true;
	var d = initModalDialog();
	onLoadContent = displayEditIndices;
	loadContent(buildAbsolutePath("/markets/editIndices.asp"), d.id, "loadingBuffer");

}
function displayEditIndices() {
	displayModalDialog();
	onLoadContent = function() {};
}

function showRecentSymbols(e, el) {
	if (document.getElementById("recentSymbols")) {
		var recentSymbols = document.getElementById("recentSymbols");
		if (recentSymbols.style.visibility == 'visible') {
			closeRecentSymbols();
			return false;
		}

		var coords = getAbsolutePos(el);
		recentSymbols.style.top = coords.y + 19;
		recentSymbols.style.left = coords.x;


		/*getCurrPageWidth();
		var currPageWidth = (gContent) ? getElementSize(gContent).width : gCurrPageWidth;*/

		//recentSymbols.style.left = currPageWidth - recentSymbols.offsetWidth;

		hideSelectElements(recentSymbols);

		recentSymbols.style.visibility = 'visible';

		if (e) {
			e.cancelBubble = true;
		}

		var b = new browserObj();
		if (b.isIE) {
			document.body.attachEvent("onclick", closeRecentSymbols);
		} else {
			document.body.addEventListener("onclick", closeRecentSymbols, true);
		}
	}
}
function closeRecentSymbols(e) {
	if (e) { e.cancelBubble = true; }
	var b = new browserObj();
	if (b.isIE) {
		document.body.detachEvent("onclick", closeRecentSymbols);
	} else {
		try {
		document.body.removeEventListener("onclick", closeRecentSymbols, true);
		} catch(e) { }
	}
	if (document.getElementById("recentSymbols")) {
		var recentSymbols = document.getElementById("recentSymbols");
			recentSymbols.style.visibility = 'hidden';
	}
	showSelectElements();
}
function highlightRecentSymbolsRow(trObj) {
	trObj.className = "mouseover";
}
function unhighlightRow(trObj) {
	trObj.className = "";
}
function selectSymbol(symbol, crossTab, crossTabSection, watchlistPopup) {
	document.getElementById("symbol").value = symbol;
	document.getElementById("symbol").form.submit();
	closeRecentSymbols();
}

function checkSymbolEntry(symbolObj, isInit) {
	if (!symbolObj) {
		symbolObj = document.getElementById("symbol");
	}
	if (symbolObj) {
		if (symbolObj.value.indexOf('...') > -1) {
			if (!isInit) {
				symbolObj.value = '';
			}
			symbolObj.focus();
			symbolObj.select();
		} else {
			symbolObj.focus();
			symbolObj.select();
		}
	}
}

function changeTextColor(el, color) {
	if (color != el.style.color) {
		el.style.color = color;
	}
}

function checkSymbol(crossTabURL, crossTabSection) {
	var symbolObj = document.getElementById("symbol");
	if (symbolObj.value != '' && symbolObj.value.indexOf('...') == -1) {
		if (crossTabURL) {
			buildCrossTabLink(crossTabURL + '?symbol=' + symbolObj.value, crossTabSection);
		} else {
			symbolObj.form.submit();
		}

		//symbolObj.form.submit();
	} else {
		return false;
	}
}

function disableLinks() {
	var theLinks = Element.parseSelector("a");
	Element.setStyle(theLinks,"text-decoration:none;color:black;cursor:default;");
	for(i=0;i<theLinks.length;i++) {
		theLinks[i].href = "javascript:void(0)";
		Events.remove(theLinks[i], "click"); // removeEvent was used in Events.2
		theLinks[i].onfocus = function() {this.blur();}
		theLinks[i].onmouseover = function() {
			Element.setStyle(this,"background-color:transparent;")
			window.status = "";
			return true;
		}
		theLinks[i].onclick = function() {return false;}
	}
}

function hideSelectElements(el) {
	if (b.isIE) {
		//var dbg = document.createElement("DIV");
		var str = '';

		var blackoutCoords = getAbsolutePos(el);
		var blackoutSize = getElementSize(el);

		str += 'Blackout:' + blackoutCoords + ',' + blackoutSize.width + ',' + blackoutSize.height + '<br />'

		var selects = document.getElementsByTagName("SELECT");
		var selectCoords; var selectSize;
		for (var x = 0; x < selects.length; x++) {
			selectCoords = getAbsolutePos(selects[x]);
			selectSize = getElementSize(selects[x]);

			if (
				!(selectCoords.x < blackoutCoords.x && selectCoords.x < blackoutCoords.x + blackoutCoords.width) &&
				!(selectCoords.y < blackoutCoords.y && selectCoords.y < blackoutCoords.y + blackoutCoords.height)
			) { // not perfect, but catches most cases
				selects[x].style.visibility = 'hidden';
				selects[x].setAttribute("HiddenByJavascript", "true");
			}


			str += 'Select' + x + ':' + selectCoords + ',' + selectSize.width + ',' + selectSize.height + '<br />'
		}

		//dbg.innerHTML = str;
		//document.body.appendChild(dbg);
	}
}
function showSelectElements() {
	var selects = document.getElementsByTagName("SELECT");
	for (var x = 0; x < selects.length; x++) {
		if (selects[x].getAttribute("HiddenByJavascript") == "true") {
			selects[x].style.visibility = 'visible';
			selects[x].setAttribute("HiddenByJavascript", "");
		}
	}
}



function printable(path) {
	//window.print();
	launchExternal('printable', path);

}

var origCompanyWidth;
var newCompanyWidth;
function resizeCompanyName(w) {
	//window.status = w;
	if (w) {
		var headerPrice = document.getElementById("headerPrice");
		var companyName = document.getElementById("companyName");
		var companySymbol = document.getElementById("companySymbol");

		if (!origCompanyWidth) {
			var companyNameSize = getElementSize(companyName);
			origCompanyWidth = companyNameSize.width;
		}

		var headerPriceSize = getElementSize(headerPrice);

		var companySymbolSize = getElementSize(companySymbol);

		//dbg(w + ',' + headerPriceSize.width + ',' + companySymbolSize.width);
		//window.status = (headerPriceSize.width + companySymbolSize.width) + ',' + w;

		//window.status = companyName.clientWidth;


		//alert(companyName.style.width);

		newCompanyWidth = Math.min(origCompanyWidth, w - (headerPriceSize.width + companySymbolSize.width - 20));
		newCompanyWidth = Math.max(1, newCompanyWidth);

		//window.status = newCompanyWidth;

		//dbg(newCompanyWidth);
		companyName.style.width = newCompanyWidth;
		//dbg(newCompanyWidth);
	}
}

function isVal(v){


	if (v && v != -32768){


		//dbg("isVal("+v+")", "true")
		return true;

	}
	//dbg("isVal("+v+")", "false")
	return false;

}

function getAbsolutePos (who) {

	var x = 0, y = 0, onscreen = true;

	var pNode = who;

	// detect if element is visible on the screen by nature of parent elements
	while(pNode && pNode.tagName.toUpperCase() != "HTML") {
		if (Element.getStyle(pNode,"display") == "none" || Element.getStyle(pNode,"visibility") == "hidden") {
			onscreen = false;
		}

		pNode = pNode.parentNode;
	}

	while (who.offsetParent != null) {

		x += who.offsetLeft
		y += who.offsetTop
		who = who.offsetParent
	}

	x += who.offsetLeft
	y += who.offsetTop
	return {x:x,y:y,onscreen:onscreen}
}


// Set Alerts and Trade Functions
function setAlert(who) {
	window.location.href = buildAbsolutePath('/alerts/edit_alerts.asp') + '?symbol='+who;
}

function trade(symbol, isFund) {
	//alert("Link to Trading area for "+who);

	if (isFund) {
		gotoTDPage('mf_trade', symbol);
	} else {
		gotoTDPage('trade', symbol);
	}

}

function accountSnapshot() {

	var url = gotoTDPage('account_snapshot', null, true, 'redirect');

	if (url) {
		var w = window.open(url,'snap_bal','height=220,width=180,left=25,top='+screen.height/3+',resizable=0,scrollbars=0,toolbar=0');
		try {
			w.opener=top;
		} catch(e) {}
	}


}


function gotoTDPage(pageID, symbol, returnUrl, specialTarget, noWindowClose) {
	var url = '';
	if (gTDPath) {
		url = gTDPath + '/nav/call_back?SID=' + gSID + '&pageID=' + pageID;
		if (symbol) { url += '&Symbol='+symbol; }
	}



	if (url) {
		if (specialTarget) {
			url += '&target=' + specialTarget;
		} else {
			url += gFrameTargetUrl;
		}

		if (returnUrl) {
			return url;
		} else {
			/*if (gIsPrivate) {
				if (top.opener!=null) { top.opener.top.TWEcontent.location = url; }   //Since Trade Icon can be called from a torn away SnapQuote Bar
				else {window.top.TWEcontent.location.href = url;}
			} else {
				window.top.location.href = url;
			}*/


			if (gIsPrivate) {
				if (top.opener) {
					top.opener.location.href = url;



					window.close();
				} else {
					location.href = url;
				}
			} else {
				location.href = url;
			}




			//window.top.TWEcontent.location.href = url;
			//parent.location.href = url;
		}
	}
}

function buildCrossTabLink(page, navID, targetAbsolute, noRedirect) {
	// verify that change is also made on Server Side common
	if (gTDPath) { // let's make sure that we can get to our own pages if the retVal wasn't passed

		if (!page) { page = '' }
		if (page.charAt(0) == '/') { page = page.substring(1, page.length) }
		if (!gIsPrivate && !page.match(/public/gi)) {
			page = 'public/' + page;
		}

		url = gTDPath + '/nav/generic_frameset?VenID=WSOD&navID1=quotes_research&navID2=' + navID + '&PageID=' + page + '&SID=' + gSID;
	} else {
		//url = '/tdameritrade' + page;
		url = page;
	}

	if (targetAbsolute) {
		url += '&target=opener.top.TWEcontent';
	} else {
		url += gFrameTargetUrl;
	}

	if (noRedirect) {
		return url;
	} else { // default
		location.href = url;
	}


}

function gotoMorningstar(symbol) {
	var url = '';
	if (gTDPath) {
		if (gIsPrivate) {
			url = gTDPath + '/nav/generic_frameset?VenID=MRSR&PageID=FP&symbol=' + symbol + '&SID=' + gSID+ '&navid1=quotes_research&navid2=mutual_funds';
		} else {
			url = gTDPath + '/nav/generic_frameset?VenID=MRSR&PageID=TDW/MShare/NewTDWMain.asp?MP=FP~ticker=' + symbol + '&navid1=quotes_research&navid2=mutual_funds';
		}
	}


	url += gFrameTargetUrl;

	/*if (gIsPrivate) {
		if (top.opener && top.opener.top && top.opener.top.TWEcontent && top.opener.top.TWEcontent.location) { top.opener.top.TWEcontent.location.href = url; window.close(); }   //Since Trade Icon can be called from a torn away SnapQuote Bar
		else {window.top.TWEcontent.location.href = url;}
	} else {
		window.top.location.href = url;
	}*/

	if (gIsPrivate) {
		if (top.opener) {
			top.opener.location.href = url;
			window.close();
		} else {
			location.href = url;
		}
	} else {
		location.href = url;
	}


}

function popChartWindow(pageType,symbol) {
	var name = "Chart" + Math.random(1);
	name = name.replace(/./g, "");
	
	var chartPath = "/stocks";
	if (pageType == "MF") { chartPath = "/mutualfunds"; }
	if (pageType == "ETF") { chartPath = "/etfs"; }

	window.open(buildAbsolutePath(chartPath + "/charts/charts.asp?display=popup"+(symbol?("&symbol="+symbol):"")), name, "width=810, height=755, scrollbars=yes, resizable=yes")
}

var dbgArr = [];
function dbg(str) {
	dbgArr[dbgArr.length] = str;
}
//loadBuffer.add("runDbg()");
function runDbg() {
	var debug = document.createElement('DIV');

	debug.innerHTML = dbgArr.join("<br />");

	document.body.appendChild(debug);
}




// displays text in a textarea for debugging
function debugTextarea(content) {
		var n1 = window.open('','');
		n1.document.write("<textarea style='width:99%;height:99%'>"+content+"</textarea>");
}

function getIndexSymbol(name) {
	
	var newSymbols = Features.getAllowed("All.NewSPSymbols");

	var indexMap = {
		 SPN:newSymbols?"US@SPN":"US&SPENE"
		,SPS:newSymbols?"US@SPS":"US&SPFIN"
		,OE:newSymbols?"US@OE":"US&OEX"
		,MD:newSymbols?"US@MD":"US&MID"
		,SP:newSymbols?"US@SP":"US;SPX"
		,SPC:newSymbols?"US@SPC":"US&SML"

	}

	return indexMap[name] || null;

}

function hitch (obj, meth) {
	return function () {
		return typeof meth == "function" ? meth.apply(obj, arguments) : obj[meth].apply(obj, arguments);
	};
};

/*
Attach to window.onresize
Resizes class="fullWidth" images to the full width of it's parent DIV container.
Assumptions: The image must be immediately surrounded in a div
*/
function sizeFullWidths() {
	this.timer = null;
	this.counter = 0;
	this.images = [];
}
sizeFullWidths.prototype.init = function() {

	this.getFullWidthImages();
	this.onResize();

}

sizeFullWidths.prototype.getFullWidthImages = function() {

	this.images = Element.parseSelector("img.fullWidth, div.fullWidth");

}

sizeFullWidths.prototype.onResize = function() {

	Element.setStyle(this.images,"width:0px;"); // resize so that the parent DIV's width isn't constrained

	if (this.timer) clearTimeout(this.timer);
	var ths = this;
	this.timer = setTimeout(function() {
		ths.onResizeDelay();
		},100);

}

sizeFullWidths.prototype.onResizeDelay = function() {

	Element.setStyle(this.images,"width:0px;");

	var parentDiv,parentDivWidth,newSrc,imgSrc;
	for (var i=0; i < this.images.length; i++) {
		parentDiv = Element.getParent(this.images[i],"div");
		parentDivWidth = Element.getSize(parentDiv).width;
		Element.setStyle(this.images[i],"width:"+parentDivWidth+"px;");

		// grab the new source (hasn't loaded yet) or current source (already loaded)
		newsrc = this.images[i].getAttribute("newsrc")
		if (newsrc) {
			imgSrc = newsrc;
			this.images[i].setAttribute("newsrc","");
		}
		else {
			imgSrc = this.images[i].getAttribute("src");
		}

		widthRE = new RegExp("(^.*Width=)(\\d{0,4})(.*)","i");
		
		var tagName = this.images[i].tagName.toLowerCase();

		if (tagName == "img"  && imgSrc.match(widthRE)) {
			// only reset the source if the width has changed
			if (!this.images[i].currentWidth || (this.images[i].currentWidth && this.images[i].currentWidth != parentDivWidth)) {
				imgSrc = (RegExp.$1)+parentDivWidth+(RegExp.$3);
				this.images[i].currentWidth = parentDivWidth;
				this.images[i].setAttribute("src",imgSrc);
			}
		}
		else {
			this.images[i].style.width = parentDivWidth + "px";
		}

	}

}

sizeFullWidths = new sizeFullWidths();





function DataFunctions() {};

function DataFunctions() {
	this.serializer = new Serializer();
	this.serializer.addTypeExclusion("function");

	this.serializerNoEncode = new Serializer();
	this.serializerNoEncode.allowEncoding(false);
	this.serializer.addTypeExclusion("function");
};

// Serialize/Deserialize between Javascript object structure and string
DataFunctions.prototype.serialize = function(jsObject) {
	return this.serializer.serialize(jsObject);
}
DataFunctions.prototype.deserialize = function(str) {
	return this.serializer.deserialize(str);
}


DataFunctions.prototype.convertToArraySortable = function(arr) {
	var arrayS = new ArraySortable(); for (var i=0;i<arr.length;i++) { arrayS.push(arr[i]); }
	return arrayS;
}


var DataFunctions = new DataFunctions();


// Firebug console message wrapper.  Will use WSOD's dbg() if Firebug isn't installed or on IE
if (!window.console){ 
	console = {
		log:function(s) { dbg(s); }
		,info:function(s) { dbg("Info: "+ s,"","blue"); }
		,error:function(s) { dbg("Error: "+ s,"","red"); }
		,warn:function(s) { dbg("Warning: "+ s,"","orange"); }
	}
}




////////////////////////////////////////////////////////////////



	OverviewChart_class = function() {

		this._symbols = []; // used on Markets Overview or other pages where you can switch the symbol

	}

	OverviewChart_class.prototype.init = function(args) {

		if (!args) { args = {}; }

		this.oldTimeFrame = args.timeframe || "current";

		this.currCompares = [];

		this.chart = Element.get("chart");
		this.error = Element.get("chartError");

		this.chart.onload = function() { OverviewChart.displayChart();};
		this.chart.onerror = function() {
			if ("current" == args.timeframe && "true" == this.CurrentChartUnavailable) {
				OverviewChart.displayError();
			} else if ("current" == args.timeframe) {
				this.CurrentChartUnavailable = "true";
				OverviewChart.switchChart("1mo");
			} else {
				OverviewChart.displayError();
			}
		};

		// TODO - add MorningStar category symbols here when we get them
		this.compares = {
			 "current":{symbol:'', color:''}
			,"DJI":{symbol:'us&DJI', color:'FBBA55'}
			,"SP500":{symbol:getIndexSymbol('SP'), color:'2A5E3A'}
		}
	}

	OverviewChart_class.prototype.displayChart = function() {

		this.chart.style.display = "block";
		this.error.style.display = "none";
	}


	OverviewChart_class.prototype.displayError = function() {

		this.chart.style.display = "none";
		this.error.style.display = "block";

	}

	OverviewChart_class.prototype.displayLoading = function() {
		// not used
	}

	OverviewChart_class.prototype.symbol = function(symbol) {

		if (symbol !== undefined) { this._symbol = symbol; };
		return this._symbol;

	}

	OverviewChart_class.prototype.symbols = function(symbols) {

		if (symbols !== undefined) { this._symbols = symbols; };
		return this._symbols;

	}


	OverviewChart_class.prototype.switchChart = function(timeframe) {

		Element.toggleClass(Element.get("ch_"+this.oldTimeFrame),"active");
		Element.toggleClass(Element.get("ch_"+timeframe),"active");
		Element.get("ch_"+timeframe).blur();
		this.oldTimeFrame = timeframe;

		var chartSrc = this.chart.src;

		chartSrc = chartSrc.replace(/[?&]timeframe\=([^?&$]+)/gi, '').replace(/[?&]timeframe\=/gi, '');
		chartSrc = chartSrc.replace(/[?&]ruleoverride\=([^?&$]+)/gi, '');

		var now = new Date();
		var nowYear = now.getFullYear();
		var januaryFirst = new Date("January 1, " + nowYear);
		var YTDDays= Math.floor((((now.getTime()-januaryFirst.getTime())/24)/60)/60/1000);

		var timeframes = {'current':'', '5da':'5', '1mo':'30', '3mo':'90', '6mo':'180', 'YTD':YTDDays, '1yr':'365', '3yr':'1095', '5yr':'1825', '10yr':'3650'};

		if (timeframe == '5da') {
			chartSrc += '&ruleOverride=isWeekend';
		} else {
			chartSrc += '&timeframe=' + timeframes[timeframe];
		}
		this.chart.src = chartSrc;

	}



		OverviewChart_class.prototype.loadHistoricalData = function(isHistInterface) {

			var prefix = (isHistInterface) ? "histBuffer" : "hist";

			var hist_month = document.getElementById(prefix + "_month");
			hist_month = hist_month[hist_month.selectedIndex].value;

			var hist_day = document.getElementById(prefix + "_day");
			hist_day = hist_day[hist_day.selectedIndex].value;

			var hist_year = document.getElementById(prefix + "_year");
			hist_year = hist_year[hist_year.selectedIndex].value;

			var d = hist_month + '-' + hist_day + '-' + hist_year;
			//alert(d);

			document.getElementById("timeframe_controls").style.display = "none";
			document.getElementById("priceData").style.display = "none";
			document.getElementById("histData").style.display = "block";

			var chartSrc = document.getElementById("chart").src;
			chartSrc = this.cleanHistUrl(chartSrc);
			chartSrc += '&histDate=' + d;
			chartSrc += '&showSplits=true';
			//alert(chartSrc);
			//window.open(chartSrc);
			document.getElementById("chart").src = chartSrc;

			loadContent("historicalData_buffer.asp?symbol="+this.symbol()+"&date=" + d, "histData", false, this.cleanup);


		}

		OverviewChart_class.prototype.cleanup = function() {
			if (!b.isIE) {
				//document.getElementById("overviewChartContainer").style.height = (getElementSize(document.getElementById("histData")).height + 20) + "px";
			}
		}

		OverviewChart_class.prototype.cleanHistUrl = function(url) {
			url = url.replace(/[?&]histDate\=([^?&$]+)/gi, '').replace(/[?&]histDate\=/gi, '');
			url = url.replace(/[?&]showSplits\=([^?&$]+)/gi, '').replace(/[?&]showSplits\=/gi, '');
			return url;
		}

		OverviewChart_class.prototype.todaysQuote = function() {
			document.getElementById("timeframe_controls").style.display = "inline";
			document.getElementById("priceData").style.display = "block";
			document.getElementById("histData").style.display = "none";
			if (!b.isIE) {
				//document.getElementById("overviewChartContainer").style.height = (getElementSize(document.getElementById("priceData")).height) + "px";
			}


			var chartSrc = this.chart.src;
			chartSrc = this.cleanHistUrl(chartSrc);
			document.getElementById("chart").src = chartSrc;


		}


	OverviewChart_class.prototype.switchMarketOverviewChartIndex = function(indexNum) {

		//alert(this.symbols)
		var chartSrc = this.chart.src;

		chartSrc = chartSrc.replace(/us&DJI/gi,""); // & was coming through in .src on certain servers
		chartSrc = chartSrc.replace(/[?&]symbol\=([^?&$]+)/gi, '').replace(/[?&]symbol\=/gi, '');


		chartSrc += '&symbol=' + escape(this.symbols()[indexNum]);
		this.chart.src = chartSrc;
		
		if (frames["predictWallSt"]) {
			var symbolMap = {
				 "us&DJI": "DJIA" 
				,"us;COMP": "NASDAQ"
				,"US@SP": "S&P 500"
				,"US;SPX": "S&P 500"				
			};
			var frameLocation = Element.get("predictWallSt").src;
			frames["predictWallSt"].location.replace(frameLocation.replace(/(symbol=)[^&]*/i,"$1" + Common.encode(symbolMap[this.symbols()[indexNum]])));
		}

		Common.contentBufferAbortRequests();
		Common.loadContentBuffer({
			page:"chartTabsBuffer.asp",
			context:this,
			contentType:"text/html",
			data:{
				MOChartIndex:indexNum
			},
			onload:function(cb) {
				Element.setHTML("index_buttons",cb.getResult());
			},
			onerror:null
		});
	}


	OverviewChart_class.prototype.compareChart = function(sym, name, isHistorical) {
		var enableCompare = false;
		if (document.getElementById(name)) {
			var srcReplace;
			var imgSrc = document.getElementById(name).src;
			if (imgSrc.indexOf('_off') > -1) {
				srcReplace = imgSrc.replace('_off', '_on');
				enableCompare = true;
			} else {
				srcReplace = imgSrc.replace('_on', '_off');
			}
			document.getElementById(name).src = srcReplace;
		}

		var chartSrc = this.chart.src.replace(/[?&]compares\=([^?&$]+)/gi, '').replace(/[?&]compares\=/gi, '');

		chartSrc = chartSrc.replace(/[?&]compareColors\=([^?&$]+)/gi, '').replace(/[?&]compareColors\=/gi, '');


		if (enableCompare) {
			this.currCompares[this.compares[name].symbol] = this.compares[name];
		} else {
			this.currCompares[this.compares[name].symbol] = false;
		}

		var tempArr = [];
		var colorArr = [];
		for (var i in this.currCompares) {
			if (this.currCompares[i]) {
				tempArr.push(i);
				colorArr.push(this.currCompares[i].color);
			}
		}


		chartSrc += '&compares=' + escape(tempArr.join('|'));
		chartSrc += '&compareColors=' + escape(colorArr.join('|'));

		//window.open(chartSrc);

		this.chart.src = chartSrc;
	}

	OverviewChart = new OverviewChart_class();





	function MarketsOverviewExchangeTables_class() {
		this.RankingExch = "nasdaq";
		this.RankingType = "active";
		this.RankingPenny = true;
	}


	MarketsOverviewExchangeTables_class.prototype.privateVar = function(name,val) {
		if (val !== undefined) {
			this[name] = val;
		}
		return this[name] || false;
	}
		
	MarketsOverviewExchangeTables_class.prototype.switchExchange = function(meter,useCaching) {
		// updates entire tab

		if (!meter) { meter = this.RankingExch; }
		//var chartWidth = Element.getSize("MarketDiariesLeftCol").width
		Element.removeClass(Element.get("tab_"+this.privateVar("RankingExch")),"current");
		Element.addClass(Element.get("tab_"+meter),"current");
		Element.get("a_"+meter).blur();
		this.privateVar("RankingExch",meter);
		this.privateVar("RankingPenny",0)

		useCaching = useCaching || false;

		Common.contentBufferAbortRequests();
		Common.loadContentBuffer({
			page:"exchangeBuffer.asp",
			context:this,
			contentType:"text/html",
			data:{
				meter:this.privateVar("RankingExch"),
				type:this.privateVar("RankingType"),
				useCaching:useCaching
			},
			onload:function(cb) {
				Element.setHTML("exchangebuffer",cb.getResult());
			},
			onerror:null
		});

	}

	MarketsOverviewExchangeTables_class.prototype.switchRankings = function(type) {
		// only updates rankings cell
		this.privateVar("RankingType",type);

		Common.contentBufferAbortRequests();
		Common.loadContentBuffer({
			page:"rankingsBuffer.asp",
			context:this,
			contentType:"text/html",
			data:{
				meter:this.privateVar("RankingExch"),
				type:this.privateVar("RankingType"),
				whatToChange:"rankingsbuffer",
				penny:this.privateVar("RankingPenny")
			},
			onload:function() {
				var data = DataFunctions.deserialize(arguments[0].contentPackage.data.data);
				Element.setHTML(data.whatToChange,arguments[0].getResult());
			},
			onerror:null
		});

		//loadContent("rankingsBuffer.asp?meter="+RankingExch+"&type="+RankingType,"rankingsbuffer", false);
	}
	
	MarketsOverviewExchangeTables_class.prototype.togglePenny = function(obj) {
		var value = 0;
		if (obj.checked == true) { value = 1; }
		this.privateVar("RankingPenny",value);

		this.switchRankings();
	}

	MarketsOverviewExchangeTables = new MarketsOverviewExchangeTables_class();



// Upgrading from Events.2 to Events.3 removed certain methods.  These pointers are for backwards compatibility
if (Events.cancelEvent == undefined) {
	Events.cancelEvent = Events.cancel;
}

if (Events.removeEvent == undefined) {
	Events.removeEvent = Events.remove;
}



	

// IE 6 Background Image Flicker fix
try {
  document.execCommand("BackgroundImageCache", false, true);

} catch(err) {}




/* -- Loaded:/tdameritrade/common/scripts/common.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


var estHelp = false;
function helpObj(section, page){

	this.section = section;
	this.page = page;
	this.initialized = false;

	this.init = function(){

		this.initElements();

		this.initialized = true;

	}

	this.initElements = function(resize){

		// create all the divs necessary for this page's help bubbles.

		var i,e,d,d_nw,d_n,d_ne,d_w,d_e,d_sw,d_s,d_se,sO_w,sO_h,sI_w,sI_h,pad;

		if (typeof(helpData) == "undefined"){ return false; }

		for (var x=0; x < helpData.length; x++){
			d = helpData[x];
			if (document.getElementById(d.divId)!=null) {
				pad = !(typeof(d.noPad) != "undefined");

				if (d.position == "div"){

					// position based on page div location.

					var divPos = document.getElementById(d.divId);
					var divPosAbs = getAbsolutePos(divPos);

					d.x = Math.max(0, divPosAbs.x - ((pad)?10:0)); // pad opening a bit.
					d.y = Math.max(0, divPosAbs.y - ((pad)?10:0)) ;
					d.onscreen = divPosAbs.onscreen;

					if (!this.initialized || d.stretch){
						d.iW = (d.iW && !resize)? d.iW: getElementSize(divPos).width + ((pad)?20:0);
						d.iH = (d.iH && !resize)? d.iH: getElementSize(divPos).height + ((pad)?20:0);
						d.oW = (d.oW && (!resize || /left|right/.test(d.alignOuter)))? d.oW: d.iW;
						d.oH = (d.oH && (!resize || /top|bottom/.test(d.alignOuter)))? d.oH: d.iH - 7;
					}

				} else {

					// otherwise get explicit position info in help data.

				}

				d.alignOuter = (/top|bottom|left|right/.test(d.alignOuter))?d.alignOuter:"bottom";
				d.iW = (d.iW && d.iW > 30)?d.iW:30;
				d.iH = (d.iH && d.iH > 30)?d.iH:30;

				if (!helpData[x].elem){
					helpData[x].elem = {}
				}

				i = helpData[x].elem;

				sO_w = d.oW - 16;	sO_h = d.oH - 9;
				sI_w = d.iW - 24;	sI_h = d.iH - 24;

				// outer table

				if (!i.divOuter){

					// create div as necessary

					i.divOuter = document.body.appendChild(document.createElement("DIV"));
					i.divOuter.id = "divOuter_"  + x;
					i.divOuter.style.position = "absolute";
					i.divOuter.style.visibility = "hidden";
					i.divOuter.style.zIndex = 1500;

					d_nw = "oNW";	d_n = "oN"; 	d_ne = "oNE";	d_w = "oW";
					d_e = "oE"; 	d_sw = "oSW";	d_s = "oS"; 	d_se = "oSE";

					if (d.alignOuter == "bottom"){
						d_nw = "oW"; d_n = "oNull"; d_ne = "oE";
					} else if (d.alignOuter == "top"){
						d_sw = "oW"; d_s = "oNull"; d_se = "oE";
					} else if (d.alignOuter == "right"){
						d_nw = "oN"; d_w = "oNull"; d_sw = "oS";
					} else if (d.alignOuter == "left"){
						d_ne = "oN"; d_e = "oNull"; d_se = "oS";
					}

					var html = [];
					html.push('<table border="0" cellpadding="0" cellspacing="0" id="oDimT_'+x+'">');
					html.push('	<tr>');
					html.push('		<td class="'+d_nw+'"></td>');
					html.push('		<td class="'+d_n+'"><img src="/gif/x.gif" width="1" height="1" alt="" id="oWidth_'+x+'"></td>');
					html.push('		<td class="'+d_ne+'"></td>');
					html.push('	</tr>');
					html.push('	<tr>');
					html.push('	<td class="'+d_w+'"><img src="/gif/x.gif" width="1" height="1" alt="" id="oHeight_'+x+'"></td>');
					html.push('		<td id="oContent_'+x+'" class="oContent" align="center">'+d.text+'</td>');
					html.push('		<td class="'+d_e+'"></td>');
					html.push('	</tr>');
					html.push('	<tr>');
					html.push('		<td class="'+d_sw+'"></td>');
					html.push('		<td class="'+d_s+'"></td>');
					html.push('		<td class="'+d_se+'"></td>');
					html.push('	</tr>');
					html.push('</table>');

					i.divOuter.innerHTML = html.join("");

					i.oHeight = document.getElementById("oHeight_" +  x);
					i.oWidth = document.getElementById("oWidth_" +  x);
					i.oDimT = document.getElementById("oDimT_" +  x);

				}

				// inner table

				if (!i.divInner){

					// create div as necessary

					i.divInner = document.body.appendChild(document.createElement("DIV"));
					i.divInner.id = "divInner_"  + x;
					i.divInner.style.position = "absolute";
					i.divInner.style.visibility = "hidden";
					i.divInner.style.zIndex = 1500;

					d_nw = "iNW";	d_n = "iN";		d_ne = "iNE";	d_w = "iW";
					d_e = "iE"; 	d_sw = "iSW";	d_s = "iS"; 	d_se = "iSE";

					if (d.alignOuter == "top"){
						d_nw += "-N"; d_n += "-N"; d_ne += "-N";
					} else if (d.alignOuter == "bottom"){
						d_sw += "-S"; d_s += "-S"; d_se += "-S";
					} else if (d.alignOuter == "left"){
						d_nw += "-W"; d_w += "-W"; d_sw += "-W";
					} else if (d.alignOuter == "right"){
						d_ne += "-E"; d_e += "-E"; d_se += "-E";
					}


					var html = [];
					html.push('<table border="0" cellpadding="1" cellspacing="0">');
					html.push('	<tr>');
					html.push('		<td class="'+d_nw+'"></td>');
					html.push('		<td class="'+d_n+'"></td>');
					html.push('		<td class="'+d_ne+'"></td>');
					html.push('	</tr>');
					html.push('	<tr>');
					html.push('		<td class="'+d_w+'"></td>');
					html.push('		<td style="visibility:hidden" id="iContent_'+x+'"></td>');
					html.push('		<td class="'+d_e+'"></td>');
					html.push('	</tr>');
					html.push('	<tr>');
					html.push('		<td class="'+d_sw+'"></td>');
					html.push('		<td class="'+d_s+'"></td>');
					html.push('		<td class="'+d_se+'"></td>');
					html.push('	</tr>');
					html.push('</table>');

					i.divInner.innerHTML = html.join("")

					i.iContent = document.getElementById("iContent_" +  x);

				}

				// adjust height and width shims.

				i.oHeight.style.height = Math.max(sO_h, 14) + "px";
				i.oWidth.style.width = sO_w + "px";
				i.oDimT.style.width = d.oW + "px";
				i.iContent.style.height = sI_h + "px";
				i.iContent.style.width = sI_w + "px";

				// position inner div, use normal coords

				i.divInner.style.left = d.x + "px";
				i.divInner.style.top = d.y + "px";

				// position outer div, based on alignOuter setting.

				if (d.alignOuter == "left"){

					i.divOuter.style.left = (d.x - d.oW) + "px";
					i.divOuter.style.top = d.y + "px";

				} else if (d.alignOuter == "top"){

					i.divOuter.style.left = d.x + "px";
					i.divOuter.style.top = (d.y - d.oH - 5) + "px";

				} else if (d.alignOuter == "right"){

					i.divOuter.style.left = d.iW + d.x + "px";
					i.divOuter.style.top = d.y + "px";

				} else if (d.alignOuter == "bottom"){

					i.divOuter.style.left = d.x + "px";
					i.divOuter.style.top = (d.y + d.iH) + "px";

				}
			}
		}
	}

	this.showElements = function(){

		for (var x=0; x < helpData.length; x++){
			d = helpData[x];

			// check if specific to 1 div area.
			// added isNaN and ! checks to verify element is on screen
			if (d.divArea && (document.getElementById(d.divArea).style.display == 'none' || !d.x || !d.y || isNaN(d.x) || !d.onscreen)) {
				continue;
			}
			if (document.getElementById(d.divId)!=null) {
				i = helpData[x].elem;
				i.divInner.style.visibility = "visible";
				i.divOuter.style.visibility = "visible";
			}
		}
	}

	this.hideElements = function(){

		for (var x=0; x < helpData.length; x++){
			d = helpData[x];
			if (document.getElementById(d.divId)!=null) {
				i = helpData[x].elem;
				i.divInner.style.visibility = "hidden";
				i.divOuter.style.visibility = "hidden";
			}
		}
	}
}


var help = new helpObj();


// --------------------------------------------------------------------------------------------


function resizeHelp(){

	if (help && help.initialized){
		help.initElements("resize");
	}

}

function showHelp(){

	if (typeof(help) != "undefined"){

		if (!help.initialized){
			help.init();
		}
		else {
			help.initElements("resize"); // recalculate values always
		}

		help.showElements();
		updateHelpButton("off");

	}

	return false;

}

function hideHelp(){

	if (help && help.initialized){

		help.hideElements();
		updateHelpButton("on");

	}

}

function initHelp(){

	// don't init actual divs yet
	gShowChartHelp = false;
	
	if ((window.helpData && helpData.length > 0) || gShowChartHelp){
		
		updateHelpButton("on", gShowChartHelp);
		
		var el = Element.get("timestampBar");
		var anchors = Element.parseSelector("a", el);
			
		if(anchors.length == 1) {
			Element.setDisplay("pageHelpLinkSpacer", "none");
		}
	}
	else {
		try {
			Element.setDisplay("pageHelpLink","none");
			Element.setDisplay("pageHelpLinkSpacer", "none");
		}
		catch(e) {}
	}
}

function updateHelpButton(onOff, chartHelp){

	if (document.getElementById("pageHelpLink")) {
		var pH = document.getElementById("pageHelpLink")

		if (onOff == "on") {

			Element.removeClass(pH,"off");
			//pH.innerHTML = '&nbsp;<span class="color smaller"><img src="/tdameritrade/images/icn_help.gif" align="absmiddle">&nbsp;<u>' + pageHelpText + '</u></span>&nbsp;&nbsp;';
			if (chartHelp) {
				pH.onclick = showChartHelp;
			} else {
				pH.onclick = showHelp;
			}
			estHelp = false;
		} else {
			Element.addClass(pH,"off");
			//pH.innerHTML = '&nbsp;<span class="color smaller"><img src="/tdameritrade/images/help/iOff.gif" align="absmiddle">&nbsp;<u>' + pageHelpText + '</u></span>&nbsp;&nbsp;';
			pH.onclick = hideHelp;
			estHelp = true;
		}
	}
}


/* -- Loaded:/tdameritrade/common/scripts/help.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


/*
function switchCategory(which) {
	location.href = 'story.asp?newsType=online&searchCategory=' + which;
}
function loadImage(imgKey) {
	window.open('image.asp?imgKey=' + imgKey, 'image', 'menubars=no,toolbars=no,statusbar=no,resizable=yes,scrollbars=auto');
}




*/



function switchStocksNewsCategory(c) {
	if (c == "SearchResults") {
		location.reload();
	} else {
		location.href = 'news.asp?searchCategory=' + c;
	}
}




function NewsHeadlines() {

	Events.add({element:window,type:"load",handler:this.init,context:this});

	this.numberOfPages = 0;
	this.currentPage = 0;

}

NewsHeadlines.prototype.init = function() {
	//alert("SF")


	var newsHeadlineTypesContainer = Element.get("newsHeadlineTypesContainer")
	if (newsHeadlineTypesContainer) {
		var headlineTypeRadios = Element.parseSelector("input[name='headlineType']",newsHeadlineTypesContainer);
		for (var i=0; i<headlineTypeRadios.length; i++) {
			Events.add({element:headlineTypeRadios[i],type:'click',handler:this.changeHeadlineType,context:this});
		}
	}


	return;
	// old paging

	var newsPageControls = Element.get("newsPageControls");
	if (newsPageControls) {
		this.pagingLinks = Element.parseSelector("a",newsPageControls);
		for (var i=0; i<this.pagingLinks.length; i++) {
			Events.add({element:this.pagingLinks[i],type:'click',handler:this.navigatePage,context:this});
		}

	}

	this.pageContainers = Element.parseSelector("div[id*='headlinePage']");
	this.numberOfPages = this.pageContainers.length;

	this.updateNavigation()

}

NewsHeadlines.prototype.changeHeadlineType = function(e,el,data) {
	var loc = location.href;
	var headlineType = el.value;
	loc = loc.replace(/[?|&]headlineType=[^?&]+/,""); // remove headlineType parameter
	loc = loc.replace(/#.*/,""); // remove hash
	loc += (/\?/.test(loc)?'&':'?') + "headlineType=" + headlineType;
	location.href = loc;
}


NewsHeadlines.prototype.navigatePage = function(e,el,data) {

	Events.cancel(e);
	Element.addClass('headlinePage'+this.currentPage,"none");
	this.currentPage = /next/.test(el.id) ? this.currentPage+1 : this.currentPage-1;
	Element.removeClass('headlinePage'+this.currentPage,"none");

	this.updateNavigation()

	location.hash = "top"


}


NewsHeadlines.prototype.updateNavigation = function(e,el,data) {
	
	if (!this.pagingLinks) { return; }

	Element.switchClass(this.pagingLinks[0],"none",this.currentPage <= 0); // Previous
	Element.switchClass(this.pagingLinks[1],"none",this.currentPage >= this.numberOfPages-1) // next

}


function toggleSource(e,el) {
	if (el.id == "checkboxall") {

		var checked = el.checked;

		var checkboxes = Element.parseSelector('input[type="checkbox"]',"searchProvider");
		var images = Element.parseSelector('img',"searchProvider");

		Element.setProperty(checkboxes,"checked",checked);
		for (var i = 0; i <images.length; i++) {
			images[i].src = images[i].src.replace(/(_off)?\.gif/i, checked?'.gif':'_off.gif')

		}
		
	}
	else {

		var parentSpan = Element.getParent(el,"span");

		var checkbox = Element.parseSelector('input',parentSpan,"first");
		var image = Element.parseSelector('img',parentSpan,"first");

		var checked = checkbox.checked;

		if (el.tagName.match(/img/i)) {
			checked = checkbox.checked = !checkbox.checked;
		}

		image.src = image.src.replace(/(_off)?\.gif/i, checked?'.gif':'_off.gif')

	}
}

function submitParentForm(el) {
	Element.getParent(el,"form").submit();

}

/* -- Loaded:/tdameritrade/common/scripts/news.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


Chart = function(args) {
	this.params = {};
	this.preferences = {};
}

Chart.prototype.setCache = function(cache) {
	this.cache = cache;
}

Chart.prototype.setName = function(name) {
	this.chartName = name;
}

Chart.prototype.setType = function(type) {
	this.chartType = type;
}

Chart.prototype.linkToInteractive = function() {
	this.linkToInteractive = true;
}

Chart.prototype.setBinaryWrite = function(bw) {
	this.binaryWrite = bw;
}

Chart.prototype.setDuration = function(duration) {
	this.params.duration = duration;
}

Chart.prototype.setSymbol = function(symbol) {
	this.params.symbol = symbol;
}

/* Chart.prototype.setImage = function(id) {
	this.image = Element.get(id);
	this.setImageContainer(Element.getParent(this.image, "div"));
} */

Chart.prototype.setImageContainer = function(container) {
	if ("string" == typeof container) {
		this.imageContainer = Element.get(container);
	} else {
		this.imageContainer = container;
	}
	
	this.setWidth();
}

Chart.prototype.setWidth = function() {
	if (!this.imageContainer) { return; }
	
	this.params.width = Element.getSize(this.imageContainer).width;
}

Chart.prototype.setWidthResize = function() {
	if (this.chartImage) {
		Element.setWidth(this.chartImage.image, 1);
		this.setWidth();
		Element.setStyle(this.chartImage.image, "width: 100%;");
	}
}

Chart.prototype.addComparison = function(symbol, color) {
	this.params.comparisons = this.params.comparisons || [];
	this.params.comparisons.push({
		 symbol: symbol
		,params: {
			color: color
		}
	});
}

Chart.prototype.removeComparison = function(symbol, color) {
	this.params.comparisons = this.params.comparisons || [];
	
	for (var i = 0; i < this.params.comparisons.length; i++) {
		if (symbol == this.params.comparisons[i].symbol && color == this.params.comparisons[i].params.color) {
			this.params.comparisons.splice(i, 1);
			break;
		}
	}
}

Chart.prototype.addIndicator = function(name, color) {
	this.params.indicators = this.params.indicators || [];

	var map = CopyObj(this.indicatorMap[name.toUpperCase()]);
	
	var indicator = {
		 type: map.type
		,uid: map.uid
		,params: {
			color: color
		}
	}
	
	for (var i in map.params) {
		indicator.params[i] = map.params[i];
	}
	
	this.params.indicators.push(indicator);
}

Chart.prototype.removeIndicator = function(name, color) {
	this.params.indicators = this.params.indicators || [];
	
	for (var i = 0; i < this.params.indicators.length; i++) {
		if (name.toUpperCase() == this.params.indicators[i].uid && color == this.params.indicators[i].params.color) {
			this.params.indicators.splice(i, 1);
			break;
		}
	}
}

Chart.prototype.setPreference = function(name, value) {
	this.preferences[name] = value;
}

Chart.prototype.initResizeBuffer = function() {
	resizeBuffer.add(function() {
		if (this.chartSizeTimer) { clearTimeout(this.chartSizeTimer); }
		this.chartSizeTimer = setTimeout(function() {
			this.setWidthResize();
			this.render();
		}.Context(this), 200);
	}.Context(this));
}

Chart.prototype.render = function() {
	this.chartImage = this.chartImage || new ChartImage();
	
	if (this.binaryWrite) {
		this.chartImage.loadBW(this);
	} else {
		this.chartImage.load(this);
	}
}

Chart.prototype.indicatorMap = {
	"SMA": {
		 type: "MA"
		,uid: "SMA"
		,params: {
			period: 9
		}
	}
}

ChartImage = function() {
	this.serializer = new Serializer();
	this.contentBuffer = new ContentBuffer();
	this.contentBuffer.debug = true;
}

ChartImage.prototype.load = function(args) {
	this.type = args.type || "interactive";
	this.callback = args.callback || null;
	this.context = args.context || window;
	this.imageContainer = args.imageContainer;
	this.linkToInteractive = args.linkToInteractive || false;

	this.showLoading();

	var cache = args.cache || 0;
	var chartName = args.chartName || "";
	var chartType = args.chartType || "";
	var returnVars = args.returnVars || "";
	var params = (args.params) ? this.serializer.serialize(args.params) : "";
	var preferences = (args.preferences) ? this.serializer.serialize(args.preferences) : "";

	if (this.contentBuffer) { this.contentBuffer.abortRequests(); }
	
	var connection = this.contentBuffer.load({
		url: buildAbsolutePath("/common/charts/buildChart.asp"),
		method: "post",
		contentType: "text/javascript",
		preventEval: true,
		data: {
			 chartName: chartName
			,chartType: chartType
			,returnVars: returnVars
			,params: params
			,preferences: preferences
			,cache: cache
		},
		context: this,
		onload: this.showImage
	});

	return connection;
}

ChartImage.prototype.loadBW = function(args) {
	this.fileName = queryString = "?params=" + this.serializer.serialize(args.params);
	this.fileName += "&chartName=" + args.chartName;
	this.fileName += "&binaryWrite=true";	
		
	var img = document.createElement("img");
	Events.add({element: img, type: "load", context: this, handler: this.finishLoadBW, data: {container: args.imageContainer}});
	img.src = buildAbsolutePath("/common/charts/buildChart.asp"+this.fileName);
}

ChartImage.prototype.showImage = function(data) {
	var data = DataFunctions.deserialize(data.getResult());
	this.fileName = data.fileName;
	
	var img = document.createElement('img');
	Events.add({element: img, type: "load", context: this, handler: this.finishLoad});
	img.src = this.fileName;
}

ChartImage.prototype.finishLoadBW = function(e, el, data) {
	Element.create("img", {src:buildAbsolutePath("/common/charts/buildChart.asp"+this.fileName)}, null, data.container);
}

ChartImage.prototype.finishLoad = function() {
	if (this.image) {
		this.image.src = this.fileName;
	} else {
		var parent = this.imageContainer;
		if (this.linkToInteractive) {
			var link = Element.create("a", {"href":buildAbsolutePath("/stocks/charts/charts.asp")}, null, parent);
			parent = link;
		}
		this.image = Element.create("img", {"src":this.fileName}, null, parent);
	}

	if (this.callback) { this.callback.apply(this.context); }
	
	this.hideLoading();
}

ChartImage.prototype.showLoading = function() {
	if (!this.loading) {
		this.loading = Element.create("div", {"class":"loading hide", "style":"display: block;"} , [
			Element.create("div", {"class":"loadingContainer"}, [
				Element.create("div", {"class":"loadingBackground"})
				,this.loadingContent = Element.create("div", {"class":"loadingContent"}, [
					Element.create("div", {"class":"loadingText"}, "Loading...")
				])
			])
		], this.imageContainer);	
	}

	var chartSize = Element.getSize(this.imageContainer);
	var loadingDivSize = Element.getSize(this.loadingContent);
	
	Element.setSize(this.loading, chartSize.width, chartSize.height);
	Element.setXY(this.loadingContent, (chartSize.width/2) - (loadingDivSize.width/2), (chartSize.height/2) - (loadingDivSize.height/2));
	
	Element.removeClass(this.loading, "hide");	
}

ChartImage.prototype.hideLoading = function() {
	Element.addClass(this.loading, "hide");
}

/* -- Loaded:/tdameritrade/common/scripts/Chart.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */



Table_class = function(args) {
	
	this.props = args;

	this.name = args.name || "displayonly";
	this._data = args.data || null;
	this._sort = args.sort || null;
	this.noSortLinks = args.noSortLinks || false;	
	this.noHeading = args.noHeading || false;	
	this._headingGroups = args.headingGroups || [];	
	this._headings = args.headings || [];
	this._sortasc = !!args.sortasc; // (!! converts to bool representation)
	this.customSort = args.customSort || null;
	this.onDrawComplete = args.onDrawComplete || null;
	this._sortListener = null;
	this.table = Element.get("table-"+this.name);
	this.theads = Element.parseSelector("thead.sortable",this.table);
	if (this.theads.length) {
		this.thead = this.theads[0];
	}

	this.tbodies = Element.parseSelector("tbody",this.table);
	if (this.tbodies.length) {
		this.tbody = this.tbodies[0];
	}

	//recurseObject({o:this._data,n:"this._data",buffer:0,text:0,level:500,inline:0,nowrite:0});

}

Table_class.prototype.getSortLinks = function() {
	if (!this._sortLinks) {
		this._sortLinks = Element.parseSelector("a",this.thead);
	}

	return this._sortLinks;
}


Table_class.prototype.data = function(arg) {
	if (arg !== undefined) {
		this._data = arg;
	}
	return this._data;
}

Table_class.prototype.headings = function(arg) {
	if (arg !== undefined) {
		this._headings = arg;
	}
	return this._headings;
}

Table_class.prototype.headingGroups = function(arg) {
	if (arg !== undefined) {
		this._headingGroups = arg;
	}
	return this._headingGroups;
}

Table_class.prototype.fireDrawComplete = function(){
	
	if( this.onDrawComplete ){

		eval( this.onDrawComplete )();
		
	};
	
};


Table_class.prototype.sort = function(arg,firstsort) {
	if (arg !== undefined) {

		if (this._sort == arg) {
			this._sortasc = !this._sortasc;
		}
		else if (firstsort) {
			this._sortasc = /asc/.test(firstsort) ? true : false;
		}

		this._sort = arg;
		// remove sorting from all links
		Element.removeClass(this.getSortLinks(),"sort(?:asc|dsc)");
		// add sorting
		Element.addClass(this.name+"-sort-"+this._sort,(this._sortasc?"sortasc":"sortdsc"));

		if (this.customSort) {
			try {
				eval(this.customSort+"({sort:'"+this._sort+"',sortasc:"+this._sortasc+"})");
			}
			catch(e) { }
			return;
		}
		this.drawBody();
	}
	
	return {sort:this._sort,sortasc:this._sortasc};
}


Table_class.prototype.drawBody = function() {

	if (!this.tbody) {
		this.tbody = Element.create("tbody",{},null,this.table);
	}

	var headings = this.headings();
	var data = this.data();

	if (this._sort && !this.customSort) {
		data = SortByField(this.data(),this._sort,this._sortasc, true);
	}

	Element.removeChildNodes(this.tbody);

	var headings = this.headings();

	// fix so align: can simply be "left" or "right"
	for (var i=0; i < headings.length; i++) {
		if (headings[i].align) {
			headings[i].align = headings[i].align.toString().match(/left/i) ? "alignLeft" : "alignRight";
		}
	}
	
	var tr, td;
	
	var fieldValue, cellClass;
	for (var i=0; i<data.length;i++) {
 		var rowClass = data[i].highlight? "highlight" : "";
		var tr = Element.create("tr",{className:rowClass},null,this.tbody);

		for (var x=0;x<headings.length;x++) {
			fieldValue = (data[i][headings[x].field+"_format"] || (data[i][headings[x].field]!=null?data[i][headings[x].field]:""));
			cellClass = (headings[x].field == this._sort) ? "currentsymbol ":"";
			cellClass += (headings[x].align || " alignRight");
			cellClass += (x == 0 && data[i].extraIndent) ? " extraIndent" : "";

			td = Element.create("td",{className:cellClass},fieldValue,tr);
		}

	}
	this.fireDrawComplete();

}







/* Creating tables client side */

var TableCreator_class = function ( oArgs ) {

	this._name 	     = oArgs.name;
	this._parent	 = oArgs.parent;
	this._headings   = oArgs.headings;
	this._hLen		 = this._headings.length;
	this._data 	     = oArgs.data;
	this._dLen		 = this._data.length;
	this._sort		 = oArgs.sort || false;
	this._initSort   = oArgs.initSort || false;
	this._delayed	 = oArgs.RT? false : true;

	this._initSortOrder  = oArgs.initSortOrder || false; 

	if(this._initSort) {
		
		SortByField( this._data, this._initSort, this._initSortOrder, true);	
	}

	this._table;
	this._headers   = new Array();
	this._rows	    = new Array();
	this._sortData  = new Array();
	
	this.createTable();
};


TableCreator_class.prototype.loopHeadings = function ( func, args ) {
	
	for(var i = 0; i < this._hLen; i++) {
	
		func.apply(this, [i, this._headings[i], this._hLen].concat(args));
	}
};


TableCreator_class.prototype.loopData = function ( func, args ) {

	if(!this._dLen) {
		this.handleNoData();
		return;	
	}
	
	for(var i = 0; i < this._dLen; i++) {
		
		func.apply(this, [i, this._data[i], this._dLen].concat(args));
	}
};


TableCreator_class.prototype.handleNoData = function () {

	Element.create("tbody", {}, [
		Element.create("tr", {}, [
			Element.create("td", {colSpan:this._hLen}, "We're sorry, there is currently no data available at this time.")
		])
	], this._table);	
};


TableCreator_class.prototype.createTable = function () {
	
	this._table = Element.create( "table", {
		
				 id:"table-" + this._name
				,className:"WSODTable vertical stretchy"
				,cellpadding:"0"
				,cellspacing:"0"
	});
	
	this.loopHeadings( this.addCols );
	this.loopHeadings( this.addHeader );
	this.loopData( this.addBody );
};


TableCreator_class.prototype.addCols = function () {

	Element.create("col", {}, null, this._table);	
};


TableCreator_class.prototype.addHeader = function ( i, data, total ) {
	
	if( !this._headerElement ) {
		
		var head 		    = Element.create( "thead", {}, [], this._table );
		this._headerElement = Element.create( "tr", {}, null, head );
	};
	
	var klass = this.makeCamelClass( data.align || "left", "align" );
	var th    = Element.create( "th", {className:"alignBotton " + klass }, [], this._headerElement);
	var field;
	var a;
			 
	if( this._sort && data.sort ) {

		a = Element.create( "a", {href:"javascript:void(0);", field:data.field}, data.label, th );
		this._headers.push( a );
	} 
	else {
		Element.setHTML( th, data.label == "clientBuySell" || data.label == "delayed" || data.label == "morelink"? "&nbsp;" : data.label );	
	}
};


TableCreator_class.prototype.addBody = function ( i, data, total ) {
	
	if(!this._tableBody)
		
		this._tableBody = Element.create( "tbody", {}, null, this._table);
		
	
	
	var tr = Element.create( "tr", {}, null, this._tableBody );
	
	this._rows.push( tr );
	this.loopHeadings( this.addCells, [ data, tr ] );
	
	
	var _data = data;
		_data.element = tr;
		
	this._sortData.push( _data );
};


TableCreator_class.prototype.addCells = function ( i, headingData, total, cellData, parent ) {
	
	var klass = this.makeCamelClass( headingData.align || "left", "align" );
	var field = cellData[ headingData.field + "_format" ] || cellData[ headingData.field ];
	var field_raw = cellData[ headingData.field ];
	
	
	if(headingData.format && field) {

		field = WSDOM.Format[headingData.format.method](field,headingData.format.format, headingData.format.color);	
		
	} else if(headingData.label) {
		
		switch(headingData.label) {
			
			case "delayed":	
				field = this._delayed? Element.create("span", {className:"iconBackground iconDelayed"}, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;") : "&nbsp;";
				break;
				
			case "clientBuySell":
				
				field = [
					 Element.create("a", {className:"normal", target:"vendorLinks", href:gSessionSeedDomain+"/cgi-bin/apps/u/ThirdPartyUrlLauncher/new?target=buyBttn&param="+field_raw}, "Buy")
					,'&nbsp;'
					,Element.create("a", {className:"normal", target:"vendorLinks", href:gSessionSeedDomain+"/cgi-bin/apps/u/ThirdPartyUrlLauncher/new?target=sellBttn&param="+field_raw}, "Sell")
				];
				break;
				
			case "morelink":
				var aTag;
				field = Element.create("div", {className:"mi"} ,
					[
						aTag = Element.create("a", {
							href:"javascript:void(0)", 
							id:"morelink_"+cellData.Symbol, 
							className:"normal", 
							onmouseover:"showMoreTitle(this);"							
						}, [
						Element.create("div", {id:"more_" + cellData.Symbol,  className:"moreicon"})
					])
				]);
				
				aTag.onclick = function() {
	                generateResearchMore(cellData.Symbol, cellData.Symbol, cellData.CompanyName, cellData.Exchange, '', '');
					return false;
                }

				
				break;
				
			default:
				field = field;
		}
	}
	
	if(headingData.creator) {
		
		var vals = window[headingData.creator.context][headingData.creator.method]( cellData[headingData.field] );
		
		field = vals.format;
		cellData[headingData.field] = vals.raw;
		
	}
	
	if(headingData.classname) {
		klass += " " + headingData.classname;	
	}
	
	Element.create( "td", {className:klass}, field, parent );
};


TableCreator_class.prototype.makeCamelClass = function( elem, prepend ) {
	
	prepend = prepend || "";
	
	var klass = elem.slice(0,1).toUpperCase() + elem.slice(1);
		klass = prepend + klass;
		
	return klass;
};


TableCreator_class.prototype.bindSortableEvents = function () {
	
	Events.add({
		 element:this._headers
		,type:'click'
		,handler:this.sortTable
		,context:this
	});
};


TableCreator_class.prototype.sortTable = function ( ev, el ) {
	
	el.blur();
	
	Element.removeClass( this._headers, "current" );
	Element.addClass( el, "current" );
	
	Element.removeClass( this._headers, 'dsc' );
	Element.removeClass( this._headers, 'asc' );
	Element.addClass( el, this._initSort? 'asc':'dsc');
	
	var field = el.getAttribute("field");
	
	this._sortData  = SortByField( this._sortData, field, this._initSort, true );
	
	this._initSort = !this._initSort;
	
	var i   = 0,
		len = this._sortData.length;
		
	for(; i < len; i++) {
		
		Element.addChild( this._tableBody, this._sortData[i].element );	
	}
};


TableCreator_class.prototype.draw = function () {
	
	if( this._sort ) {
		this.bindSortableEvents();
	}
	
	Element.addChild( this._parent, this._table );
	
	return this._table;
};

/* -- Loaded:/tdameritrade/common/scripts/Table.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


var WSODPopup = function(type, bNoButtons, tabNum, from) {
	
	if(Common.popups[type]) {
		return null;
	}
		
	
	var blocker = Element.get("WSODPopupBlocker");
	
	if(!blocker) {
		Element.create("div", {id:"WSODPopupBlocker"}, null, "siteContainerPadding");	
	}
	
	this.showButtons = !bNoButtons;	
	this.tab = tabNum || 0;
	this.content = this.popupContentMap[type];

	if(from == "StocksOverview"){
		this.content.html = this.content.html.replace('<li><a href="javascript:void(0);" item="updowns">Upgrades &amp; Downgrades</a></li>', '');
	}
	this.init(type);
}

WSODPopup.prototype.popupContentMap = {
	"ResearchTeam":{
		
		html: '<div id="TabNav" class="hasLayout rtNav TabNav">'
			+'<ul>'
			+'<li><a href="javascript:void(0);" item="whatsthis">What\'s This?</a></li>'
			+'<li><a href="javascript:void(0);" item="methodology">Methodology</a></li>'
			+'<li><a href="javascript:void(0);" item="updowns">Upgrades &amp; Downgrades</a></li>'
			+'</ul>'
			+'</div>'
			+'<br class="clear" />'
			+'<div class="none" contentid="methodology">'
			+"<p><strong>ResearchTeam reports provide you with a complete rating picture including the current ResearchTeam rating, each independent provider\'s rating, and the historical accuracy and performance of ResearchTeam ratings.</strong></p><p><img src='" + buildAbsolutePath('/images/reports/RT-Diagram.png') + "' /></p>"
			+'</div>'
			+'<div class="none" contentid="whatsthis">'
			+'<p>ResearchTeam is a unique third-party research tool that employs a \'wisdom of crowds\' approach to investment research. The concept is simple: a combination (a team) of different research providers providing company recommendations perform better than the recommendations of individual research providers alone. Performance measurement is traditionally used to find the "best" research provider. Certain providers may have poor performance, but may still add overall value if their strengths are used in combination with another research provider.</p>'
			+'<p>ResearchTeam research is a team-based approach to investment research, based on the universe of companies covered by five underlying third-party research providers-Standard & Poor\'s, Ford Equity Research, TheStreet.com, MarketEdge and Jaywalk. Rules are applied to the five providers\' recommendations to form an overall "team recommendation" for each company covered. Following the "wisdom of crowds" idea, the theory is that the team recommendation will outperform the individual provider recommendations.</p>'
			+'</div>'
			+'<div class="none" contentid="updowns">'
			+'<strong>Upgrades</strong>'
			+'<p>This list of securities represents those companies which have been upgraded by ResearchTeam in the last two weeks. For example, if ResearchTeam raised its recommendation from a HOLD rating to an ACCUMULATE rating (or a REDUCE to a HOLD rating) in the last two weeks, that company would be included in this list. The success of ResearchTeam recommendations over the last year is displayed in the Rating Accuracy column which gives the percentage of recommendations that were successful in terms of total return. The list only includes companies where the team upgraded the company, not individual team members. Reiterations of ratings and initiations of coverage are not included in this list. Multiple upgrades by the team in a two week period for one company will only result in a single entry on this list. Please see the Recent Downgrades report for a list of recently downgraded companies.</p>'
			+'<strong>Downgrades</strong>'
			+'<p>This list of securities represents those companies which have been downgraded by ResearchTeam in the last two weeks. For example, if ResearchTeam lowered its recommendation from an ACCUMULATE rating to a HOLD rating (or a HOLD to a REDUCE rating) in the last two weeks, that company would be included in this list. The success of ResearchTeam recommendations over the last year is displayed in the Rating Accuracy column which gives the percentage of recommendations that were successful in terms of total return. The list only includes companies where the team as a whole provided a downgrade - not individual team members. Reiterations of ratings and initiations of coverage are not included in this list. Multiple downgrades in a two week period for one company will only result in a single entry on this list. Please see the Recent Downgrades report for a list of recently upgraded companies.</p>'
			+'</div>',
			
		iframe: '<iframe style="top:0px;left:0px;width:100%;height:100%;zoom:1;" src="javascript:\'<html></html>\';" frameborder="0"></iframe>',
		className: "RTPopup", 
		buttons: [{ 
			label: 'Download the Report',
			className: 'fright',
			link:  '<a class="openReport" href="' + buildAbsolutePath('/common/reports/report.asp?reportName=stocks.researchteam') + '">',
			handler: Common.popReport,
			context: Common
		},{
			label: 'View the Tour',
			className: 'fright',
			link: '<a href="javascript:void(0);" onclick="javascript:window.open(\'tour/index.asp\', \'tourWindow\', \'location=1, status=1, scrollbars=1, width=1100, height=845\');" >'
		}]
		,tabs:true
	},
	"BondMutualFunds": {
		html: "<h2>Bond Mutual Funds</h2><p>Investing in Bond Mutual Funds involves substantial risk, including loss of principal and may not be suitable for all investors.</p><p>Data quoted represents past performance. Past performance is not an indication of future results and investment returns and prices for exchange-traded funds will fluctuate. Your investment may be worth more or less than your original cost at redemption. Current performance may be lower or higher than the performance data quoted.</p>" 
	},
	"BondETFs":{
		html: "<h2>Bond ETFs</h2><p>Investing in Bond ETFs involves substantial risk, including loss of principal and may not be suitable for all investors. ETFs are subject to risk similar to those of stocks including those regarding short-selling and margin account maintenance.</p><p>Data quoted represents past performance. Past performance is not an indication of future results and investment returns and prices for exchange-traded funds will fluctuate. Your investment may be worth more or less than your original cost at redemption. Current performance may be lower or higher than the performance data quoted.</p>"
	},
	"CommodityETFs":{
		html: "<h2>Commodity ETFs</h2><p>Investing in commodity ETFs involves substantial risk, including loss of principal and may not be suitable for all investors. Commodity ETFs may be affected by changes in overall market movements, commodity index volatility, changes in interest rates or factors affecting a particular industry or commodity. Commodity ETFs may subject to greater volatility than ETFs that invest in traditional securities. ETFs are subject to risk similar to those of stocks including those regarding short-selling and margin account maintenance.<br /><br />Data quoted represents past performance. Past performance is not an indication of future results and investment returns and prices for exchange-traded funds will fluctuate. Your investment may be worth more or less than your original cost at redemption. Current performance may be lower or higher than the performance data quoted."
	},
	"CurrencyETFs":{
		html:"<h2>Currency ETFs</h2><p>Investing in currency ETFs involves substantial risk, including loss of principal and may not be suitable for all investors. Currency ETFs may be affected by changes in overall market movements, changes in interest rates or currency fluctuations and political and economic instability. ETFs are subject to risk similar to those of stock including those regarding short-selling and margin account maintenance.</p><p>Data quoted represents past performance. Past performance is not an indication of future results and investment returns and prices for exchange-traded funds will fluctuate. Your investment may be worth more or less than your original cost at redemption. Current performance may be lower or higher than the performance data quoted.</p>"
	}
}

WSODPopup.prototype.init = function(type){
	this._popupContent = Element.create("div", {'class': 'content hasLayout'}, "<div class='fright closer'><a href=\"javascript:void(0);\" class='close'>x <span>Close</span></a></div><br class='clear'/>");
	Element.addChild(this._popupContent, this.content.html);

	
	this._popup = Element.create(
		"div", 
		{"id": "WSODPopup", className:"hasLayout " +  this.content.className}, 
		this._popupContent, "siteContainer"
	);
	
	if(this.content.buttons && this.showButtons){
		for (var i = 0; i < this.content.buttons.length; i++) {
			Element.addChild(		
				this._popupContent,
				this.content.buttons[i].link + 
				'<div class="btnPriorityOnInner ' + this.content.buttons[i].className + '" style="padding: 3px; width: 143px;">' +
				this.content.buttons[i].label +
				'</div></a>'
			);
		}
	}


	if(this.content.iframe){
		Element.addChild(this._popup, this.content.iframe);		
	}
	
	Common.popups[type] = true;	
}

WSODPopup.prototype.show = function(type, bNoButtons){	
	
	this.content = this.popupContentMap[type];
	this.showButtons = !bNoButtons;
	
	if (this.content.buttons && this.showButtons) {
		for (var i = 0; i < this.content.buttons.length; i++) {
			if (this.content.buttons[i].handler) {
			
				Events.add({
					element: Element.parseSelector('a.openReport', 'WSODPopup'),
					type: "click",
					handler: this.content.buttons[i].handler,
					context: this.content.buttons[i].context
				});
			}
		}
	}
	
	if(this.content.tabs) {
		
		var tabs = Element.parseSelector("li a", this._popup);
		
		if(this.tab < tabs.length) {
			Element.addClass(tabs[ this.tab ].parentNode, "current");
			
			var attr = tabs[ this.tab ].getAttribute("item");
			
			var contentToShow = Element.parseSelector("div[contentid='"+attr+"']", this._popup);
	
			Element.removeClass(contentToShow, "none");
		}
	
		Events.add({
			 element:tabs
			,type:'click'
			,handler:this.switchTab
			,context:this
			,data:tabs
		});
		
		var lis = Element.parseSelector("li", this._popup);
		Events.add( { element:lis, type:"mouseover", handler:this.mouseOverTabs, context:this, data:true } )	
		Events.add( { element:lis, type:"mouseout", handler:this.mouseOverTabs, context:this, data:false } )	
	}
	
	Events.add({
		element: Element.parseSelector("a.close", this._popup)[0],
		type: 'click',
		handler: this.close,
		context: this,
		data:type
	});
	
	var siteC = Element.get("siteContainerPadding");

	Element.setStyle("WSODPopupBlocker", "height:" + siteC.offsetHeight + "px");
	Element.removeClass("WSODPopupBlocker", "none");
	Element.addClass(this._popup, "visible");
	this.setPosition(this._popup);
}

WSODPopup.prototype.close = function(e, el, type){
	
	Common.popups[type] = null;
	Element.remove(this._popup);
	Element.addClass("WSODPopupBlocker", "none");
}

WSODPopup.prototype.setPosition = function(el){
	var port = getViewport();
	
	Element.setXY(
		el, 
		((port.width / 2) - (Element.getSize(el).width / 2) ), 
		(port.top + 130)
	);
}

WSODPopup.prototype.switchTab = function(e, el, tabs) {
	
	var i   = 0;
	var len = tabs.length;

	for(; i < len; i++) {
		
		Element.removeClass(tabs[i].parentNode, "current");
	}
		
	Element.addClass( el.parentNode, "current");
	
	var attr = el.getAttribute('item');
	var content = Element.parseSelector("div[contentid]", this._popup);
	var curcontent = Element.parseSelector("div[contentid='"+attr+"']", this._popup);
	
	
	Element.addClass(content, "none");
	Element.removeClass(curcontent, "none");	
	if(this.content.iframe){
		this.resizeIframe();
	}
}

WSODPopup.prototype.resizeIframe = function(){
	var iframe = Element.parseSelector("iframe", this._popup);
	var size = Element.getSize(this._popup);	
	Element.setSize(iframe, size.width, size.height);
}

WSODPopup.prototype.mouseOverTabs = function( e, el, over ) {
	if( Element.hasClass( el, "current" ) ) {
 		over = false;
	}

	Element.switchClass(el, "highlight", over );

};


/* -- Loaded:/tdameritrade/common/widgets/popup.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */




/* this file to be pulled in via a script tag at tdameritrade.com 
 * we should set max-age cache header to about an hour on this dir
 * 
 */

var FastLookup = function(elForm) {
	this.localCache = {};
	this.eventManager = new EventManager();
	this.query = "";
	this.issueType = "";
	
	this.setDestinationURL(this.DESTINATION_URL);
	this.setRequestURL(this.REQUEST_URL);
	this.setFinderURL(this.FINDER_URL);
	this.setStopSubmit(this.STOPSUBMIT);
	
	if (elForm || Element.get(this.DEFAULT_FORM_ID)) {
		// DOM has loaded
		this.setForm(elForm);
	}
};

FastLookup.prototype.DEFAULT_FORM_ID = "symbolSearch";
FastLookup.prototype.FORM_INPUT_SELECTOR = "input";

FastLookup.prototype.REQUEST_URL = "/tdameritrade/common/fastlookup/buffer_fastlookupresults.asp";
FastLookup.prototype.DESTINATION_URL = "";
FastLookup.prototype.FUND_DESTINATION_URL = "";
FastLookup.prototype.FINDER_URL = "";
FastLookup.prototype.KEY_PRESS_WAIT = 0;

FastLookup.prototype.CSS_HIDDEN = "fastLookupHidden";
FastLookup.prototype.CSS_SELECTED = "selected";
FastLookup.prototype.CSS_RESULTS = "fastLookup";
FastLookup.prototype.CSS_ISSUE_NAME = "issueName";
FastLookup.prototype.CSS_GROUP_END = "fastLookupGroupEnd";
FastLookup.prototype.CSS_FLAG = "wsod-flag";
FastLookup.prototype.CSS_FLAG_COUNTRY = "flag-";
FastLookup.prototype.CSS_MORE_LINK = "more";

FastLookup.prototype.ATTR_NO_RESULTS = "noresults";

FastLookup.prototype.KEY_CODE_UP = 38;
FastLookup.prototype.KEY_CODE_DOWN = 40;
FastLookup.prototype.KEY_CODE_ESC = 27;
FastLookup.prototype.KEY_CODE_ENTER = 13;

FastLookup.prototype.invalidChars = /\s/g;
FastLookup.prototype.countryPrefix = /^[a-z]{2}\:/i;

FastLookup.prototype.STOPSUBMIT = false;
FastLookup.prototype.setStopSubmit = function (stopSubmit) {
	this.stopSubmit = stopSubmit;
};

FastLookup.prototype.setForm = function(elForm) {
	this.clearInputEventHandlers();
	
	this.elForm = Element.get(elForm) || Element.get(this.DEFAULT_FORM_ID);
	if (!this.elForm) {
		return;
	}
	this.elInput = Element.parseSelector(this.FORM_INPUT_SELECTOR, this.elForm, "first");
	if (!this.elInput) {
		return;
	}
	
	this.addInputEventHandlers();
};

FastLookup.prototype.addInputEventHandlers = function() {
	this.eventManager.add(this.elInput, "keyup", this.search, this, null, this.KEY_PRESS_WAIT);
	this.eventManager.add(this.elInput, "click", function(e) {
		e.cancel();
	});
};

FastLookup.prototype.clearInputEventHandlers = function() {
	if (this.elInput) {
		this.eventManager.remove(this.elInput);
	}
};

FastLookup.prototype.addResultEvents = function(noResults) {
	this.selectedRow = -1;
	
	if (!noResults) {
		this.getOnNavResults().addElement(this.elInput);
		this.getOnHoverResults().addElement(this.elResultRows);
		this.getOnClickResults().addElement(this.elResultRows);
	}
	
	this.getOnHideResults().addElement(document);
	this.getOnSubmitResults().addElement(this.elInput);
	this.getOnChangeInput(true).addElement(this.elInput);
};

FastLookup.prototype.removeResultEvents = function() {	
	this.getOnNavResults().removeAllElements();
	this.getOnHoverResults().removeAllElements();
	this.getOnClickResults().removeAllElements();
	this.getOnHideResults().removeAllElements();
	this.getOnSubmitResults().removeAllElements();
	this.getOnChangeInput(true).removeAllElements();
};

FastLookup.prototype.getOnChangeInput = function(cancelNative) {
	var eventSourceCancel = this.eventManager.add(null, "change", this.delayChangeEvent, this, true);
	var eventSourcePassThrough = this.eventManager.add(null, "change", this.delayChangeEvent, this);
	
	this.getOnChangeInput = function(cancelNative) {
		if (cancelNative) {
			return eventSourceCancel;
		}
		return eventSourcePassThrough;
	};
	
	return this.getOnChangeInput(cancelNative);
};

FastLookup.prototype.delayChangeEvent = function(e, el, cancelNative) {
	console.log("Delay Change")
	if (cancelNative) {
		console.log("Cancelling")
		e.cancel();
	}
};

FastLookup.prototype.getOnNavResults = function() {
	var eventSource = this.eventManager.add(null, "keydown", this.navigate, this);
	this.getOnNavResults = function() {
		return eventSource;
	};
	
	return this.getOnNavResults();
};

FastLookup.prototype.getOnHoverResults = function() {
	var eventHandler = function(e, el) {
		this.highlightRow(el.rowIndex);

	};
	var eventSource = this.eventManager.add(null, "mouseover", eventHandler, this);
	this.getOnMouseOverResults = function() {
		return eventSource;
	};
	
	return this.getOnMouseOverResults();
};
FastLookup.prototype.getOnHideResults = function() {
	var eventSource = this.eventManager.add(null, "click", this.clearResults, this);

	this.getOnHideResults = function() {
		return eventSource;
	};
	
	return this.getOnHideResults();
};
FastLookup.prototype.getOnClickResults = function() {
	var eventSource = this.eventManager.add(null, "click", this.selectResult, this);
	this.getOnClickResults = function() {
		return eventSource;
	};
	
	return this.getOnClickResults();
};
FastLookup.prototype.getOnSubmitResults = function() {
	var eventSource = this.eventManager.add(null, "keypress", this.selectResult, this);
	this.getOnSubmitResults = function() {
		return eventSource;
	};
	
	return this.getOnSubmitResults();
};
FastLookup.prototype.setRequestor = function(requestor) {
	this.requestor = requestor;
};
FastLookup.prototype.setDestinationURL = function(URL) {
	this.destinationURL = URL;
};

FastLookup.prototype.setCallbackMethod = function(method) {
	this.callbackMethod = method;
};

FastLookup.prototype.setRequestURL = function(URL) {
	this.requestURL = URL;
};
FastLookup.prototype.setFinderURL = function(URL) {
	this.finderURL = URL;
};

FastLookup.prototype.highlightText = function(c) {
	var s = String(this.query).replace(this.countryPrefix, "").split(" ");
	var replacement = "<b>$1</b>";
	for (var i=0; i<s.length; i++) {
		s[i] = s[i].replace(/\s/g, "");
		
		if (!s[i].length) {
			continue;
		}
		var re = new RegExp("\\b(" + s[i] + ")", "ig");
		c.d = String(c.s).replace(re, replacement);
		c.n = String(c.n).replace(re, replacement);	
	}
	
	return c;
};

FastLookup.prototype.ISSUE_TYPES = {
	ALL: "",
	EQ: "EQ",
	MF: "MF"
};

FastLookup.prototype.setIssueType = function(type) {
	this.issueType = type;
};

FastLookup.prototype.search = function(e, el) {

	if (this.searchTimer) { clearTimeout(this.searchTimer); }
	
	if (el.value == this.query) {
		return;
	}	

	else if (!String(el.value).replace(this.invalidChars, "")) {
		this.query = el.value;
		this.clearResults();

	}
	else {


		this.abortActiveRequests();
		this.query = el.value;
		if (this.localCache[this.query + this.issueType]) {
			this.drawResults(this.localCache[this.query + this.issueType]);

		}
		else {

			this.abortActiveRequests();

			// short delay to reduce number of requests
			var  self = this;
			this.searchTimer = setTimeout(function() { self.searchDelay(e, el); },300);

		}

	}	

};


FastLookup.prototype.searchDelay = function(e, el) {

		//console.info("Search")
		this.searchTimer = null;

		this.requestor.load({
			url: this.requestURL,
			contentType: "text/javascript",
			data: { q: this.query, issueType: this.issueType, callback: "handleResults", context: "this" },
			context: this
		});


}

FastLookup.prototype.handleResults = function(query, results, showMoreLink) {

	var cachedNodes = [];
	var elTable = Element.create("table");
	
	for (var i=0,group; i<results.length; i++) {
		group = results[i];
		if (group.length) {
			var elTbody = Element.create("tbody"); 
			
			for (var j=0,c; j<group.length; j++) {
				c = this.highlightText(group[j]);
				

				var elRow = Element.create("tr", { symbol: c.s, isfund: c.f }, [
					Element.create("td", { "class": this.CSS_ISSUE_NAME }, c.n),
					Element.create("td", { "class": "symbolColumn" }, c.d)
				], elTbody);
				
				if (group.length-1 == j && (results.length -1 != i || showMoreLink)) {
					Element.addClass(elRow, this.CSS_GROUP_END);
				}

			}
			Element.addChild(elTable, elTbody);
		}
	}
	
	if (showMoreLink) {
		Element.create("tbody", null, [
			Element.create("tr", { "class": this.CSS_MORE_LINK }, [
				Element.create("td", { "colspan":3 }, [
					Element.create("a", { href: this.buildMoreLink() }, "Additional matches...")
				])
			])
		], elTable);	
	}
	
	if (!elTable.childNodes.length) {
		Element.create("tbody", null, [
			Element.create("tr", { "class": this.CSS_GROUP_END }, [
				Element.create("td", null, "No securities were found for \"<b>" + query + "</b>\".<br />Try symbol lookup for a more advanced search.")
			])
		], elTable);
		elTable.setAttribute(this.ATTR_NO_RESULTS, "true");
	}
	
	cachedNodes.push(elTable);
	this.localCache[query + this.issueType] = cachedNodes;
	
	this.drawResults(cachedNodes);
	
};

FastLookup.prototype.createResultsContainer = function() {
	this.elResults = Element.create("div", { "class": this.CSS_HIDDEN }, null, document.body);
	Element.addClass(this.elResults, this.CSS_RESULTS);
};


FastLookup.prototype.drawResults = function(cachedNodes) {
	this.clearResults();
	
	if (!this.elResults) {
		this.createResultsContainer(); 

	}

	var pos = Element.getXY(this.elInput);
	var size = Element.getSize(this.elInput);
	
	Element.setXY(this.elResults, pos.x, pos.y + size.height);
	
	Element.removeClass(this.elResults, this.CSS_HIDDEN);
	for (var i=0; i<cachedNodes.length; i++) {
		Element.addChild(this.elResults, cachedNodes[i]);
	}
	this.elResultRows = Element.parseSelector("tr", this.elResults);
	this.elMoreLink = Element.parseSelector("tr." + this.CSS_MORE_LINK + " a", this.elResults, "first");
	
	this.addResultEvents(cachedNodes[0].getAttribute(this.ATTR_NO_RESULTS));
	
	WCH.Apply(this.elResults, null, true);
};


FastLookup.prototype.clearResults = function() {
	if (!this.elResults) {
		return;

	}
	if (this.elResultRows && this.elResultRows.length) {
		Element.removeClass(this.elResultRows, this.CSS_SELECTED);
	}
	Element.addClass(this.elResults, this.CSS_HIDDEN);
	Element.removeChildNodes(this.elResults);
	this.removeResultEvents();
	WCH.Discard(this.elResults);
};

FastLookup.prototype.buildMoreLink = function() {
	var URL = this.finderURL
		+ (/\?/.test(this.finderURL) ? "&" : "?")

	URL += "text=" + this.query;
	
	if (this.issueType) {
		URL += "&issueType=" + this.issueType;
	}
	
	return URL;
};

FastLookup.prototype.navigate = function(e) {
	switch (e.nativeEvent.keyCode) {
		case this.KEY_CODE_DOWN :
			e.cancel();
			var rowIdx = Math.min(this.selectedRow + 1, this.elResultRows.length-1);
			this.highlightRow(rowIdx);
			break;
		
		case this.KEY_CODE_UP :
			e.cancel();
			var rowIdx = Math.max(this.selectedRow - 1, -1);
			this.highlightRow(rowIdx);
			break;
		
		case this.KEY_CODE_ESC :
			e.cancel();
			this.clearResults();
			break;
	}

};

FastLookup.prototype.highlightRow = function(rowIdx) {
	if (this.selectedRow != rowIdx) {
		if (this.elResultRows[this.selectedRow]) {
			Element.removeClass(this.elResultRows[this.selectedRow], this.CSS_SELECTED);		
		}
		if (this.elResultRows[rowIdx]) {

			Element.addClass(this.elResultRows[rowIdx], this.CSS_SELECTED)
		}
		
		this.selectedRow = rowIdx;
	}

};

FastLookup.prototype.selectResult = function(e) {
	if ("click" == e.nativeEvent.type || this.KEY_CODE_ENTER == e.nativeEvent.keyCode) {

		if (this.selectedRow == -1) {
			// recently commented the below return to have .setEventFire work
			// if problems occur consider removing comment
			//return;
			if (this.elResultRows && 1 == this.elResultRows.length) {
				// only one result, set it as selected
				this.selectedRow = 0;
			}
			else {
				// multiple results, just submit the form
				this.go(this.elInput.value);
				return;
			}
		}
		else {
			if (Element.hasClass(this.elResultRows[this.selectedRow], this.CSS_MORE_LINK)) {
				// more link clicked
				window.location = this.elMoreLink.href;
				return;
			}
		}
		
		e.cancel();

		// go to selected row
		this.go(
			this.elResultRows[this.selectedRow].getAttribute("symbol"), 
			(this.elResultRows[this.selectedRow].getAttribute("isfund") == "1")
		);
		
	}
};

FastLookup.prototype.setInputValue = function(value) {
	this.elInput.value = value;
	
	var onChangeInput = this.getOnChangeInput();
	onChangeInput.addElement(this.elInput);
	onChangeInput.fire();
	onChangeInput.removeAllElements();
};

FastLookup.prototype.setEventFire = function(eventToFire) {
	this.submitFire = eventToFire;
};

FastLookup.prototype.go = function(symbol, isFund) {

	if (this.callbackMethod) {
		this.callbackMethod(symbol);
		return;
	}


	if (symbol) {
		this.query = symbol;
		this.setInputValue(symbol);
	}
		
	if (this.destinationURL) {
		window.location = this.destinationURL + this.query;
	}
	else if (!this.stopSubmit) {
		if (this.submitFire) {
			this.submitFire.fire();
		} else {
			this.elForm.submit();
		}
	}
	
	this.clearResults();
	
};

FastLookup.prototype.abortActiveRequests = function() {
	this.requestor.abortRequests();

};



var CrossDomainRequestor = function() {
	this.globalContext = "window";
	this.requests = [];
};

CrossDomainRequestor.prototype.setGlobalContext = function(value) {
	this.globalContext = value;
};

CrossDomainRequestor.prototype.buildRequestURL = function(params) {
	var url = params.url + "?";
	
	if (params.contentType) {
		params.data["..contentType.."] = params.contentType;
	}
	
	params.data.context = this.globalContext;
	
	for (var i in params.data) {
		url += i + "=" + encodeURIComponent(params.data[i]) + "&";
	}
	
	return url;
};

CrossDomainRequestor.prototype.load = function(params) {
	var elScript = document.createElement("script");
	elScript.src = this.buildRequestURL(params);
	document.getElementsByTagName("head")[0].appendChild(elScript);
	this.requests.push(elScript);
};

CrossDomainRequestor.prototype.abortRequests = function() {
	for (var i=0; i<this.requests.length; i++) {
		//try {
			//this.requests[i].src = "javascript:false;" // error in IE https
			Element.remove(this.requests[i]);
			this.requests[i] = null;
		//} catch (e) {}
	}
	this.requests = [];
};

//wch.js
var WCH_Constructor=function(){if(!(document.all&&document.getElementById&&!window.opera&&navigator.userAgent.toLowerCase().indexOf("mac")==-1)){this.Apply=function(){};this.Discard=function(){};return;}
var _bIE55=false;var _bIE6=false;var _oRule=null;var _bSetup=true;var _oSelf=this;this.Apply=function(vLayer,vContainer,bResize){if(_bSetup)_Setup();if(_bIE55&&(oIframe=_Hider(vLayer,vContainer,bResize))){oIframe.style.visibility="visible";}else if(_oRule!=null){_oRule.style.visibility="hidden";}};this.Discard=function(vLayer,vContainer){if(_bIE55&&(oIframe=_Hider(vLayer,vContainer,false))){oIframe.style.visibility="hidden";}else if(_oRule!=null){_oRule.style.visibility="visible";}};function _Hider(vLayer,vContainer,bResize){var oLayer=_GetObj(vLayer);var oContainer=((oTmp=_GetObj(vContainer))?oTmp:document.getElementsByTagName("body")[0]);if(!oLayer||!oContainer)return;var oIframe=document.getElementById("WCHhider"+oLayer.id);if(!oIframe){var sFilter=(_bIE6)?"filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0);":"";var zIndex=oLayer.style.zIndex;if(zIndex=="")zIndex=oLayer.currentStyle.zIndex;zIndex=parseInt(zIndex);if(isNaN(zIndex))return null;if(zIndex<2)return null;zIndex--;var sHiderID="WCHhider"+oLayer.id;oContainer.insertAdjacentHTML("afterBegin",'<iframe class="WCHiframe" src="javascript:false;" id="'+sHiderID+'" scroll="no" frameborder="0" style="position:absolute;visibility:hidden;'+sFilter+'border:0;top:0;left;0;width:0;height:0;background-color:#ccc;z-index:'+zIndex+';"></iframe>');oIframe=document.getElementById(sHiderID);_SetPos(oIframe,oLayer);}else if(bResize){_SetPos(oIframe,oLayer);}
return oIframe;};function _SetPos(oIframe,oLayer){oIframe.style.width=oLayer.offsetWidth+"px";oIframe.style.height=oLayer.offsetHeight+"px";oIframe.style.left=oLayer.offsetLeft+"px";oIframe.style.top=oLayer.offsetTop+"px";};function _GetObj(vObj){var oObj=null;switch(typeof(vObj)){case"object":oObj=vObj;break;case"string":oObj=document.getElementById(vObj);break;}
return oObj;};function _Setup(){_bIE55=(typeof(document.body.contentEditable)!="undefined");_bIE6=(typeof(document.compatMode)!="undefined");if(!_bIE55){if(document.styleSheets.length==0)
document.createStyleSheet();var oSheet=document.styleSheets[0];oSheet.addRule(".WCHhider","visibility:visible");_oRule=oSheet.rules(oSheet.rules.length-1);}
_bSetup=false;};};var WCH=new WCH_Constructor();


/* -- Loaded:/tdameritrade/common/scripts/fastlookup/fastlookup.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


WatchLists_class = function() {


}

WatchLists_class.prototype.attachAddLink = function(el) {

	el = Element.get(el);
	if (!el) { return; }

	Events.add({element:el,type:"click",context:this,handler:this.displayWatchlists});

	this.symbol = el.getAttribute("symbol");

	// this.watchlistsData = [{name:"TEST"}]

}


WatchLists_class.prototype.displayWatchlists = function(e,el,data) {


	Events.cancel(e);
	el.blur();

	if (!this.watchlistsData) {


		Common.loadContentBuffer({
			page:buildAbsolutePath("/modules/WatchLists/buffer_retrieveWatchlists.asp"),
			context:this,
			contentType:"text/javascript",
			preventEval:true,
			data:{retrieveWatchlists:true},
			onload:function(contentBuffer) {
				var data = DataFunctions.deserialize(contentBuffer.getResult());
				this.watchlistsData = data;
				this.displayWatchlists(e,el,data);
			},
			onerror:null
		});

		return;
	}

	//console.info(el);

	this.watchListsModule = this.watchListsModule || this.createAddToWatchListsModule();
		
	Element.toggleClass(this.watchListsModule,"none");

	if (!Element.hasClass(this.watchListsModule,"none")) {
		var linkPos = Element.getXY(el);

		Element.setXY(this.watchListsModule,linkPos.x,linkPos.y-8);
		WCH.Apply("addToWatchListsModule",null,true);


	}
	else {
		this.hideAddToWatchListsModule()
	}

	
}

WatchLists_class.prototype.hideAddToWatchListsModule = function(e,el,data) {
	Element.addClass(this.watchListsModule,"none");
	WCH.Discard("addToWatchListsModule");
}

WatchLists_class.prototype.createAddToWatchListsModule = function(e,el,data) {

	//recurseObject({o:this.watchlistsData,n:"this.watchlistsData",nowrite:1})

	var ul;
	var div = Element.create("div",{id:"addToWatchListsModule",className:"none"},[
		 Element.create("div",{id:"addToWatchListsModuleHeader",Events:{type:"click",context:this,handler:this.displayWatchlists}},[
		 	"Add to Watch List "
		 	,Element.create("img", {className:"addToWatchlist_arrow", src:"https://tdameritrade.cache.wallst.com/images/charts/ico-control-down-arrow.gif"})
		 ])
		,Element.create("div",{id:"addToWatchListsModuleBody"},[
			ul = Element.create("ul",{})
		])
	],document.body);

	var a,aHref;

	this.watchlistsData.push({name:"Create a New Watch List",type:"new"});

	for (var i=0; i<this.watchlistsData.length;i++) {

		aHref = gSessionSeedDomain + ('/cgi-bin/apps/u/ThirdPartyUrlLauncher/new?target=watchlists&param='+Common.encode(this.symbol)) + (!this.watchlistsData[i].type ? ('&param2='+this.watchlistsData[i].id) : '')

		Element.create("li",{},[
			a = Element.create("a",{href:aHref,target:"vendorLinks"},this.watchlistsData[i].name)
		],ul);

		if (!i) {
			Element.addClass(a,"first");
		}


		if (i == this.watchlistsData.length-1) {
			Element.addClass(a,"last");
		}

	}

	Events.add({element:document,type:"click",context:this,handler:this.hideAddToWatchListsModule});


	return div;

}


/* -- Loaded:/tdameritrade/modules/WatchLists/WatchLists_class.js*/




/* -- Attempting to load:/includes/jslib/contentbuffer/contentBuffer.4.js */


function ApplicationStateManager() {

	if(!this.__state_manager__) {
		ApplicationStateManager.prototype.__state_manager__ = this;

		function Executable(funcPtr, context, args, onerror) {
			this.f = funcPtr || function() {};
			this.c = context || window;
			this.a = args || [];
			this.e = onerror || function() {};
		}
		var currentHash = false;
		var iframe = false;
		var stateManager = "/includes/jslib/wsdom/stateManager/stateManager.html?hash=";

		var curOp = -1;
		var queue = [];
		var temp = 0;

		function fnHandler() {
			if(/Debug\.addObject/.test(document.body.innerHTML)) {
				ApplicationStateManager.prototype.queue = queue;
			}
		}


		var ref = this;

		var AddListener = function() {
			if(window.addEventListener) {
				return function(el, type, func) {
					el.addEventListener(type, func, false);
				}
			} else if(window.attachEvent) {
				return function(el, type, func) {
					el.attachEvent("on" + type, func);
				}
			}
		}();

		function CreateIframe(src) {
			iframe = document.createElement("iframe");
			iframe.style.display = "none";
			iframe.setAttribute("src", src);
			AddListener(iframe, "load", CheckHash);
			document.body.appendChild(iframe);
		}
		function AddToQueue(funcPtr, context, args, onerror) {
			if(curOp < ref.QueueMax - 1) {
				curOp++;
				if(curOp == ref.QueueMax) {
					queue.push(new Executable(funcPtr, context, args, onerror));
				} else {
					queue.splice(curOp, ref.QueueMax - curOp, new Executable(funcPtr, context, args, onerror));
				}
			} else {
				queue.shift();
				queue.push(new Executable(funcPtr, context, args, onerror));
			}
		}
		function CheckHash() {
			if(iframe.contentWindow.location.search != currentHash) {
				currentHash = iframe.contentWindow.location.search;
				ExecuteHash();
			}
		}
		function SetHash(item) {
			if(!iframe) {
				CreateIframe(stateManager + "action_"+item);
				currentHash = "?hash=action_"+item;
			} else if(iframe.contentWindow.location.search != ("?hash=action_"+item)) {
				iframe.src = stateManager + "action_"+item;
				currentHash = "?hash=action_"+item;
			}
		}
		function ExecuteHash() {
			var item = parseInt(iframe.contentWindow.location.search.replace(/[^\d]*(\d+)[^\d]*/, "$1"));
			Execute(item, true);
		}
		function Execute(item, bDontChangeHash) {
			var s = queue[item] || new Executable();
			try {
				s.f.apply(s.c, s.a);
				if(!bDontChangeHash) {
					SetHash(item);
				}
			} catch(err) {
				console.log(err);
				s.e.apply(s.c, [err].concat(s.a));
			}
		}

		AddListener(window, "load", fnHandler);

		ApplicationStateManager.prototype.Change = function(funcPtr, context) {
			if(typeof funcPtr == "function" || typeof funcPtr == "string") {
				funcPtr = (typeof funcPtr == "function") ? funcPtr : context[funcPtr];
				var args = [];
				if(arguments.length > 2) {
					for(var i = 2, len = arguments.length; i < len; i++) {
						args.push(arguments[i]);
					}
				}
				AddToQueue(funcPtr, context, args);
			} else if (typeof funcPtr == "object") {
				AddToQueue(funcPtr.handler, funcPtr.context, funcPtr.arguments || funcPtr.args || funcPtr.data, funcPtr.onerror);
			}

			Execute(curOp);
		}

		ApplicationStateManager.prototype.previous = function() {
			if(curOp > 0) {
				curOp--;
				Execute(curOp);
			}
		}

		ApplicationStateManager.prototype.next = function() {
			if(curOp < this.QueueMax - 1) {
				curOp++;
				Execute(curOp);
			}
		}

		ApplicationStateManager.prototype.IsNext = function() {
			return curOp < (this.QueueMax - 1);
		}
		ApplicationStateManager.prototype.IsPrevious = function() {
			return curOp > 0;
		}
	}
}
//Over ride this to change the size of the queue to be managed
ApplicationStateManager.prototype.QueueMax = 5;

/* -- Loaded:/tdameritrade/common/scripts/ApplicationStateManager.js*/


