
function StockReports() { }

StockReports.prototype = {

	 BUFFER_URL : buildAbsolutePath("/common/reports/reports.archives.asp")

	,PROVIDER_DATA_URL : buildAbsolutePath("/common/reports/provider.info.asp")

	/*--------------------------------------
		COL_WIDTH_ + num

		This is because in IE tables render to
		100% width by default. This means to
		create a width based on a table we
		need to have it be pre-defined. Lame,
		i know.
	----------------------------------------*/

	,COL_WIDTH_1 : 220

	,COL_WIDTH_2 : 240

	,COL_WIDTH_2B : 320

	/*--------------------------------------
		Tracker
		Stores provider info that has been
		queried
	----------------------------------------*/

	,Tracker : { }

	/*--------------------------------------
		headings
		columns for EVERY archive table
	----------------------------------------*/

	,headings: [
		 {label:"Report Date", field:"DocumentDate", colwidth:160}
	]

	/*--------------------------------------
		altHeadings
		extra columns for specified archive tables
	----------------------------------------*/

	,altHeadings : {label:"Ratings", field:"RatingNormalized"}

	,csHeading : {label:"Headline", field:"Headline"}

	/*----------------------
		init()
	-----------------------*/

	,init : function() {

		Common.addTopLink(Element.create("a",{
			id:"tdamPageHelp",
			className:"iconWhatsNew",
			href:"#",
			target: "vendorLinks",
			Events:{
				type:"click",
				context:this,
				handler:this.popWhatsNew
			}
		}, "What's New?"));

		this.body = Element.parseSelector("table.WSODTable", "right", "first");
		this.attachEvents();
	}

	/*--------------------------------------
		showMainLoader()
		this is the loader
		that shows up over the table
	----------------------------------------*/

	,showMainLoader : function() {

		this.mainLoader = this.mainLoader || Element.get("reportLoader");

		var h = this.body.parentNode.offsetHeight;
			h = Math.round((h / 2) - 30) + "px";

		Element.setStyle(this.mainLoader, "top:"+h);
		Element.removeClass(this.mainLoader, "none");
	}

	/*--------------------------------------
		hideMainLoader()
		this is the loader
		that shows up over the table
	----------------------------------------*/

	,hideMainLoader : function() {

		if(this.mainLoader) {
			Element.addClass(this.mainLoader, "none");
		}
	}

	/*-----------------------------------
		attachEvents()
		attach ALL events for main content
		(not any side bars).
	-------------------------------------*/

	,attachEvents : function() {

		if(!this.body) {
			return;
		}

		//Events.add({
		//	 element: Element.get("reportsWhatsNew")
		//	,type:"click"
		//	,context:this
		//	,handler:this.popWhatsNew
		//});

		Events.add({
			 element:Element.parseSelector("a.closeLrg", "providerInfoPopup")
			,type:"click"
			,handler:this.closeProviderInfo
			,context:this
		});

		Events.add({
			 element:Element.parseSelector("thead .question", this.body)
			,type:"click"
			,handler:this.openInfoPopup
			,context:this
		});

		Events.add({
			 element:document.body
			,type:"click"
			,handler:this.closeArchive
			,context:this
		});

		Events.delegate(this.body, "click", {
			 selector:".hourGlass!disabled"
			,handler:this.handleArchives
			,context:this
		});

		Events.delegate(this.body, "click", {
			 selector:"a.next"
			,handler:this.handleArchives
			,context:this
			,data:{increment : 10}
		});

		Events.delegate(this.body, "click", {
			 selector:"a.previous"
			,handler:this.handleArchives
			,context:this
			,data:{increment : -10}
		});

		Events.delegate(this.body, "click", {
			 selector:"a.firstArchive"
			,handler:this.firstArchive
			,context:this
		});

		Events.delegate(this.body, "click", {
			 selector:"a.lastArchive"
			,handler:this.lastArchive
			,context:this
		});

		Events.delegate(document.body, "click", {
			 selector:".definitionLink"
			,handler:this.defineProvider
			,context:this
		});
	}

	/*-----------------------------------
		openInfoPopup()
		Open infoPopup for methodologies
		and approach
	-------------------------------------*/

	,openInfoPopup : function(e, el) {

		var th = Element.getParentBySelector(el, "th", true);

		if(Element.hasClass(th, "approach")) {
			return Common.openCenteredPopup( 'methodologyApproach', true, 1 );
		}
		Common.openCenteredPopup( 'methodologyApproach', true, 0 );
	}

	,popWhatsNew : function(e, el){
		e.cancel();
		window.open("tour/index.asp", "tourWindow", "location=1, status=1, scrollbars=1, width=1100, height=1000");
	}

	,firstArchive : function(e, el) {

		var cache = this.Tracker[el.getAttribute("provider")];
			cache.FirstRow = -10;

		return this.handleArchives(e, el, {increment:10});
	}

	,lastArchive : function(e, el) {

		var cache = this.Tracker[el.getAttribute("provider")];
			cache.FirstRow = cache.lastArchive - 10

		return this.handleArchives(e, el, {increment:10});
	}

	/*---------------------------------
		handleArchives()

		function for both opening
		and closing the archives.
		Also sets up remotings for
		archives.
	----------------------------------*/

	,handleArchives : function(e, el, data) {

		if(!data) {
			this.closeArchive();
		} else {
			el = Element.getParentBySelector(el, ".archiveContainer");
			el = el.parentNode;
			el = Element.parseSelector(".hourGlass", el)[0];
		}

		if(Element.hasClass(el, "hourGlass") && !data) {
			return;
		}

		var pDIV;

		if((pDIV = Element.getParentBySelector(el, ".hourGlass", true))) {

			var provider = pDIV.getAttribute("provider");
			var providerCache = this.Tracker[provider];

			if(!providerCache) {
				this.Tracker[provider] = {
					 provider:provider
					,FirstRow:0
					,RowCount:10
					,positioned:false
					,trigger:pDIV
					,firstArchive: 0
					,lastArchive: null
				};
				providerCache = this.Tracker[provider];
			}

			if(data && data.increment) {
				providerCache.FirstRow += ( data.increment );
			}

			var pTD     = Element.getParentBySelector(pDIV, "td");
			var archive = Element.parseSelector(".popbox", pTD, "first");

			this.openArchive( archive, {
				 FirstRow:providerCache.FirstRow
				,RowCount:providerCache.RowCount
				,provider:providerCache.provider
			}, data !== undefined);
		}
	}

	/*---------------------------
		openArchive()
		Open an already existing
		queried archive.
	----------------------------*/

	,openArchive:function(el, args, retrieveNew) {

		this.currentlyOpen = el;

		var prevOpen = Element.parseSelector("table", el);

		if(!prevOpen.length || retrieveNew) {
			return this.loadArchives(args, retrieveNew);
		}
		Element.removeClass(el, "none");
	}

	/*-------------------------
		loadArchives()
		Kick off buffer call
		to archive.
	--------------------------*/

	,loadArchives : function(args, retrieveNew) {

		this.Buffer = this.Buffer || new ContentBuffer();

		this.Buffer.abortRequests();

		if(retrieveNew) {

			//Independent archive loader

			var elem = Element.parseSelector(".loader", this.currentlyOpen)[0];
				elem.style.height = (this.currentlyOpen.offsetHeight - 10) + "px";	// Thank You IE for being a POS
			Element.removeClass(elem, "none");
		}
		else {
			//Global Report loader
			this.showMainLoader();
		}

		this.Buffer.load({
			debug: true
			,url: this.BUFFER_URL
			,method: "post"
			,contentType: "text/javascript"
			,context:this
			,preventEval:true
			,data:{
				data:DataFunctions.serializer.serialize(args)
			}
			,onload:  this.renderArchives
			,onerror: this.failSilently
		});
	}

	/*----------------------
		renderArchives()
	-----------------------*/

	,renderArchives : function(buffer) {

		var data = DataFunctions.serializer.deserialize(buffer.getResult());
		var container = Element.parseSelector(".container", this.currentlyOpen)[0];

		if(!Element.parseSelector("h3", container).length) {
			Element.create("h3", {}, data.headline, container);
		}

		var headings = Array.prototype.concat(this.headings);
			headings[0].colwidth = 160;

		var lengthAppend = "";
		var formatval = "DocumentDate";


		if("researchteam" == data.provider) {
			headings.push(this.altHeadings);
		} else if("creditsuisse" == data.provider) {
			headings[0].colwidth = 125;
			headings.unshift(this.csHeading);
			lengthAppend = "B";
			formatval = "Headline";
		}

		var results = data.data;
		var i = 0;
		var len = results.length;

		for(; i < len; i++) {

			results[i][formatval+"_format"] = [
				'<div class="iconBackground reportPdfLeft">'
					,'<div><a class="noDecorations" href="', results[i].href,'" onclick="pdf(this.href); return false;">'
						,results[i][formatval]
					,'</a></div>'
				,'</div>'
			].join("");
		}

		var table = new TableCreator_class({
			 headings:headings
			,data:results
			,tableClass:"noHeight"
			,parent:container
			,name:"test"
		});

		var providerCache = this.Tracker[data.provider];
			providerCache.lastArchive = data.lastArchive;

		var paging = Element.create("div", {className:"hasLayout pagingContainer textCenter"});

		if(data.current.first != 1) {
			Element.create("a", {href:"javascript:void(0);", className:"normal firstArchive smaller", provider:data.provider}, "&lt;&lt;", paging);
			Element.create("span", {}, "&nbsp;&nbsp;", paging);
		} else {
			Element.create("span", {className:"smaller lighter"}, "<<&nbsp;", paging);
		}

		if(data.showPrev) {
			Element.create("a", {href:"javascript:void(0)",className:"normal previous smaller"}, "&lt; Previous", paging);
		} else {
			Element.create("span", {className:"lighter smaller"}, "&lt; Previous", paging);
		}

		Element.create("span", {className:"smaller lighter"}, data.text, paging);

		if(data.showNext) {
			Element.create("a", {href:"javascript:void(0)",className:"normal next smaller"}, "Next &gt;", paging);
		} else {
			Element.create("span", {className:"smaller lighter"}, "Next &gt;", paging);
		}

		if(data.current.last != data.current.total) {
			Element.addChild(paging, "<span>&nbsp;&nbsp;</span>");
			Element.create("a", {href:"javascript:void(0);", className:"normal lastArchive smaller", provider:data.provider}, "&gt;&gt;", paging);
		} else {
			Element.create("span", {className:"smaller lighter"}, "&nbsp;&nbsp;&gt;&gt;", paging);
		}

		Element.remove(Element.parseSelector(".pagingContainer", container));
		Element.remove(Element.parseSelector("table", container));

		var table = table.draw();
		Element.addChild(container, paging);

		var cache = this.Tracker[data.provider];

		if(!cache.positioned) {
			this.positionArchive(container, cache, headings.length + lengthAppend);
		}

		this.hideMainLoader();

		var loader = Element.parseSelector(".loader", this.curretlyOpen);
		Element.addClass(loader, "none");
		Element.removeClass(this.currentlyOpen, "none");
	}

	/*----------------------
		positionArchive()
		They are set in an
		odd place per design.
		This handles that.
	-----------------------*/

	,positionArchive : function(container, cache, widthAppend) {

		// cannot be dynamic without being a serious pain b/c
		// of tables in IE expanding to the parent width

		var width = ( this["COL_WIDTH_" + (widthAppend)] );
		var widthDif = (cache.trigger.lastChild.offsetLeft + cache.trigger.lastChild.offsetWidth - 28);

		if(Element.hasClass(document.body, "msie")) {
			widthDif += 10;	// B/C of IE padding calc includes
		}

		this.currentlyOpen.style.width = (width + 30) + "px";	// 30 for padding
		this.currentlyOpen.style.left  = (((width + 30) - widthDif) * -1) + "px";
		container.style.width = width + "px";
		cache.positioned = true;
	}

	/*-------------------------
		failSilently()
		Let us know something
		failed in the request
		per FireBug.
	--------------------------*/

	,failSilently : function() {
		if(window.console && console.log) {
			console.log("Error loading results");
		}
	}

	/*----------------------
		closeArchive()
	-----------------------*/

	,closeArchive:function(e, container) {

		if(e) {

			var el = e.getTarget();
			var archiveClicked = Element.is(el, ".archiveContainer", container, true);

			if(archiveClicked && !Element.hasClass(el, "closeSml")) {
				return;
			}

			var parent = Element.getParentBySelector(el, ".hourGlass", true);
			var isArch = Element.hasClass(el, "hourGlass") || Element.hasClass(el, "paginglink");

			if(isArch || parent) {
				return;
			}
		}

		if(this.currentlyOpen) {
			Element.addClass(this.currentlyOpen, "none");
			this.currentlyOpen = false;
		}
	}

	,providerInfo : { }

	/*----------------------
		defineProvider()
	-----------------------*/

	,defineProvider : function(e, el) {

		var key = el.getAttribute("key");
		
		if(!key) {
			return;	
		}
		this.closeProviderInfo();
		this.activeProviderInfo = el;
		this.getProviderInfo(key);
	}

	/*----------------------
		getProviderInfo()
	-----------------------*/

	,getProviderInfo : function(key) {

		this.ProviderBuffer = this.ProviderBuffer || new ContentBuffer();
		this.ProviderBuffer.abortRequests();

		this.showMainLoader();

		this.ProviderBuffer.load({
			 debug: true
			,url: this.PROVIDER_DATA_URL
			,method: "post"
			,contentType: "text/javascript"
			,context:this
			,preventEval:true
			,data:{key : key}
			,onload:  this.renderProviderInfo
			,onerror: this.failSilently
		});
	}

	/*----------------------
		closeProviderInfo()
	-----------------------*/

	,closeProviderInfo : function() {

		if(this.activeProviderInfo) {
			Element.addClass( this.providerInfo.element, "none" );
			this.activeProviderInfo = null;
		}
	}

	/*-------------------------
		renderProviderInfo()
	--------------------------*/

	,renderProviderInfo : function(oBuffer, key) {

		if(oBuffer && oBuffer.getResult) {

			var data = oBuffer.getResult();
				data = DataFunctions.serializer.deserialize(data);

			this.providerInfo[data.key] = data;
		} else {
			var data = 	this.providerInfo[key];
		}

		if(!this.providerInfo.element) {
			this.providerInfo.element = Element.get("providerInfoPopup");
		}

		var pLink = this.activeProviderInfo;
		var pos   = pLink.offsetTop + 20;

		Element.setHTML(this.providerInfo.element.lastChild, this.providerInfo[data.key].Description);
		Element.setStyle(this.providerInfo.element, "top:"+pos+"px;right:0;left:50px;");
		Element.removeClass(this.providerInfo.element, "none");

		this.hideMainLoader();
	}
}

loadBuffer.add(function(){
	window.stockReports = new StockReports();
	window.stockReports.init();
});
