var CM = new Object();
var chartPropsKey = "Chart_";
if(ajaxCharts_chartsPerRow > 4 || ajaxCharts_chartsPerRow < 1) ajaxCharts_chartsPerRow = 1;

var onThumbnailsChange = null;
//STUDY KEYS					// paramaters [Pn](paramater n=number) (n)=param/default(none supplied)
BID_ASK_SPREAD			="Bid-Ask"; // Options
BOLLINGER_BAND			="BB"; 		//[P1]Duration: 	(n)/20 bars		[P2]Std. Dev: 	(n)/2 	 
COMMODITY_CHANNEL		="CCI_BS";	//[P1]Time Periods: (n)/18 bars 	  	 
HIST_IMP_VOLATILITY		="HistImpVol" //Options
MACD_HISTOGRAM			="MACDH_BS";//[P1]1st MA: 		(n)/8 bars 		[P2]2nd MA: 	(n)/17 bars			[P3]3rd MA: (n)/9 bars
MOMENTUM_HISTOGRAM		="MOM_BS";	//[P1]Stk MA: 		(n)/21 bars 	[P2]Distance:	(n)/22				[P3]Mom MA: (n)/7 bars
MOVING_AVERAGE			="MA_BS";	//[P1]Length: 		(n)/30 bars
MOVING_AVERAGE_EXP		="EMA_BS";	//[P1]Length: 		(n)/30 bars
NEGATIVE_VOLUME_INDEX	="NVI";		//NONE	  	  	 
ON_BALANCE_VOLUME		="IOBV";	//NONE	 
OPEN_INTEREST			="OpenInt" 	// Options 	  	 
POSITIVE_VOLUME_INDEX	="PVI";		//NONE	  	  	 
STOCHASTICS_VALUE 		="STO_BS";	//[P1]Length: 		(n)/14 bars 	[P2]1st MA: 	(n)/5 bars 			[P3]2nd MA: (n)/0 bars
WILDER_RSI_VALUE		="RSI_BS";	//[P1]Length: 		(n)/14 bars 	[P2]1st MA: 	(n)/2 bars 	 
INSIDER_TRADING			="IT";		//NONE

