Overview = function(args) {
	args = args || "{}";
	args = DataFunctions.deserialize(args);

	this.symbol = args.symbol || "";
	this.displaySymbol = args.displaySymbol || "";
	this.domain = args.domain || "";
	this.predictLink = args.predictLink || "";
	this.predictWallStreet = args.predictWallStreet;
	this.chartDuration = args.chartDuration;
	
	this.StateManager = new ApplicationStateManager;
	this.StateManager.QueueMax = 100;
}

Overview.prototype.tabMap = [
	 {type: "news", callback: "renderNews"}
	,{type: "industryPosition", callback: "renderIndustryPosition"}
	,{type: "companyProfile", callback: "renderCompanyProfile"}
]

Overview.prototype.init = function() {
	
	this.primaryContentTab = Element.get("primaryContentTab");
	this.durationControls = Element.parseSelector("a", "smartChartDurationControls");
	this.comparisonControls = Element.parseSelector("div.comparison input[type='checkbox']", "smartChartComparisonControls");
	this.indicatorControls = Element.parseSelector("div.indicator input[type='checkbox']", "smartChartComparisonControls");
	this.tabNav = Element.parseSelector("ul li", Element.parseSelector( "div[id='TabNav']!stocksHeader" ) );

	Events.add({element: this.durationControls, type: "click", handler: this.selectDuration, context: this});
	Events.add({element: this.comparisonControls, type: "click", handler: this.selectComparison, context: this});
	Events.add({element: this.indicatorControls, type: "click", handler: this.selectIndicator, context: this});
	Events.add({element: Element.get("popAdvancedChart"), type: "click", handler: Common.popWindow, context: Common, data: {path: buildAbsolutePath("/stocks/charts/charts.asp?display=popup"), width: 810, height:755, scrollbars:"yes", resizable:"yes"} });
	Events.add({element: Element.get("historicalLink"), type: "click", handler: Common.popWindow, context: Common, data: {path: buildAbsolutePath("/modules/QuotesSplits/QuotesSplits.asp"), width: 580, height:370, resizable:"no"} });
	Events.add({element: Element.get("togglePredictWallStreet"), type: "click", handler: this.setPredictPreference, context: this});
	Events.add({element: Element.parseSelector(".reportsAndRatingsModule a!whatsThis", "lowerContent"), type: "click", handler: this.popReport, context: this});	
	
	for (var i = 0, tabPress; i < this.tabNav.length; i++) {
		tabPress = Events.add({element: this.tabNav[i], type: "click", handler: this.switchTabState, context: this, data: this.tabMap[i]});
	}
	
	if ("hide" != this.predictWallStreet && Element.get("togglePredictWallStreet")) {
		this.togglePredict(Element.get("togglePredictWallStreet"));
	}
	
	this.initSmartChart();
	if (Element.get("pricePerformance")) { this.initPricePerformanceChart(); }
	
	this.StateManager.Change({
		handler: this.switchTab,
		context: this,
		arguments: [
			this.tabNav[0], {type: "news"}
		]
	});
	
	/*Common.addTopLink(Element.create("a",{href:"javascript:void(0)",Events:{type:"click",context:Common,handler:Common.popWindow, data: {path:buildAbsolutePath("stocks/overview/whatsnew/index.asp"), width: 800, height: 600, scrollbars: 1}},className:"iconBackground comingSoon"},"What's New?"));*/

	if (gIsPrivate) {
		Common.addTopLink(Element.create("a",{href:"javascript:void(0)",Events:{type:"click",context:Common,handler:Common.popWindow,data:{path:gSessionSeedDomain+"/cgi-bin/apps/u/PLoad?pagename=thirdparty/stockGlossary.html", width: 810, height: 755}}},"Glossary"));
	}
	if (gIsPrivate) {
		Common.addTopLink(Element.create("a",{target:"vendorLinks", id:"tdamPageHelp", className:"iconBackground", href:gSessionSeedDomain+"/cgi-bin/apps/u/ThirdPartyUrlLauncher/new?target=help&param=toolsAndResearch/research/mainResearch"},"Page Help"));
	}
}

