// Change Chart Scaling Type
chart.prototype.changeScale = function(who) {
	this.scaling = who.id;
	this.load();
}
// Add Lower Indicator
chart.prototype.addLower = function(who,lowObj){
	if (!lowObj) {
		var lowObj = this.lower[who.id];
	}
	if (this.lowerManager.length > this.lowerLimit) {
		this.limit = this.lowerLimit;
	} else {
		this.limit = this.lowerManager.length;
	}
	// moves lower indicators, and enforces limit
	for (var i=this.limit;i>0;i--) {
		this.lowerManager[i] = {value:this.lowerManager[(i-1)].value,params:this.lowerManager[(i-1)].params}
	}
	this.lowerManager[0] = {value:who.id,params:lowObj.params}
	this.load();
	this.showSubItem(document.getElementById('overlays'), 0);
	this.selectItem('overlaysContent', who);
}
// Updates the Lower Indicator
chart.prototype.updateLower = function(lowerIndex,numParams) {
	// get props
	var type = this.lowerManager[lowerIndex].value;
	// get all params
	var params = [];
	for (var i=0;i<numParams;i++) {
		var value = document.getElementById("i"+lowerIndex+"_"+i).value;
		if (type.indexOf("volume") > -1 && i == 0 && type.indexOf("rateofchange") < 1) {
			value = value.toUpperCase();
			if (value == 'EMA' || value == 'SMA' || value == 'WMA') {

			} else {
				alert("Value must be either SMA, EMA, or WMA");
				return null;
			}
		} else if (type.indexOf("relativeratio") > -1) {
			value = value + '';
			if (value.length < 1 || value.length > 6) {
				alert("Please enter a valid symbol to compare");
				return null;
			}
		} else {
			value = parseFloat(value);
			if (value < 0 || value > 1000 || isNaN(value)) {
				alert("Value must be within acceptable range");
				return null;
			}
		}
		params.push(value);
	}

	var tmpParams = params.join(",");
	this.lowerManager[lowerIndex].params = tmpParams;
	this.sublowermenu.style.display = 'none';
	this.closeLowerItem();
	this.load();
}
// Removes an Lower Indicator
chart.prototype.removeLower = function(key) {
	var len = this.lowerManager.length;
	// When only 1 force clean
	if (len == 1) {
		this.lowerManager = [];
	} else {
		var tempArray = [];
		var count = 0;
		
		for (var i=0;i<len;i++) {
			if (i == key) {
				var count = parseInt(i);
				break;
			} else {
				tempArray[i] = {value:this.lowerManager[i].value,params:this.lowerManager[i].params}
			}
		}
		
		for (var c = count;c<(len - 1);c++) {
			var x = parseInt(c) + 1;
			tempArray[c] = {value:this.lowerManager[x].value,params:this.lowerManager[x].params}
		}
		// replace Array
		this.lowerManager = tempArray;
	}
	this.load();
}
// --Time Durations Menu--
chart.prototype.showDuration = function(who,show,duration){
	if(show == 1){
		var pos = this.getPos(who,1,20);
		this.durationmenu.style.display = 'block';
		this.durationmenu.style.left = pos.x + 'px';
		this.durationmenu.style.top = pos.y + 'px';
		this.clearDurationTimeout();
	}else{
		this.durationTimeout = window.setTimeout("chart.hideDuration();",200);
	}
}
chart.prototype.hideDuration = function(who){
	this.durationTimeout = null;
	this.durationmenu.style.display = 'none';
}
chart.prototype.clearDurationTimeout = function(){
	window.clearTimeout(chart.durationTimeout);
}
// change duration
chart.prototype.chgDuration = function(elm, duration){
	this.dMin = 0;
	this.dMax = 0;
	if (!duration) {duration = this.duration;}
	this.duration = duration;
	this.updateFrequency(duration);
	this.selectItem('durationsContent', elm);
	this.showSubItem(document.getElementById('durations'), 0);
	this.load();
}
chart.prototype.selectItem = function(container, elm) {
	var img = '<img src="../common/images/menu_check.gif" class="menu_checked" />';
	var d = document.getElementById(container).childNodes;
	//Switch out arrow icon
	for(var i = 0; i < d.length; i++){
		if(elm.id == d[i].id){
			if (d[i].className.indexOf('activeItem') == -1) {
				d[i].innerHTML = img + d[i].innerHTML;
				d[i].className = 'activeItem subitem';
			}
		}else{
			d[i].className = 'subitem';
			if(d[i].innerHTML){
				if(d[i].innerHTML.toLowerCase().indexOf('<img') != -1){
					d[i].removeChild(d[i].childNodes[0]);
				}
			}
		}
	}
}
// Updates Frequency Menu Options
chart.prototype.updateFrequency = function(){
	this.freqOptions = this.durations[this.duration].options;
	this.frequency = this.durations[this.duration].interval; // if previous default not avail, use data default
}
// Change Chart Display Style
chart.prototype.changeDisplay = function(who) {
	this.display = who.id;
	this.load();
}
// Change Chart Frequency
chart.prototype.changeFrequency = function(who,duration) {
	if (duration != this.duration) {
		this.dMin = 0;
		this.dMax = 0;
	}
	this.duration = duration;
	this.frequency = who;
	var elm = document.getElementById('duration_'+duration, duration);
	this.selectItem('durationHolder', elm);
	this.load();
}
// -- Side Menu Display --
chart.prototype.showSubItem = function(who,show,offset) {
	if (show == 1) {
		if (!offset) {offset = 0;}
		
		if (typeof(document.all) == "undefined") {
			var pos = this.getPos(who,1 + offset,20);
		} else {
			var pos = this.getPos(who,1 + offset,20);
		}
		
		if(this.activeMenuItem && this.activeMenuItem !== false){
			this.activeMenuItem.className = 'menuitem';
		}
		
		this.activeMenuItem = who;
		this.activeMenuItem.className = 'menuitemHL';
		this.submenu.style.display = 'block';
		this.submenu.style.left = pos.x + 'px';
		this.submenu.style.top = pos.y + 'px';
		if (offset) {
			this.submenu.style.width = 160 + offset + 'px';
		} else {
			this.submenu.style.width = '160px';
		}
		this.submenucontent.innerHTML = document.getElementById(who.id+'Content').innerHTML;
		this.mView = 0;
		this.clearMenuTimeout();
		this.clearMenuTimeout2();
	} else {
		this.mView = 1;
		this.mView2 = 1;
		this.mViewID = window.setTimeout("chart.closeSubItem();", 200);
		this.mViewID2 = window.setTimeout("chart.closeSubItem2();", 200);
	}
}
// close menu
chart.prototype.closeSubItem = function() {
	if (this.mView) {
		this.submenu.style.display = 'none';
		this.submenu2.style.display = 'none';
		this.activeMenuItem.className = 'menuitem';
		this.activeMenuItem = false;
	}
	window.clearTimeout(chart.mViewID);
}
chart.prototype.clearMenuTimeout = function() {
	this.mView = 0;
	window.clearTimeout(chart.mViewID);
}
// close secondary menu
chart.prototype.closeSubItem2 = function() {
	if (this.mView2) {
	this.submenu2.style.display = 'none';
	}
	window.clearTimeout(chart.mViewID2);
}
chart.prototype.clearMenuTimeout2 = function() {
	this.mView = 0;this.mView2 = 0;
	window.clearTimeout(chart.mViewID);
	window.clearTimeout(chart.mViewID2);
}
// highlight menu item
chart.prototype.hlMenu = function(who,what) {
	if (what) {
		if(who.className.indexOf('active') == -1){
			who.className = 'subitem subitemHL';
		}
	} else {
		if(who.className.indexOf('active') == -1){
			who.className = 'subitem';
		}
	}
}
// -- Upper Options Menu --
chart.prototype.showUpperItem = function(who,show) {
	if (show == 1 && this.getUpperOptions(who.id) != '') {
		if (typeof(document.all) == "undefined") {
			var pos = this.getPos(who,0,16); // firefox
		} else {
			var pos = this.getPos(who,2,18); // ie
		}
		this.lastWho = who;
		this.subuppermenu.style.display = 'block';
		this.subuppermenu.style.left = pos.x + 'px';
		this.subuppermenu.style.top = pos.y + 'px';
		this.subuppermenucontent.innerHTML = this.getUpperOptions(who.id);
		
		this.uView = 0;
		this.clearUpperTimeout();
	} else {
		this.uView = 1;
		this.uViewID = window.setTimeout("chart.closeUpperItem();",200);
	}
}
chart.prototype.getUpperOptions = function(key){
	for (var i = 0;i<this.upperManager.length;i++) {
		if (key == 'u'+this.upperManager[i].key) {
			var u = this.upperManager[i];
			var content = [];
			if (u.type == 'event' || u.type == 'compare') {
				var paramslength = 0;
			} else {
				var params = u.params.split(",");
				var paramLabels = this.upper[u.value].paramLabel.split(",");
					content.push('<table class="paramsTable"><tr>');
				for (var p = 0;p<params.length;p++) {
					content.push('<td>'+paramLabels[p]+':</td>');
				}
					content.push('</tr><tr>');
				for (var p = 0;p<params.length;p++) {
					content.push('<td><input id="i'+u.key+'_'+p+'" class="paramsInput" type="text" value="'+params[p]+'" maxlength="3" /></td>');
				}
					content.push('</tr></table>');
			}
			
			if (paramslength != 0) {
				content.push('<div class="button" onclick="chart.updateUpper('+i+','+params.length+');">Update</div>');
			}
			
			return content.join("");
			break;
		}
	}
}
// close upper menu
chart.prototype.closeUpperItem = function() {
	if (this.uView) {
		this.subuppermenu.style.display = 'none';
	}
	window.clearTimeout(chart.uViewID);
}
chart.prototype.clearUpperTimeout = function() {
	this.uView = 0;
	this.lastWho.className = 'fLeft upperOption';
	window.clearTimeout(chart.uViewID);
}