var showPopCharts = true;
var chartProfileOnLoaded = null;
var chartProfileOnSaved = null;
var chartProfileOnDeleted = null;
/* Example useages this is what I was using to test.
window.onload = test;
chartProfileOnLoaded = test2;
chartProfileOnSaved = test3;
function test(){
	myChartProfile.loadById("blah");
	alert("loaded");
	getCharts(null, null);
	alert("gotcharts");
} 
function test2(profile){
	alert("test2");
	profile.save();
	alert("test2 out");
}
function test3(xml){
	alert(xml);
}
*/
var chartsWasOn = (ajaxCharts_chartsOn && ajaxCharts_chartsPerRow > 0);
//function alertMessage(message){
//	document.getElementById("resultSize").innerHTML = message;
//}
var elementTypes = new Array("i", "s");
function recieveStyle(){
	var xml = this.req.responseXML;
	var mainresponse = xml.getElementsByTagName("response")[0];
	if(mainresponse == null) return;
	var error = mainresponse.getElementsByTagName("error");
	if (error!=null&&error[0]!=null){
		//alert(error[0].getAttribute("message"));
		return;
	}	
	var style = mainresponse.getElementsByTagName("liteStyle")[0];
	var model = style.getElementsByTagName("ChartModel")[0];
	var children = model.childNodes;
	var profileId = "snapshot";//mainresponse.getAttribute("profileId");
	var id = mainresponse.getAttribute("id");
	
	var profile = getProfile(profileId);
	//profile = new CM.ChartManager.ChartProfile(profileId);
	profile.id = id;

	for(var i=0; i<children.length; i++){
		var value = null;
		var child = children[i];
		if(child.tagName == null || child.tagName.indexOf("jc2") != 0) continue;
		var bElements = child.getElementsByTagName("b");
		if(bElements.length > 0){
			val = bElements[0].childNodes[0].nodeValue;
			if(val == "0"){
				value = false;
			} else {
				value = true;
			}
		}
		var sElements = child.getElementsByTagName("s");
		if(sElements.length > 0){
			value = sElements[0].childNodes[0].nodeValue;
		}
		var tag = child.tagName;
		if(tag == "jc2.hideStudyLegends"){
			profile.hideStudyLegends = value;
		}else if(tag == "jc2.hideEvents"){
			profile.hideEvents = value;
		}else if(tag == "jc2.hideVolume"){
			profile.hideVolume = value;
		}else if(tag == "jc2.showCompanyInfo"){
			profile.companyInfo = value;
		}else if(tag == "jc2.logScale"){
			profile.logScale = value;
		}else if(tag == "jc2.barStyle"){
			profile.barStyle = value;
		}else if(tag == "jc2.showlastvalue"){
			profile.showLastValue = value;
		}else if(tag == "jc2.durCode"){
			var props = child.getElementsByTagName("Properties")[0];
			profile.durIntraday = props.getAttribute("intraday");
			profile.durationCode = props.getAttribute("code");
			profile.durationTitle = props.getAttribute("title");
			profile.freqCode = props.getAttribute("defaultfreq");
		}else if(tag == "jc2.freqCode"){
			var props = child.getElementsByTagName("Properties")[0];
			profile.freqIntraday = props.getAttribute("intraday");
			profile.freqMinutes = props.getAttribute("minutes");
			profile.freqCode = props.getAttribute("code");
			profile.freqTitle = props.getAttribute("title");
		}
	}
	var studies = style.getElementsByTagName("Study");
	profile.removeAllStudies();
	for(var i = 0; i < studies.length; i++){
		var study = studies[i];
		var studyString = study.getAttribute("spec");
		var vals = studyString.split(" ");
		var name = vals[0];
		var att1 = null;
		var att2 = null;
		var att3 = null;
		if(vals.length > 1){
			att1 = vals[1];
			if(vals.length > 2){
				att2 = vals[2];
				if(vals.length > 3){
					att3 = vals[3];
				}
			}
		}
		profile.createAndAddStudy(name, att1, att2, att3);
	}
	if(chartProfileOnLoaded != null)
		chartProfileOnLoaded.call(this, profile);
	
}
function recieveSaved(){
	var xml = this.req.responseXML;
	var mainresponse = xml.getElementsByTagName("response")[0];
	if(chartProfileOnSaved != null){
		chartProfileOnSaved.call(this, mainresponse);
	}
}
function recieveDeleted(){
	var xml = this.req.responseXML;
	var mainresponse = xml.getElementsByTagName("response")[0];
	var id = mainresponse.getAttribute("id");
	if(chartProfileOnDeleted != null){
		chartProfileOnDeleted.call(this, mainresponse);
	}
}
ChartStudy = function(key, param1, param2, param3){
	this.key = key;
	this.params = null;
	if(param1 != null){
		this.params = new Array();
		this.params.push(param1);
	}else return;
	if(param2 != null){
		this.params.push(param2);
	}else return;
	if(param3 != null){
		this.params.push(param3);
	}
}
ChartStudy.prototype = {
	toXML:function() {
		var xml = new Array();
		xml.push("<Study spec='");
		xml.push(this.key);
		if(this.params != null){
			xml.push(" ");
			xml.push(this.params.join(" "));
		}
		xml.push("'/>");
		return xml.join("");
	}
}
Comparison = function(symbol){
	this.symbol = symbol;
}
Comparison.prototype = {
	toXML:function() {
		var xml = new Array();
		xml.push("<Study spec='COMPARISON ");
		xml.push(this.symbol);
		xml.push("'/>");
		return xml.join("");
	}
}
function showThumbnails(on){
	pops = new Array();
	savePreference(chartPropsKey+"chartsOn", on);
	ajaxCharts_chartsOn = on;
	if(onThumbnailsChange != null){
		onThumbnailsChange.call(this);
	}
	chartsWasOn = (ajaxCharts_chartsOn && ajaxCharts_chartsPerRow > 0);
}
function chartsOnlyOn(on){
	savePreference(chartPropsKey+"chartsOnly", on);
	ajaxCharts_chartsOnly = on;
	if(onThumbnailsChange != null){
		onThumbnailsChange.call(this);
	}
	chartsWasOn = (ajaxCharts_chartsOn && ajaxCharts_chartsPerRow > 0);
}
function changeChartsPerRow(number){
	savePreference(chartPropsKey+"chartsPerRow", number);
	ajaxCharts_chartsPerRow = number;
	if(onThumbnailsChange != null){
		onThumbnailsChange.call(this);
	}
	chartsWasOn = (ajaxCharts_chartsOn && ajaxCharts_chartsPerRow > 0);
	
}
function chartsStudiesOn(on, profileId){
	var profile = getProfile(profileId);
	profile.hideStudyLegends = !on;
	savePreference(chartPropsKey+"chartStudies", on);
	clearCharts();
	getCharts(null, null);
}
function chartsEventsOn(on, profileId){
	var profile = getProfile(profileId);
	profile.hideEvents = !on;
	savePreference(chartPropsKey+"chartEvents", on);
	clearCharts();
	getCharts(null, null);
}