Overview.prototype.switchTabState = function(e, el, data) {
	Events.cancel(e);
	
	el.blur();
	
	if (Element.hasClass(el, "current")) { return; }

	this.StateManager.Change({
		handler: this.switchTab,
		context: this,
		arguments: [
			el, data
		]
	});	
}

Overview.prototype.switchTab = function(el, data) {
	Element.removeClass(this.tabNav, "current");
	Element.addClass(el, "current");	
	
	if (Element.get(data.type)) {
		Element.addClass(Element.parseSelector("div.tabContent", "primaryContentTab"), "hide");
		Element.removeClass(Element.get(data.type), "hide");
	} else {
		this.getTabData(data);
	}
}

Overview.prototype.getTabData = function(args) {
	Common.loadContentBuffer({
		 page: buildAbsolutePath("/stocks/overview/overview_getTabData.asp")
		,context: this
		,preventEval: true
		,data: {
			type: args.type
		}
		,onload: this[args.callback]
	});
}

Overview.prototype.initSmartChart = function(args) {
	this.smartChart = new Chart();
	
	args = args || {}; 
	var duration = this.chartDuration || 1;
	var symbol = this.symbol || "";

	this.smartChart.setName("smartChart");
	this.smartChart.setCache(120);
	this.smartChart.setDuration(duration);
	this.smartChart.setSymbol(symbol);
	this.smartChart.setImageContainer("smartChartContainer");
	this.smartChart.linkToInteractive(true);
	
	Element.addClass(Element.parseSelector("a[duration='"+duration+"']", "smartChartDurationControls", "first"), "active");
	if (1 == duration) { this.toggleSMA(0); }

	this.smartChart.render();
	this.smartChart.initResizeBuffer();
}

Overview.prototype.toggleSMA = function(on) {
	var smaControl = Element.parseSelector("div.indicator", "smartChartComparisonControls", "first");

	if (on) {
		Element.removeClass(smaControl, "disabled");
		Element.parseSelector("input", smaControl, "first").disabled = false;
	} else {
		Element.addClass(smaControl, "disabled");
		Element.parseSelector("input", smaControl, "first").disabled = true;
	}
}

Overview.prototype.pricePerformanceChartDuration = 365;
Overview.prototype.pricePerformanceChartComparisonColors = [
	"EB8B10"
	,"3164CD"
	,"FFCB00"
];

Overview.prototype.initPricePerformanceChart = function(args) {
	this.pricePerformanceChart = new Chart();
	
	args = args || {};
	var duration = this.pricePerformanceChartDuration;
	var symbol = this.symbol || "";
	
	this.pricePerformanceChart.setName("pricePerformance");
	this.pricePerformanceChart.setCache(120);
	this.pricePerformanceChart.setDuration(duration);
	this.pricePerformanceChart.setSymbol(symbol);
	this.pricePerformanceChart.setImageContainer("pricePerformanceChartContainer");	

	var comparisons = Element.parseSelector("div.chartControls div.label", "industryPositionChart");
	for (var i = 1; i < comparisons.length; i++) {
		this.pricePerformanceChart.addComparison(comparisons[i].getAttribute("wsodIssue"), this.pricePerformanceChartComparisonColors[i-1]);
	}
	
	this.pricePerformanceChart.render();
	this.pricePerformanceChart.initResizeBuffer();
}

Overview.prototype.selectDuration = function(e, el, data) {
	Events.cancel(e);
	
	el.blur();

	var duration = parseInt(el.getAttribute("duration"));
	
	Element.removeClass(this.durationControls, "active");
	Element.addClass(el, "active");
	
	if (1 == duration) { 
		this.toggleSMA(0); 
	} else {
		this.toggleSMA(1); 
	}
	
	this.smartChart.setDuration(duration);
	this.smartChart.setPreference("Settings.OverviewChartDuration", duration);
	
	this.smartChart.render();
}