// -- Lower Options Menu --
chart.prototype.showLowerItem = function(who,show) {
	try{
		if (show == 1) {
			var pos = this.getPos(who,1,18);
			//this.lastWho = who;
			this.sublowermenu.style.display = 'block';
			this.sublowermenu.style.left = pos.x + 'px';
			this.sublowermenu.style.top = pos.y + 'px';
			this.sublowermenucontent.innerHTML = this.getLowerOptions(who.id);
			this.lView = 0;
		} else {
			this.lView = 1;
			this.lViewID = window.setTimeout("chart.closeLowerItem();",200);
		}
	}catch(e){}
}
chart.prototype.getLowerOptions = function(key) {
	var key = key.split("_");
		lIndex = key[1] - 1;

	var lowObj = this.lowerManager[lIndex];
	var params = lowObj.params + '';
	var params = params.split(",");
	if (this.lower[lowObj.value]) {
		var paramLabels = this.lower[lowObj.value].paramLabel.split(",");
		var numParams = this.lower[lowObj.value].numParams;
	} else {
		var paramLabels = [];var numParams = 0;
	}
	
	var content = [];

	if (numParams > 0) {
		content.push('<table class="paramsTable"><tr>');

		for (var p = 0;p<numParams;p++) {
			content.push('<td>'+paramLabels[p]+':</td>');
		}
		content.push('</tr><tr>');

		for (var p = 0;p<numParams;p++) {
			content.push('<td><input id="i'+lIndex+'_'+p+'" class="paramsInput" type="text" value="'+params[p]+'" maxlength="5" /></td>');
		}
		content.push('</tr></table>');
		content.push('<table class="paramsTable"><tr><td align="left">');
		content.push('<div class="button" onclick="chart.updateLower(\''+lIndex+'\','+numParams+');">Update</div>');
		content.push('</td></tr></table>');
	} // end if params check

	return content.join("");
}
// close lower menu
chart.prototype.closeLowerItem = function() {
	if (this.lView) {
		this.sublowermenu.style.display = 'none';
	}
	window.clearTimeout(chart.lViewID);
}
chart.prototype.clearLowerTimeout = function() {
	this.lView = 0;
	window.clearTimeout(chart.lViewID);
}