function chartsVolumeOn(on, profileId){
	var profile = getProfile(profileId);
	profile.hideVolume = !on;
	savePreference(chartPropsKey+"chartVolume", on);
	clearCharts();
	getCharts(null, null);
}
		
CM.ChartManager = function(){
	CM.chartManager = this;
	this.chartProfiles = new Array();
	this.charts = new Array();	
}

CM.ChartManager.prototype = {
	
	getChartProfile:function(profileId) {
		for(var i = 0; i < this.chartProfiles.length; i++)
			if(this.chartProfiles[i].id == profileId){
				return this.chartProfiles[i];
			}
		return null;
	},
	getChart:function(chartId){
		return this.charts[chartId];
	}
	
}
new CM.ChartManager();
CM.ChartManager.ChartProfile = function(id){
	CM.chartManager.chartProfiles.push(this);
	this.backgroundColor = "255,255,255,255";
	this.studies = new Array();
	this.comparisons = new Array();
	this.createAndAddStudy(MOVING_AVERAGE);
	this.createAndAddStudy(STOCHASTICS_VALUE);
	this.createAndAddStudy(MACD_HISTOGRAM);
	this.hideStudyLegends = !ajaxCharts_chartStudies;
	this.hideEvents = !ajaxCharts_chartEvents;
	this.hideVolume = !ajaxCharts_chartVolume;
	this.companyInfo = true;
	this.logScale = "1";
	this.barStyle = "OHLC";
	this.freqIntraday = false;
	this.durIntraday = false;
	this.durationCode = "6m";
	this.durationTitle = "6 Mo";
	this.defaultFreq = 0;
	this.freqMinutes = 1440;
	this.freqCode = "d";
	this.freqTitle = "D   ";
	this.showLastValue = true;
	this.id = id;
	this.width = 300;
	this.height = 220;
}
CM.ChartManager.ChartProfile.prototype = {
	loadById:function(id, chartType){
		if(id == null) id = this.id;
		if(this.name == null) this.name = "";
		var xml = "<"+"request name='loadStyle'><id>"+id+"</id><type>"+chartType+"</type></request>";
		chartsActiveReq = new CATS.RequestMaker(contextPath + '/ajaxbridge/chartStyles.iedu', 
		recieveStyle, null, xml, false, null);
		chartsActiveReq.loadXMLDoc();
	},
	save:function(id, name, chartType, dontUpdateStyles){
		if(id != null) this.id = id;
		if(name != null) this.name = name;
		if (dontUpdateStyles == null) dontUpdateStyles = false;
		var xml = "<"+"request name='saveStyle' updateStyles='"+(!dontUpdateStyles)+"'><name>"+this.name+"</name><id>"+id+"</id><type>"+chartType+"</type><liteStyle>"+getChartModel(this)+this.getStudyNodes()+"</liteStyle></request>";
		chartsActiveReq = new CATS.RequestMaker(contextPath + '/ajaxbridge/chartStyles.iedu', 
		recieveSaved, null, xml, false, null);
		chartsActiveReq.loadXMLDoc();
	},
	deleteStyle:function(id, chartType){
		if (id==null) return;
		var xml = "<"+"request name='deleteStyle'><id>"+id+"</id><type>"+chartType+"</type></request>";
		chartsActiveReq = new CATS.RequestMaker(contextPath + '/ajaxbridge/chartStyles.iedu', 
		recieveDeleted, null, xml, false, null);
		chartsActiveReq.loadXMLDoc();
	},
	addStudy:function(study){		
		this.studies[study.key] = study;
	},
	getStudy:function(key){
		return this.studies[key];
	},
	getStudies:function(){
		return this.studies;
	},
	removeStudyKey:function(key){
		this.studies[key] = null;
	},
	removeStudy:function(study){
		this.removeStudyKey(study.key);
	},
	removeAllStudies:function(){
		this.studies = new Array();
	},
	createAndAddStudy:function(key, param1, param2, param3){
		var study = new ChartStudy(key, param1, param2, param3);
		this.addStudy(study);
	},
	addComparisonSymbol:function(symbol){
		this.comparisons[symbol] = new Comparison(symbol);
	},
	removeComparisonSymbol:function(symbol){
		this.comparisons[symbol] = null;
	},
	removeAllComparisonSymbols:function(){
		this.comparisons = new Array();
	},
	getShowLastValueNode:function(){
		var val = (this.showLastValue)? "1" : "0";
		return "<jc2.showlastvalue><b>"+val+"</b></jc2.showlastvalue>";
	},
	getFrequencyNode:function(){
		return (this.freqCode!=null)? 
				"<jc2.freqCode><XmlSerializable><Properties intraday='"+this.freqIntraday+"' minutes='"+this.freqMinutes+"' code='"+this.freqCode+"' title='"+this.freqTitle+"'/></XmlSerializable></jc2.freqCode>" : "";
	},
	getDurationNode:function(){
		return "<jc2.durCode><XmlSerializable>"+
			"<Properties intraday='"+this.durIntraday+"' defaultfreq='"+this.defaultFreq+"' code='"+this.durationCode+"' custom='false' "+
			"title='"+this.durationTitle+"' days='-1'/></XmlSerializable></jc2.durCode>";
	
	},
	getBarStyleNode:function(){
		return "<jc2.barStyle><s>"+this.barStyle+"</s></jc2.barStyle>";
	},
	getLogScaleNode:function(){
		var val = (this.logScale)? "1" : "0";
		return "<jc2.logScale><b>"+val+"</b></jc2.logScale>";
	},
	getSizeNode:function(){
		return "<Size width='"+this.width+"' height='"+this.height+"'/>";
	},
	getStudyNodes:function(){
		if(this.hideStudyLegends) return "";
		var ret = new Array();
		for (var study in this.studies){
			if (this.studies[study]==null) continue;
			ret.push(this.studies[study].toXML());
		}
		return ret.join("");
	},
	getComparisonNodes:function(){
		var ret = new Array();
		for (var compare in this.comparisons){
			if (this.comparisons[compare]==null) continue;
			ret.push(this.comparisons[compare].toXML());
		}
		return ret.join("");
	},
	getHideNodes:function(){
		var returnStr = "";
		var legends = (this.hideStudyLegends)? "1" : "0";
		var events = (this.hideEvents)? "1" : "0";
		var volume = (this.hideVolume)? "1" : "0";
		var companyInfo = (this.companyInfo)? "1" : "0";
		return "<jc2.hideStudyLegends><b>"+legends+"</b></jc2.hideStudyLegends>"+
				"<jc2.hideEvents><b>"+events+"</b></jc2.hideEvents>"+
				"<jc2.hideVolume><b>"+volume+"</b></jc2.hideVolume>"+
				"<jc2.showCompanyInfo><b>"+companyInfo+"</b></jc2.showCompanyInfo>";
	}
}
CM.ChartManager.Chart = function(symbol, url){
	CM.chartManager.charts[symbol] = this;
	this.id = symbol;
	this.url = url;
	this.map = null;
}
CM.ChartManager.Chart.Map = function(mapXML, symbol){
	this.html = "<map id='map_"+symbol+"' name='map_"+symbol+"' >";
	var events = mapXML.getElementsByTagName("ChartStockEvent");
	for(var i = 0; i< events.length; i++){
		attrs = events[i].attributes;
		var description = attrs.getNamedItem("description").value;
		var coords = attrs.getNamedItem("area").value;
		var href = attrs.getNamedItem("url");
		this.html+="<area shape='rect' coords='"+coords+"' ";
		this.html+= "onMouseover='ddrivetip(\""+description+"\", 300)'";
		this.html+= " onMouseout='hideddrivetip()'";
		if(href != null)
			this.html += " href='javascript:openEvent(\""+href.value+"\")'>";
		else this.html += ">";
	}
	this.html+="</map>";
}
var requestQue = new Array();
var lastSymbols = "";
var lastProfile = null;