Overview.prototype.selectComparison = function(e, el, data) {
	var symbol = el.value;
	var color = el.getAttribute("color");
	
	if (el.checked) {
		this.smartChart.addComparison(symbol, color);
	} else {
		this.smartChart.removeComparison(symbol, color);
	}
	
	this.smartChart.render();
}

Overview.prototype.selectIndicator = function(e, el, data) {
	var name = el.value;
	var color = el.getAttribute("color");
	
	if (el.checked) {
		this.smartChart.addIndicator(name, color);
	} else {
		this.smartChart.removeIndicator(name, color);
	}
	
	this.smartChart.render();
}

Overview.prototype.popReport = function(e, el, data) {
	Events.cancel(e);
	
	Common.popCustomWindow({
		path: el.getAttribute("href")
		,name: "pdf_window"
		,width: 700
		,height: 450
		,scrollbars: "yes"
		,menubar: "no"
		,toolbar: "no"
		,status: "yes"
		,resizable: "yes"
	});
}

Overview.prototype.renderNews = function(data) {
	var newsData = DataFunctions.deserialize(data.getResult());
	
	var div = Element.create("div", {"id":"news", "class":"tabContent"});
	
	var todaysDate = jsToMsDate(new Date());
	
	var prevDate, newsStory;
	for (var i = 0; i < newsData.length; i++) {
		if (!prevDate || Math.floor(newsData[i].rawDate) != prevDate) {
			Element.addChild(div, 
				Element.create("h3", {"class":(!prevDate?"first":"")}, (Math.floor(todaysDate) == Math.floor(newsData[i].date) ? "Today's News, " : "")+newsData[i].displayDate)
			);
		}
		
		Element.addChild(div,
			Element.create("div", {"class":"newsItem"}, [
				Element.create("div", {"class":"newsDate"}, newsData[i].displayTime)
				,newsStory = Element.create("div", {"class":"newsStory"}, [
					Element.create("a", {"href":buildAbsolutePath("/stocks/news/story.asp?docKey="+newsData[i].docKey)}, newsData[i].headline)
					,Element.create("span", {}, "("+newsData[i].provider+")")
				])
				,Element.create("br", {"class":"clearNoHeight"})
			])
		);
		
		if (0 == i) {
			Element.addChild(newsStory,
				Element.create("div", {}, newsData[i].headline)
			);
		}
		
		prevDate = Math.floor(newsData[i].rawDate);
	}
	
	Element.addChild(div, 
		Element.create("div", {"class":"additionalItem"}, [
			Element.create("a", {"href":buildAbsolutePath("/stocks/news/story.asp")}, "Go to All Current &amp; Historical News")
		])
	);
	
	Element.addClass(Element.parseSelector("div.tabContent", "primaryContentTab"), "hide");
	Element.addChild(this.primaryContentTab, div);
}