// wrappers
function clearUpperTimeout() {
	try {
		chart.clearUpperTimeout();
	} catch(e) {}
}
function showUpperItem(who,what) {
	try {
		chart.showUpperItem(who,what);
	} catch(e) {}
}
function clearLowerTimeout() {
	try {
		chart.clearLowerTimeout();
	} catch(e) {}
}
function showLowerItem(who,what) {
	try {
		chart.showLowerItem(who,what);
	} catch(e) {
		//alert(e);
	}
}
function removeLower(key) {
	try {
		chart.removeLower(key);
	} catch(e) {alert(e);}
}
function hl(who,what) {
	try {
	chart.hlMenu(who,what);
	} catch(e) {}
}
function showSubItem(who,show,offset) {
	try {
	chart.showSubItem(who,show,offset);
	} catch(e) {}
}
function show10KSubItem(who,show,offset) {
	try {
	chart.show10KSubItem(who,show,offset);
	} catch(e) {}
}

function aU(who,what,forceParams) {
	try {
	chart.addUpper(who,what,forceParams);
	} catch(e) {}
}
function aL(who) {
	try {
	chart.addLower(who);
	} catch(e) {}
}
// durations
function showDuration(who,show,duration) {
	try {
	chart.showDuration(who,show,duration);
	} catch(e) {}
}
function clearDurationTimeout() {
	try {
	chart.clearDurationTimeout();
	} catch(e) {}
}
function chgDuration(elm, duration) {
	try {
	chart.chgDuration(elm, duration);
	} catch(e) {}
}

