
/*
FILE CONCAT ADD FILE
PATH: /ft/resources/client/editorial/EditorialSymbolSearch.js
*/
//Nothing to do with interactive charting, this is for the interactive chart landing page
var preload = Events.add("preload");
//SymbolSearch.prototype.REQUEST_URL = "/ft/symbolSearch/data/getSymbolsEditorial.asp";
var EditorialSymbolSearch = function(){
	EditorialSymbolSearch.Super(this);
	var REQUEST_URL = "/ft/symbolSearch/data/getSymbolsEditorial.asp";
	this.setRequestURL(REQUEST_URL);
	//overwrite
	this.FORM_INPUT_SELECTOR = "input[searchtype='query']";

	this.searchFormID = 'searchBoxForm';
	this.parentObject = null;

}; 

EditorialSymbolSearch.Extend(SymbolSearch);

//?Testing to see if we can get parent
EditorialSymbolSearch.prototype.setEditorialParent = function(parentObject)
{
	this.parentObject = parentObject;
}

//Since this is a dynamic page, events can only be attached once elements exist
EditorialSymbolSearch.prototype.associateBehavior = function()
{
		this.setForm(Element.get('searchBoxForm'));
		this.setRequestor(new ContentBuffer());
}

//EditorialSymbolSearch.prototype.REQUEST_URL = "/ft/symbolSearch/data/getSymbolsEditorial.asp";
EditorialSymbolSearch.prototype.handleResults = function(query, results, showMoreLink, inputId) {

	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 elFlag = Element.create("div");
				Element.addClass(elFlag, this.CSS_FLAG);
				Element.addClass(elFlag, this.CSS_FLAG_COUNTRY + c.c);
		
				var elRow = Element.create("tr", { inputid: inputId, symbol: c.s, isfund: c.f, issueid: c.w}, [
					Element.create("td", { "class": this.CSS_ISSUE_NAME }, c.n),
					Element.create("td", null, elFlag),
					Element.create("td", null, c.d)
				], elTbody);
				
				if (group.length-1 == j && (results.length -1 != i || showMoreLink)) {
					Element.addClass(elRow, this.CSS_GROUP_END);
				}

			}
			Element.addChild(elTable, elTbody);
		}
	}
	
	//Get rid of show more link for now, Comment back if need more links
	/*
	if (showMoreLink) {
		Element.create("tbody", null, [
			Element.create("tr", { "class": this.CSS_MORE_LINK }, [
				Element.create("td", { "colspan":3 }, [
					Element.create("a", { "class":this.CSS_MORE_SEARCH_RESULTS, href: this.moreResultsPopupMode() ? "#" : this.buildMoreLink() }, "Additional matches for " + query + " &gt;")
				])
			])
		], 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, inputId);
};


EditorialSymbolSearch.prototype.selectResult = function(e, el) {
	
	if ("click" == e.nativeEvent.type || this.KEY_CODE_ENTER == e.nativeEvent.keyCode) {
		e.cancel();
	
		if (this.selectedRow == -1) {
			if (this.elResultRows && 1 == this.elResultRows.length) {
				// only one result, set it as selected
				this.selectedRow = 0;
			}
			else {
				// multiple results, just submit the form
				//TO DO: Check what changes required here
				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;
			}
		}		
		// go to selected row
		var symbol = this.elResultRows[this.selectedRow].getAttribute("symbol");
		var isfund = (this.elResultRows[this.selectedRow].getAttribute("isfund") == "1");
		var issueId = this.elResultRows[this.selectedRow].getAttribute("issueid");
		var inputId = this.elResultRows[this.selectedRow].getAttribute("inputid");
		
		//first portion is query
		var inputElement = Element.get(inputId);
		var inputTag = "query";
		var inputTagIndex = inputId.indexOf(inputTag);
		var queryNumber = inputId.substring(inputTagIndex + inputTag.length, inputId.length);
		var elementId = "Equity" + queryNumber;
		var variableType = inputElement.getAttribute("variableType");
		if(variableType && variableType == "indexQuery")
		{
			elementId = "InputIndex" + queryNumber;
		}
		var symbol = this.elResultRows[this.selectedRow].getAttribute("symbol");
		this.go(
			this.elResultRows[this.selectedRow].getAttribute("symbol"), 
			(this.elResultRows[this.selectedRow].getAttribute("isfund") == "1"),
			elementId,
			issueId,
			inputId, e, inputElement
		);
	}
};

EditorialSymbolSearch.prototype.setHiddenIssueId = function(elementId, issueId)
{
	var issueIdElement = Element.get(elementId);
	if(issueIdElement)
	{
		issueIdElement.value = issueId;
	}
}

EditorialSymbolSearch.prototype.go = function(symbol, isFund, issueIdElement, issueId, queryInputId, e, el) {

	if (symbol) {
		this.query = symbol;
		//should be issue id now
		if(issueIdElement)
		{
			this.setHiddenIssueId(issueIdElement, issueId);	
			Element.get(queryInputId).value = symbol;
			Element.get(queryInputId).setAttribute("selected", "true");
			//Anyway to 'Trigger' ?
			if(this.parentObject != null)
			{
				this.parentObject.handleSelectVariable(e, el);
			}
		}
		//Get correct input id
	}
	//Original method checked whether or not this is a fund
	this.clearResults();
	
};


//We now have multiple inputs
EditorialSymbolSearch.prototype.setForm = function(elForm) {
	this.clearInputEventHandlers();
	
	this.elForm = elForm || Element.get(this.DEFAULT_FORM_ID);
	//elInput is now an array
	this.elInput = Element.parseSelector(this.FORM_INPUT_SELECTOR, this.elForm);
	this.addInputEventHandlers();
};

//Attempt: Add new generated input
EditorialSymbolSearch.prototype.addSearchElements = function(newSearchElement) {
	this.eventManager.add(newSearchElement, "keyup", this.search, this, null, this.KEY_PRESS_WAIT);
	this.eventManager.add(newSearchElement, "click", function(e) {
		e.cancel();
	});
};

EditorialSymbolSearch.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();
	});
};


EditorialSymbolSearch.prototype.search = function(e, el) {
	var elementId = el.id;
	
	//if search box has been emptied, resend event to handle 
	if(el.value == "")
	{	
		this.parentObject.handleSelectVariable(e, el);
	}
	
	//Based on element 
	if(el.getAttribute("variableType") && el.getAttribute("variableType") == "indexQuery")
	{
		this.setIssueType(this.ISSUE_TYPES["IN"]);
	}
	else {
		this.setIssueType(this.ISSUE_TYPES["ALL"]);
	}
	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], el.id);

		}
		else {
			this.requestor.load({
				url: this.requestURL,
				contentType: "text/javascript",
				data: { q: this.query, issueType: this.issueType, inputid: elementId, callback: "handleResults", context: "this" },
				context: this
			});
		}
	}	

};

//Set x and y according to which input selected
EditorialSymbolSearch.prototype.drawResults = function(cachedNodes, inputId) {
	this.clearResults();
	
	if (!this.elResults) {
		this.createResultsContainer(); 

	}

	var pos = Element.getXY(inputId);
	var size = Element.getSize(inputId);
	
	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.elMoreResults = Element.parseSelector("a.searchResultsMoreLink", this.elResults, "first");
	
	this.addResultEvents(cachedNodes[0].getAttribute(this.ATTR_NO_RESULTS));
	
	WCH.Apply(this.elResults, null, true);
};
/*
FILE CONCAT ADD FILE
PATH: /ft/resources/client/modules/InvestmentBanking/tablesAndTrends.js
*/