var chartOverride = null;

function getCharts(symbols, chartProfile, force){
//	debugger;
	if(chartProfile == null){
		chartProfile = lastProfile;
	} else {
		lastProfile = chartProfile;
	}
	if(symbols == null){
		symbols = lastSymbols;
	} else {
		lastSymbols = symbols;
	}
	if(chartProfile == null) return;
	if(symbols == null) return;
	requestQue = new Array();
	symbolSets = new Array();
	var symbolSet = new Array();
	for(var i = symbols.length-1; i > -1; i--){
		symbolSet.push(symbols[i]);
	}
	if(symbolSet.length > 0){
		authkey = GetCookie('chartKey');
		if (authkey==null||authkey=='') authkey = ajaxCharts_chartKey;
		if(authkey == null || authkey == ''){
			showChartKeyError();	
		} else {
			requestQue.push(createRequest(1, symbolSet, chartProfile.id, authkey));
			runChartRequest(force);
		}
	}
}
function _runChartRequest(){
	if(chartOverride != null && chartOverride())
		return;
	for(var i = 0; i < requestQue.length; i++){
		if(requestQue.length == 0) return;
		var xml = requestQue[i];
		var requestMaker = new CATS.RequestMaker(contextPath + "/servlet/CS2Proxy", retrieveCharts, null, xml, false);
		requestMaker.loadXMLDoc();
	}
	requestQue = new Array();
}
var imgArray = new Array();
function runChartRequest(force){
	if(force == null) force = false;
	if(!force && (chartOverride != null && chartOverride()))
		return;
	for(var i = 0; i < requestQue.length; i++){
		if(requestQue.length == 0) return;
		var xml = requestQue[i];
		$.ajax({
			url: $.swim.uris.getUrl("CS2Proxy"),
			processData: false,
			data: "xml="+xml,
			success: function(xml){
				var resp = $(xml).find("ChartResponse");
				if($(resp).size() < 1){
					//displayAjaxError("black", "Charts are temporarily down, try again later", true);
					return;
				}
				var groupId = $(resp).attr("groupID");
				var imageURLS = new Array();
				$(resp).find("ImageURL").each(function(){
					imgArray[$(this).attr("symbol")] = $(this).attr("url");
				});
				populateChartAndMapHtml(false);
				getMaps(groupId);
			}
		});
	}
	requestQue = new Array();
}