// Builds Interactive Chart
chart.prototype.load = function(action,action_value){
	this.showLoadingIndicator();
	//var uM = serializer.serialize(this.upperManager);
	var lM = serializer.serialize(this.lowerManager);
		//uM = uM.replace(/&amp;/gi,"-AND-");
		//uM = uM.replace(/&/gi,"-AND-");
		lM = lM.replace(/&/gi,"-AND-");
		
	if (!action) {action = '';}
	if (!action_value) {action_value = '';}
	
	var symStr = '';
	var counter = 0;
	for(var i in this.symbols){
		symStr += '&symbol' + counter + '=' + this.symbols[i];
		counter++;
	}
	
	var qs = '/betfair/charts/mlb/mlb_update_chart.asp?division='+this.division+'&duration='+this.duration+symStr+'&frequency='+this.frequency+'&freq='+this.freq+'&scaling='+this.scaling+'&display='+this.display+'&exportData='+this.exportData+'&dMin='+this.dMin+'&dMax='+this.dMax+'&lowers='+lM+'&action='+action+'&action_value='+action_value;
	
	commonGen.document.location.replace(qs);
	this.resizeMe = 0;
}

chart.prototype.addSymbol = function(symbol) {
	this.symbols[symbol] = 'on;'+symbol;
}

chart.prototype.removeSymbol = function(symbol) {
	this.symbols[symbol] = 'off;'+symbol;
}

chart.prototype.showLoadingIndicator = function(){
	var load = document.getElementById('chartLoadingIndicator');
	
	if(load){
		load.parentNode.removeChild(load);
	}
	
	var container = document.createElement('div');
	container.className = 'chartLoading';
	container.id = 'chartLoadingIndicator';
	container.style.top = '5px';
	container.style.left = '205px';
	container.style.width = '495px';
	container.style.height = '271px';
	container.style.display = 'block';
	container.innerHTML = '<img src="../common/images/loading.gif" style="position:relative;top:' + parseInt(271 / 2 - 16) + 'px;left:'+parseInt(495 / 2 - 16) + 'px;">';
	document.getElementById('chartContainer').appendChild(container);
}

chart.prototype.resize = function(){
	if (!this.resizeMe) {
		this.lcid = window.setTimeout("chart.load()",100);
		this.resizeMe = 1;
	}
}

// -- Helper --
// keeps track of which color to assign to upper indicator nav item
chart.prototype.selectUpperColor = function() {
	if (this.lastColorUsed < this.colors.length) {
		var color = this.colors[this.lastColorUsed];
		this.lastColorUsed++;
	} else {
		this.lastColorUsed = 0;
		var color = this.colors[this.lastColorUsed];
		this.lastColorUsed++;
	}
	return color;
}
// get pos of any element
chart.prototype.getPos = function(who,xOff,yOff){
	
	this.eleOffset = who;

	if (!xOff) { xOff = 0; }
	if (!yOff) { yOff = 0; }

	var x = 0;var y = 0;
	while (this.eleOffset.offsetParent != null) {
		x += this.eleOffset.offsetLeft;
		y += this.eleOffset.offsetTop;
		this.eleOffset = this.eleOffset.offsetParent;
	}
	
	x += this.eleOffset.offsetLeft + xOff;
	y += this.eleOffset.offsetTop + yOff;

	var pos = [];pos.x = x;pos.y = y;
	return pos;
}

// -- Events --
// Displays Insider/splits/earngs transaction rollover

chart.prototype.displayInfo = function(who,what,left,top,trigger, bubble) {
	try {	
		if (what) {
			this.iWin = Element.get(who+"Win");
			var content = this.iWin.innerHTML;
			var xy = Element.getXY(trigger);
			bubble.SetContent(Element.create("div", {}, content));
			bubble.MoveBubble(xy.x, xy.y, Element.getSize(trigger));
			bubble.BlowBubble();
		} else {
			bubble.PopBubble();
		}
	} catch(e){alert(e);};
}
function rWrap(who,what,left,top, trigger) {
	try {
		chart.displayInfo(who,what,left,top,trigger, this.bubble);
	} catch(e) {alert(e);}
}