var TablesAndTrends_class = function() {}


TablesAndTrends_class.prototype.TABLES_AND_TRENDS_BUFFER_URL = '/ft/resources/buffer/investmentBanking/TablesAndTrends.asp';
TablesAndTrends_class.prototype.TABLES_AND_TRENDS_DROP_DOWN_MAP = {
	'Value': {
		'All': false,
		'Bonds': {'Display': 'Bonds', 'Value': 'Bonds'},
		'Equity': {'Display': 'Equity', 'Value': 'Equity'},
		'Loans': {'Display': 'Loans', 'Value': 'Loans'},
		'MA': {'Display': 'Mergers &amp; Acquisitions', 'Value': 'MA'}
	},
	'Fees': {
		'All': {'Display': 'All', 'Value': 'All'},
		'Bonds': {'Display': 'Bonds', 'Value': 'Bonds'},
		'Equity': {'Display': 'Equity', 'Value': 'Equity'},
		'Loans': {'Display': 'Loans', 'Value': 'Loans'},
		'MA': {'Display': 'Mergers &amp; Acquisitions', 'Value': 'MA'}
	}
}

TablesAndTrends_class.prototype.init = function() {
	WSDOM.Events.add(Element.parseSelector(".investmentBankingModule select", "wsod"), "change", this.getTablesAndTrends, this);
	WSDOM.Events.add(Element.parseSelector("input.radio", "wsod"), "click", this.getTablesAndTrends, this);
	
	this.showOrHideLogos();
}