Overview.prototype.renderIndustryPosition = function(data) {
	var industryData = DataFunctions.deserialize(data.getResult());
	var comparisonData = industryData.comparisonData;
	
	var div = Element.create("div", {"id":"industryPosition", "class":"tabContent"});
	
	if (comparisonData && comparisonData.length) {
		var chartControls, compareTable, compareHeader, compareBody;
		Element.create("div", {"id":"industryPositionChart"}, [
			Element.create("h3", {}, industryData.primarySymbol+"'s 1yr Relative Performance of Stock Price vs. Peers")
			,Element.create("div", {"id":"pricePerformanceChartContainer"}, [
				Element.create("img", {"id":"pricePerformance", "src":"https://tdameritrade.cache.wallst.com/images/charts/x.gif"})
			])
			,chartControls = Element.create("div", {"class":"chartControls"})
		], div);
		
		Element.create("h3", {}, industryData.primarySymbol+"'s Position in the "+industryData.industry+" Industry", div);
		
		Element.create("div", {"class":"industryComparisonTableContainer"}, [
			compareTable = Element.create("table", {"id":"industryComparisonTable", "class":"compareTool"})
		], div);
		
		compareHeader = Element.create("thead", {}, null, compareTable);
		compareBody = Element.create("tbody", {}, null, compareTable);
		
		var rowData = {"Compared Stocks":[]};
		for (var i = 0; i < comparisonData.length; i++) {
			Element.addChild(chartControls, [
				Element.create("div", {"class":"colorKey symbol"+(i+1)}, "&nbsp;")
				,Element.create("div", {"class":"label", "wsodIssue":comparisonData[i].wsodIssue}, comparisonData[i].displaySymbol)
			]);
			
			rowData["Compared Stocks"].push({
				 value: comparisonData[i].displaySymbol
				,wsodIssue: comparisonData[i].wsodIssue
				,date: comparisonData[i].date
			})
			
			for (var j = 0, data; j < comparisonData[i].data.length; j++) {
				data = comparisonData[i].data[j];
				rowData[data.label] = rowData[data.label] || [];
				
				rowData[data.label].push({
					 value: data.value
					,percentile: data.percentile
				});
			}
		}
		Element.addChild(chartControls, Element.create("br", {"class":"clearNoHeight"}));
			
		var tr, tdContent, td;
		for (var i in rowData) {
			tr = Element.create("tr", {}, [
				Element.create("th", {}, i)
			]);
			
			if ("Compared Stocks" != i) {
				Events.add({element: tr, type: "mouseover", handler: this.highlightOver, context: this})
				Events.add({element: tr, type: "mouseout", handler: this.highlightOut, context: this})
			}
			
			for (var j = 0; j < rowData[i].length; j++) {
				tdContent = "Compared Stocks" == i ? Element.create("h3", {}, [Element.create("a", {"issue":rowData[i][j].wsodIssue, "href":buildAbsolutePath("/stocks/overview/overview.asp?symbol="+rowData[i][j].value), "Events":[{type: "mouseover", handler: this.showSymbolHover, context: this},{type: "mouseout", handler: this.hideSymbolHover, context: this}]}, rowData[i][j].value),Element.create("span",{},"As of " + rowData[i][j].date)]) : rowData[i][j].value;
				
				td = Element.create("td", {"class":(0==j?"focus":""), style:"width:"+Math.floor(85 / (comparisonData.length))+"%;"}, tdContent);
				Element.addChild(tr, td);
				
				if ("Compared Stocks" != i) {
					Element.addChild(td, [
							 Element.create("div", {"class":"highlightHide small"}, "&nbsp;")
							,Element.create("div", {"class":"highlightShow tileImg"}, [
								Element.create("img", {"src":"https://tdameritrade.cache.wallst.com/images/funds_quintile_"+rowData[i][j].percentile+".gif"})
							])
						]
					)
				}
			}
			
			Element.addChild("Compared Stocks"==i?compareHeader:compareBody, tr);
		}
		

		if (gIsPrivate) {

			tr = Element.create("tr", {}, [
				Element.create("th", {}, "&nbsp;")
			])

			for (var i in comparisonData) {
				Element.addChild(tr, 
					Element.create("td", {}, [
						Element.create("div", {"class":"btnContainer"}, [
							 Element.create("a", {"id":"Buy"+i, "target":"vendorLinks", "href":this.domain+"/cgi-bin/apps/u/ThirdPartyUrlLauncher/new?target=buyBttn&param="+comparisonData[i].displaySymbol, "tdbutton":"green", "width":"48"}, "Buy")
							,Element.create("div", {"class":"btnBreak"})
							,Element.create("a", {"id":"Sell"+i, "target":"vendorLinks", "href":this.domain+"/cgi-bin/apps/u/ThirdPartyUrlLauncher/new?target=sellBttn&param="+comparisonData[i].displaySymbol, "tdbutton":"green", "width":"48"}, "Sell")
						])
					])
				);
			}

		}

		Element.addChild(compareBody, tr);	
	} else {
		Element.addChild(div, 
			Element.create("div", {"class":"nodataerror"}, "Industry comparison is not available for "+this.displaySymbol+".")
		);
	}

	Element.addClass(Element.parseSelector("div.tabContent", "primaryContentTab"), "hide");
	Element.addChild(this.primaryContentTab, div);
	
	Common.renderTDAMButtons(this.primaryContentTab);
	
	if (!this.pricePerformanceChartImage) {
		this.initPricePerformanceChart({comparisonSymbols: industryData.comparisonSymbols});
	}
}