function getMaps(key){
	var requestMaker = new CATS.RequestMaker(contextPath + "/servlet/CS2Proxy?key="+key, populateMaps, null, null, false);
	requestMaker.loadXMLDoc();
}
var mapArray = new Array();
function populateMaps(){
	var xml = this.req.responseXML;
	if(xml != null){
		var xmlMaps = xml.getElementsByTagName("StockEvents");
		for(var i = 0; i < xmlMaps.length; i++){
			var xmlMap = xmlMaps[i];
			var rowid = xmlMap.attributes.getNamedItem("symbol").value;
			mapArray[rowid] = new CM.ChartManager.Chart.Map(xmlMap, rowid);
		}
		populateChartAndMapHtml(true);
		clearElementSet("ajaxChartSpan", "span");
	}
}
function clearCharts(){
	var imgs = getElementSet("AjaxChart", 'img');
	for(var i = 0; i < imgs.length; i++){
		imgs[i].src = contextPath + '/images/empty_chart.gif';
	}
}

function openEvent(ref){ 	
 	window.open (ref, "new");
}

function setProfile(profileId, profile){
	var chartM = CM.chartManager;
	if(profileId == null)
		chartM.chartProfiles[0]=profile;
	else
		chartM.chartProfiles[profileId]=profile;
	return profile;
}
function getProfile(profileId){
	var chartM = CM.chartManager;
	var profiles = chartM.chartProfiles;
	if(profileId == null)
		profile = chartM.chartProfiles[0];
	else
		profile = chartM.getChartProfile(profileId);
	if(profile == null){
		return chartM.chartProfiles[0];
	}else{
		return profile;
	}
}
function createRequest(one, symbols, profileId, authkey){
	var profile = getProfile(profileId);
	if(profile == null) return;
	request = new Array();
	request.push("<ChartRequest>");
	request.push(getSymbols(symbols));
	request.push("<ChartParameters authkey='"+authkey+"'>");
	request.push(profile.getSizeNode());
	request.push(getSquaredInsets(0));
	request.push("<background>",profile.backgroundColor,"</background>");
	request.push(getChartModel(profile));
	request.push(profile.getStudyNodes());
	request.push(profile.getComparisonNodes());
	request.push("</ChartParameters></ChartRequest>");
	return request.join("");
}
function getChartModel(profile){ 
	var chartModel = new Array();
	chartModel.push("<ChartModel>");
	chartModel.push(profile.getHideNodes());
	chartModel.push(profile.getLogScaleNode());
	chartModel.push(profile.getBarStyleNode());
	chartModel.push(profile.getDurationNode());
	chartModel.push(profile.getFrequencyNode());
	chartModel.push(profile.getShowLastValueNode());
	chartModel.push("</ChartModel>");
	return chartModel.join("");
}
function getSymbols(symbols){ 
	return "<Symbols><Symbol>"+symbols.join("</Symbol><Symbol>")+"</Symbol></Symbols>";
}
function getSquaredInsets(val){ 
	return getInsets(val, val, val, val);
}
function getInsets(l, t, r, b){ 
	return "<Insets left='"+l+"' top='"+t+"' right='"+r+"' bottom='"+b+"'/>";
}
function showChartKeyError(){
	var ajaxChartSpans = getElementSet("ajaxChartSpan", "span");
	for(var i = 0; i < ajaxChartSpans.length; i++){
		var ajaxChart = ajaxChartSpans[i];try{
			ajaxChart.width=lastProfile.width;
			ajaxChart.height=lastProfile.height;
			ajaxChart.innerHTML = 	'<div align="center">Unable to load chart.<br><a href="javascript:void(0)" onclick="showChartTroubleshooting();">More Information</a></div>';
		}catch(er){}		
	}
}
var chartTroubleshootingWindow;
function showChartTroubleshooting(){
	chartTroubleshootingWindow = window.open(contextPath + '/chartsTroubleShooting.iedu','','height=250, width=400,toolbar=0,status=0,scrollbars=yes');
	chartTroubleshootingWindow.focus();
}
function profileFits(width, height, img){
	if($(img).css("width") == width+"px"){
		if($(img).css("height") == height+"px"){
			return true;
		}else{
			return false;
		}
	}else{
		if($(img).attr('width') != width) return false;
		if($(img).attr('height') != height) return false;
	}
	return true;
}
function populateChartAndMapHtml(hasMaps){
	var ajaxChartSpans = getElementSet("ajaxChartSpan", "span");
	for(var i = 0; i < ajaxChartSpans.length; i++){
		var ajaxChart = ajaxChartSpans[i];
		var img = $(ajaxChart).find('img');
		if($(img).size() > 0){
			if(!profileFits(lastProfile.width, lastProfile.height, $(img))) continue;
		}
		ajaxChart.width=lastProfile.width;
		ajaxChart.height=lastProfile.height;
		var symbol = ajaxChart.getAttribute("symbol");
		var imgSrc = imgArray[symbol];
		if (imgSrc == null) continue;
		var mapEl = mapArray[symbol];
		var html = (hasMaps && mapEl!=null)? mapEl.html : '';		
		try{
			ajaxChart.innerHTML = 	'<img '+
									'src="' + imgSrc + '" '+
									'width="' + lastProfile.width + '" '+
									'height="' + lastProfile.height + '" '+
									'border="0" '+
									'class="AjaxChart" '+
									'usemap="#map_' + symbol + '" '+
									'name="chart_' + symbol + '" '+
									'id="chart_' + symbol + '"/>'+
									html;
		}catch(er){}
		var existing = $('div#chart').find("span#pop_"+symbol);
		if($(existing).size() > 0){
			pops[symbol] = $('div#chart').html()+"";
			setTimeout(function(){pops[symbol] = null;}, 25000);
		}
	}
}
// chart popups
var showPopCharts = true;
var popSymbol = null;
var myPopChartProfile = null;
var popSymbols = new Array();
function getPopSymbol(){
	if(popSymbols.length > 0){
		return popSymbols[0];
	}
}
$(document).ready(function(){
	if((typeof tipobj)+"" == "undefined") return;
	$(tipobj).css('width', "260px");
	$('span.popChart').hoverIntent({
		   sensitivity: 1,
		   interval: 250,
		   over: function(event){
		   		if(typeof(ddrivetip)!='undefined') 
		   			showTip($('div#chart').html(), 250);
		   		positiontip(event);
		   	},
		   timeout: 1,
		   out: function(event){
		   		hideddrivetip(event);
		   		popSymbol = null;
		   	}
	}).bind('click', function(){
		$(tipobj).hide();
	});
});
// IE doesn't respond to 'keypress'
$(document).bind("keydown", function(e) {
	if(e.keyCode == 113 && popSymbol != null){ // F2
		$.swim.uris.addUrl('snapshot', '/graphs/snapshot.iedu');
		$.swim.uris.go('snapshot', 'symbol='+popSymbol);
		$.swim.uris.addUrl('snapshot', '');// un set this just to be safe.
	}
});
function showTip(thetext, thewidth, thecolor){ 
	$(tipobj).css('width', "260px");
	if (ns6||ie){
		$(tipobj)
			.css('width', "260px")
			.css('backgroundColor', "white")
			.html($('div#chart').html())
			.bgiframe();
	enabletip=true;
	return false;
	}
}
var pops = new Array();