TablesAndTrends_class.prototype.getInputValues = function() {

		elTimeframeSelect = Element.get('selectTimeframe');
		sTimeframe = $ws(elTimeframeSelect).find("option:selected");
	
	return {
		'Period': $ws(sTimeframe).val(),
		'Timeframe': $ws(sTimeframe).attr("data-end-date"),
		'Display': Element.get("selectDisplay").value,
		'AssetClass': Element.get("selectAssetClass").value,
		'DealType': Element.get("chooseDealValue").checked ? 'Value' : 'Fees'
	}
}

TablesAndTrends_class.prototype.updateDateDisclaimer = function() {
	var elDateDisclaimer = Element.get('dateDisclaimer'),
		elTimeframeSelect = Element.get('selectTimeframe'),
		sTimeframe = $ws(elTimeframeSelect).find("option:selected");
		sDataFrom = $ws(sTimeframe).attr("data-from");
		sDataAsOf = $ws(sTimeframe).attr("data-as-of");
		
		
		$ws("#dataFrom").html(sDataFrom + "<br/> * No activity in comparable period");
		$ws("#dataAsOf").html(sDataAsOf);
}

TablesAndTrends_class.prototype.updateDropDownOptions = function() {
	var elDealValue = Element.get('chooseDealValue'),
		elFees = Element.get('chooseFees'),
		elAssetClass = Element.get("selectAssetClass"),
		rAssetClassOptions = Element.parseSelector("option", elAssetClass),
		sAssetClass = elAssetClass.value,
		sDealType = elDealValue.checked ? 'Value' : 'Fees',
		sOtherDealType = 'Value' == sDealType ? 'Fees' : 'Value',
		elRadioOther = Element.parseSelector("input[value='"+sOtherDealType+"']", "dealValueAndFeesFieldset", "first"),
		elSelect = Element.create("select", {'id':'selectAssetClass'}),
		oOptions = {},
		elOption;
	
	if (this.TABLES_AND_TRENDS_DROP_DOWN_MAP[sDealType]) {
		for (var i = 0; i < rAssetClassOptions.length; i++) {
			oOptions[rAssetClassOptions[i].value] = rAssetClassOptions[i];
		}
		
		for (var i in this.TABLES_AND_TRENDS_DROP_DOWN_MAP[sDealType]) {
			if (oOptions[i] && !this.TABLES_AND_TRENDS_DROP_DOWN_MAP[sDealType][i]) {
				Element.remove(oOptions[i]);
			} else if (oOptions[i]) {
				// Ignore this case
			} else if (this.TABLES_AND_TRENDS_DROP_DOWN_MAP[sDealType][i]) {
				for (var j in oOptions) {
					Element.insertBefore(Element.create("option", {"value":this.TABLES_AND_TRENDS_DROP_DOWN_MAP[sDealType][i].Value}, this.TABLES_AND_TRENDS_DROP_DOWN_MAP[sDealType][i].Display), oOptions[j]);
					break;
				}
			}
		}
	}
	
	if (elRadioOther) {
		if (this.TABLES_AND_TRENDS_DROP_DOWN_MAP[sOtherDealType] && this.TABLES_AND_TRENDS_DROP_DOWN_MAP[sOtherDealType][sAssetClass]) {
			elRadioOther = Element.parseSelector("input[value='"+sOtherDealType+"']", "dealValueAndFeesFieldset", "first");
			
			if (elRadioOther.disabled) {
				elRadioOther.disabled = false;
			}
		} else {
			elRadioOther.disabled = true;
		}
	}
}