Overview.prototype.renderCompanyProfile = function(data) {
	var profileData = DataFunctions.deserialize(data.getResult());

	var div = Element.create("div", {"id":"companyProfile", "class":"tabContent"})
	if (profileData && profileData.CompanyProfile && -32768 != profileData.CompanyProfile) {
		Element.addChild(div,
			Element.create("div", {"id":"companyProfileData"}, profileData.CompanyProfile)
		);
	} else {
		Element.addChild(div,
			Element.create("div", {"class":"nodataerror"}, "Company profile information is not available for "+this.displaySymbol+".")
		);
	}

	Element.addClass(Element.parseSelector("div.tabContent", "primaryContentTab"), "hide");
	Element.addChild(this.primaryContentTab, div);
}

Overview.prototype.highlightOver = function(e, el, data) {
	Element.addClass(el, "highlight");
}

Overview.prototype.highlightOut = function(e, el, data) {
	Element.removeClass(el, "highlight");
}

Overview.prototype.showSymbolHover = function(e, el, data) {
	if (!this["symbolHover"+el.innerHTML]) {
		Common.loadContentBuffer({
			 page: buildAbsolutePath("/modules/SymbolHover/SymbolHover.asp")
			,context: this
			,preventEval: true
			,data: {
				symbol: el.innerHTML
				,wsodIssue: el.getAttribute("issue")
			}
			,onload: function(data) {
				this.renderSymbolHover(el, data);
			}
		});
	} else {
		this.renderSymbolHover(el);
	}
}

Overview.prototype.renderSymbolHover = function(el, data) {
	var symbolData = data ? DataFunctions.deserialize(data.getResult()) : {};
	var symbol = symbolData.DisplaySymbol || el.innerHTML;

	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 
					,Element.create("span", {}, [
						" ("+symbolData.Exchange+":"
						,Element.create("strong", {}, symbol)
						,")"
					])
				 ])
				,Element.create("div", {"class":"symbolInfo"}, [
					Element.create("label", {}, "Sector:")
					,Element.create("span", {}, symbolData.Sector)
				])
				,Element.create("div", {"class":"symbolInfo"}, [
					Element.create("label", {}, "Industry:")
					,Element.create("span", {}, 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"}, "Based on last delayed trade at " + symbolData.LastTradeTime + " ET")
			])
		], "industryPosition");
		
		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");
}

Overview.prototype.hideSymbolHover = function(e, el, data) {
	Common.contentBufferAbortRequests();

	Element.addClass(Element.parseSelector("div.symbolHover", "industryPosition"), "hide");
}

Overview.prototype.setPredictPreference = function(e, el, data) {
	Common.loadContentBuffer({
		 page: buildAbsolutePath("/common/setPreference.asp")
		,context: this
		,preventEval: true
		,data: {
			PredictWallStreet: Element.hasClass(el, "expanded") ? "hide" : "show"
		}
	});
	
	this.togglePredict(el);
}

Overview.prototype.togglePredict = function(el) {
	var predictWallSt = Element.get("predictWallSt");
	
	if (!predictWallSt) {
		predictWallSt = Element.create("iframe", {"style":"border:0;", "name":"predictWallSt", "id":"predictWallSt", "class":"none", "frameBorder":"0", "style":"border:none;", "width":"100%", "height":"100", "src":this.predictLink, "scrolling":"no"}, null, "predictWallStreet")
	}

	Element.toggleClass(el, "expanded");
	Element.toggleClass(predictWallSt, "none")
	
	if (Element.hasClass(el, "expanded")) {
		Element.setHTML(el, "Close PredictWallStreet");
	} else {
		Element.setHTML(el, "Open PredictWallStreet");
	}
	
	if (predictWallSt.getAttribute("newsrc") && Element.hasClass(el, "expanded")) {
		predictWallSt.setAttribute("src", predictWallSt.getAttribute("newsrc"));
		predictWallSt.setAttribute("newsrc", "");
	}
}