function setSymbolPopupNoChart(symbol, description){
	// hack to avoid loading charts when not wanted
}
function setSymbolPopup(symbol, description){
//	debugger;
	var existing = $('div#chart').find("span#pop_"+symbol);
	if($(existing).size() > 0){
		// if the last mouse over was this, then we are good.
		return;
	}
	if(pops[symbol] != null){
		$('div#chart').html(pops[symbol]);
		return;
	} 
	popSymbol = symbol
	var sb = new StringBuffer();
    sb.append('<table><tr><td><span class=subTitle>',description,'</span></td>', 
		'<td align="right"><a href="#" onClick="chartClick();" class="navlinkbluebold">',
		'Press F2 for snapshot.<br/></a></td></tr>');
    if(showPopCharts){
        sb.append('<tr><td colspan="2"><span onClick="chartClick();" id="pop_',symbol,'" class="ajaxChartSpan" symbol="',symbol,'" >',
				'<img id="popImage" src="',$.swim.uris.getImg('emptyChart'),'" style="height:190;width:250;" width="250" height="190" border="1px"></img>',
            	'</span></td></tr>');
    }
    sb.append('</table>');
	$('div#chart').html(sb.toString());
	
	popSymbols = new Array();
	popSymbols.push(symbol);
	if(myPopChartProfile == null){
		myPopChartProfile = new CM.ChartManager.ChartProfile("popup");
		myPopChartProfile.height=190;
		myPopChartProfile.width=250;
	}
	getCharts(popSymbols, myPopChartProfile, true);
	return sb.toString();
}