TablesAndTrends_class.prototype.getTablesAndTrends = function() {
	var oParams = this.getInputValues();
	
	this.updateDateDisclaimer();
	this.updateDropDownOptions();
	
	this.loading = this.loading || new LoadingOverlay(Element.get('tablesAndTrendsContainer'))
	this.loading.showLoading();
	
	this.cb = this.cb || new ContentBuffer();
	this.cb.abortRequests();
	this.cb.load(
		{
			 contentType: 'text/javascript'
			,context:     this
			,data:        {
				data: Common.getSerializer().serialize(oParams)
			}
			,onload:      this.loadTablesAndTrends
			,onerror:     this.onError
			,preventEval: true
			,url:         this.TABLES_AND_TRENDS_BUFFER_URL
		}
	);
}

TablesAndTrends_class.prototype.loadTablesAndTrends = function(cb) {
	this.loading = this.loading || new LoadingOverlay(Element.get('tablesAndTrendsContainer'))
	this.loading.hideLoading();
	
	this.showOrHideLogos();
	
	var oResult = Common.getSerializer().deserialize(cb.getResult());
	
	Element.setHTML("tablesIBContainer", oResult.Tables);
	
	if (oResult.Trends) {
		Element.setHTML("trendsIBcontainer", oResult.Trends);
		Element.removeClass(Element.parseSelector("div.trendsModule", "wsod"), "wsodHidden");
	} else {
		Element.addClass(Element.parseSelector("div.trendsModule", "wsod"), "wsodHidden");
	}
}

TablesAndTrends_class.prototype.onError = function() {
	alert('There was an error with your request.  Please try again.');
	
	this.loading.hideLoading();
}

TablesAndTrends_class.prototype.showOrHideLogos = function() {
	var elParent = WSDOM.Element.get('dealValueAndFeesFieldset')
		,elChecked = WSDOM.Element.parseSelector('INPUT[checked=.`true`]', elParent, 'first')
		,elSelect = WSDOM.Element.get('selectAssetClass')
		,logoThomsonReuters = WSDOM.Element.get('logoThomsonReuters')
		,logoThomsonReutersLPC = WSDOM.Element.get('logoThomsonReutersLPC')
		,logoFreemanConsulting = WSDOM.Element.get('logoFreemanConsulting')
		,additionalTRFeedsDisclaimer = WSDOM.Element.get("additionalTRFeesDisclaimer");
		
	if (elChecked) {
		switch(elChecked.value) {
			case 'Fees':
				WSDOM.Element.addClass(logoThomsonReutersLPC, 'hidden');

				WSDOM.Element.removeClass(logoThomsonReuters, 'hidden');
				WSDOM.Element.removeClass(logoFreemanConsulting, 'hidden');
				WSDOM.Element.removeClass(additionalTRFeedsDisclaimer, "wsodHidden");
				
				break;

			case 'Value':
				WSDOM.Element.addClass(logoFreemanConsulting, 'hidden');
				WSDOM.Element.addClass(additionalTRFeedsDisclaimer, "wsodHidden");

				if ('Loans' == elSelect.value) {
					WSDOM.Element.addClass(logoThomsonReuters, 'hidden');
					WSDOM.Element.removeClass(logoThomsonReutersLPC, 'hidden');
				}
				else {
					WSDOM.Element.addClass(logoThomsonReutersLPC, 'hidden');
					WSDOM.Element.removeClass(logoThomsonReuters, 'hidden');
				}
				
				break;

			default:
				// to be determined
		}
	}
}