MediaWiki:Common.js/GECharts.js

var newhash = location.hash.replace(/\.([0-9a-f]{2})/gi, function(match,first) { return String.fromCharCode(parseInt(first,16)); }).replace(/ /g,'_'); if (newhash&&location.hash.match(/#[aiz]=/)) location.hash = newhash

$('.GEdatachart').attr('id', function(c) { return "GEdatachart"+c}); $('.GEdataprices').attr('id', function(c) { return "GEdataprices"+c}); $('.GEChartBox').each(function(c) { $(this).find('.GEChartItems').attr('id', 'GEChartItems'+c)});

//general functions

function cloneObj(a,b) { if (typeof(a)!='object') return ''; if (typeof(b)!='object') b = {}; for (var key in a) { b[key] = a[key]; }	return b; }

function avg(arr,amt,round) { amt = amt||arr.length; round = Math.pow(10,round||0) var avgs = [], list = []; for (var i=0;i=amt) { avgs.push([arr[i][0], Math.round((sum(list)/list.length) * round)/round]); }	}	return avgs; }

function sum(arr) { var tot = 0; for (var i=0;i=1e10) { n = Math.round(n/1e8)/10; n += 'B'; } else if (n>=1e7) { n = Math.round(n/1e5)/10; n += 'M'; } else if (n>=1e4) { n = Math.round(n/100)/10; n += 'K'; }	n = neg+n; return addCommas(n); }

$('body').append('\n Close popup [X]  '+ ' Average:  days Add more item(s):  Note: If you add more items, the averages will not be shown. Submit  Reset all fields  '+ 'Permanent link  ');

for (var c=0;c<$('div.GEdatachart').length;c++) {

var isSmall = $('#GEdatachart'+c).is('.smallChart'); var isIndexChart = !!($('#GEdataprices'+c).attr('data-item')||'').match(/index/i);

//chart-related general functions

function getSeriesIndex(id,match) { if (window['chart'+id]) { var series = window['chart'+id].series; for (var i=0;i<series.length;i++) { if (series[i].name.match(match)) { return i;			} }		return -1; } }

function permLinkHash { var xt = chartpopup.xAxis[0].getExtremes; var minDate = (new Date(xt.min)).toDateString.split(' ').slice(1).join('_'); var maxDate = (new Date(xt.max)).toDateString.split(' ').slice(1).join('_'); var inputAvg = parseInt($('#averagepopup').val); var items = ''; for (var i=0;i<chartpopup.series.length;i++) { if (chartpopup.series[i].name == 'Navigator') continue; if (items.length) items += ','; items += chartpopup.series[i].name.replace(/ /,'_'); }	var urlHash = '#t='+minDate+','+maxDate; if (!isNaN(inputAvg)) urlHash += '#a='+inputAvg; urlHash += '#i='+items; var url = 'http://rs.wikia.com/wiki/GEMW/C'+urlHash; return url; }

if ($('#GEdataprices'+c).length) { var chartid,AIQueue = [],AILoaded = [],AIData = []; function addItem(i,it) { chartid = i	var item = it||$('#extraItem'+chartid).val; if (item&&item.length) { if ($('#addedItems'+i+' [data-item], #GEdataprices'+i+'[data-item]').map(function { return $(this).attr('data-item').toLowerCase; }).get.indexOf(item.toLowerCase)!=-1 || AIQueue.indexOf(item.toLowerCase)!=-1) { alert(item+' is already in the graph.') $('#extraItem'+chartid).val(''); return false; }		$('#extraItem'+chartid).prop('disabled',true); $.get('/api.php?action=parse&format=json&page=Exchange:'+escape(item)+'/Data', function(response) {			if (response.error) {				var item = unescape((this.url.match(/Exchange:([^\/]*)\/Data/)||[])[1]);				if (response.error.code == 'missingtitle') {					alert("The item "+item+" doesn't exist on our Grand Exchange database.");				} else {					alert("An error occurred while loading "+item+".");				}				AILoaded.push(false);				if (AIData.length && AIQueue.length == AILoaded.length) loadChartsQueueComplete(chartid);				else $('#extraItem'+chartid).prop('disabled',false).val('');				return false;			}			if (response.links) {				$.get('/api.php?action=parse&format=json&page='+escape(response.links[0]['*']), this.success);				return false;			}			var item = response.parse.title.match(/Exchange:([^\/]*)\/Data/)[1]			AILoaded.push(item);			var prices = response.parse.text['*'];			var prices = prices.substring(prices.match(/\d{5,}:\d/).index, prices.match(/<\/p>/).index).split(/,\s/); var data = []; var thisprice; for (var i=0;i<prices.length;i++) { if (prices[i].replace(/\s/g,'').length) { thisprice = prices[i].split(':'); data.push([ parseInt(thisprice[0])*1000, parseInt(thisprice[1]) ]); }			}			AIData.push({name: item, data: data, id: item, lineWidth: 2}); var series = window['chart'+chartid].series if (getSeriesIndex(chartid,'average')!=-1) window['chart'+chartid].series[getSeriesIndex(chartid,'average')].remove; if (AIQueue.length == AILoaded.length) loadChartsQueueComplete(chartid); //This is always true when only 1 item is being loaded. });		AIQueue.push(item.toLowerCase)	} else {		if ($('#addedItems'+i).html.match(/^\s*$/)) {			var id = i=='popup'?$('#GEpopupchart').attr('data-chartid'):i;			var data = getData(id,false,i);			var series = window['chart'+i].series			if (getSeriesIndex(i,'average')!=-1) series[getSeriesIndex(i,'average')].remove;			window['chart'+i].addSeries(data[0][1]);		}	} }

window.addedData = [];

function loadChartsQueueComplete(c) { if (getSeriesIndex(chartid,'Volume')!=-1) { var id = c=='popup'?$('#GEpopupchart').attr('data-chartid'):c; var chartdata = getData(id,true); chartdata[1].title.text = 'Price history'; reloadChart(c,{			series: chartdata[0],			yAxis: chartdata[1]		}); }	var isSmall = $('#GEdatachart'+c).is('.smallChart') var data = new Array(AIQueue.length); for (var i=0;i<AIData.length;i++) { var index = AIQueue.indexOf(AIData[i].name.toLowerCase); data[index!=-1?index:data.length] = AIData[i] }	for (var i=0;i<data.length;i++) { if (data[i]) window['chart'+c].addSeries(data[i]); if (isSmall) { if (typeof addedData[c] != 'object') addedData[c] = []; addedData[c][i] = data[i] }	}	setChartExtremes(chartid); $('#itemstats').hide; $('#extraItem'+c).prop('disabled',false).val(''); var itemhash = (location.hash.match(/#i=[^#]*/)||[])[0]||location.hash + '#i='; for (var i=0;i'+iname+''); itemhash = '#i='+iname; } else { $('#addedItems'+c).append(', '+iname+''); itemhash += ','+iname; }	}	if (location.hash.match(/#i=/)) itemhash = location.hash.replace(/#i=[^#]*/,itemhash).replace(/ /g,'_'); else itemhash = location.hash + itemhash; if ((wgNamespaceNumber == 112 && wgTitle.split('/')[1] == 'Data'||wgPageName == 'Grand_Exchange_Market_Watch/Chart') && itemhash.replace('#i=','').length) location.hash = itemhash AIQueue = []; AILoaded = []; AIData = []; var hadBlank = removeGraphItem('Blank',c); if (hadBlank) { setChartRange(c) } }

function setChartRange(c) { var zoom = parseInt((location.hash.match(/#z=([^#]*)/)||[])[1]) zoom = zoom&&zoom<=6&&zoom>=0?zoom-1:(zoom==0?0:2); var hash = location.hash; var hasT = wgNamespaceNumber == 112 && wgTitle.split('/')[1] == 'Data'||wgPageName == 'Grand_Exchange_Market_Watch/Chart'; if (typeof c == 'number' && hash.match('#z=') && (hasT && !hash.match('#t=') || !hasT)) { $('#GEdatachart'+c+' .zoomButton').eq(zoom).click; return true; }	var timespan = unescape((hash.match(/#t=([^#]*)/)||[])[1]||'').replace(/_/g,' ').split(',') var dates = [new Date(timespan[0]), new Date(timespan[1])]; var d = new Date(timespan[0]); var extremes = chart0.xAxis[0].getExtremes; if (dates[0] != 'Invalid Date' && dates[1] == 'Invalid Date' && typeof(zoom) == 'number') { var button = chart0.rangeSelector.buttonOptions[zoom]; if (button.type == 'month') { d.setMonth(d.getMonth + button.count); } else if (button.type == 'year') { d.setYear(d.getFullYear + button.count); } else if (button.type == 'all') { d = new Date(extremes.dataMax); }		dates[1] = d;	} if (dates[0] != 'Invalid Date' && dates[1] != 'Invalid Date') { chart0.xAxis[0].setExtremes(dates[0].getTime, dates[1].getTime); return true; }	return false; }

function reloadChart(c,change) { if (!window['chart'+c].options) {return false;} for (var i in change) { window['chart'+c].options[i] = change[i]; }	window['chart'+c] = new Highcharts.StockChart(window['chart'+c].options); }

function removeGraphItem(item,c) { var id; for (var i=0;i<window['chart'+c].series.length;i++) { if (window['chart'+c].series[i].name.match(item)) { id = i;		} }	if (typeof id != 'number') return false; var newhash = location.hash.replace(/_/g,' ').replace(new RegExp('(#i=[^#]*),?'+item,'i'),'$1').replace(/,,/g,',').replace(/,#/g,'#').replace(/#i=,/g,'#i=').replace(/#i=($|#)/,'$1').replace(/ /g,'_'); if (newhash.replace('#i=','').length) location.hash = newhash; else if (location.hash.length) location.hash = ''; window['chart'+c].series[id].remove; setChartExtremes(c) $('#addedItems'+c+' [data-item="'+item+'"]').remove $('#addedItems'+c).html($('#addedItems'+c).html.replace(/,, /g,', ').replace(/, $/,'').replace(': , ',': ')); if (!$('#addedItems'+c+' [data-item]').length) { $('#addedItems'+c).empty; var id = c == 'popup'? $('#GEpopupchart').attr('data-chartid') : c;		var data = getData(id,false); reloadChart(c,{			series: data[0],			yAxis: data[1]		}); $('#itemstats').show; }	return true; }

function popupChart(i) { if (!$('#GEchartpopup').length) return false; if ($('#overlay').length) { $('#overlay').toggle; } else { $('#GEchartpopup').before(' '); }	document.getElementById('overlay').onclick = popupChart; if (typeof(i)=='number') { onkeydown = function(e) { if (e.which == 27) popupChart(false); } } else { onkeydown = function {}; }	$('#GEchartpopup').toggle; if (typeof(i)=='number' && $('#GEpopupchart').attr('data-chartid') != i) { $('#averagepopup').val(average); addPopupPriceInfo(i) $('#GEpopupchart').attr('data-chartid',i); var options = {} cloneObj(window['chart'+i].options,options); options.chart.renderTo = 'GEpopupchart'; options.chart.spacingBottom = 15; options.legend.align = 'right'; options.legend.layout = 'vertical'; options.legend.verticalAlign = 'top'; options.legend.y = 75; options.title.text = 'Grand Exchange Market Watch'; options.title.style.fontSize = '18px'; options.title.style.color = 'black'; options.subtitle.text = options.series[0].name; options.chart.zoomType = ''; options.rangeSelector.enabled = true; options.rangeSelector.inputBoxStyle.display = 'block'; options.plotOptions.series.enableMouseTracking = true; options.tooltip.enabled = true; options.navigator.enabled = true; options.credits.enabled = false; options.series = [{}]; var data = getData(i,false); options.series = addedData[i]?[data[0][0]]:data[0]; options.yAxis = data[1]; window.chartpopup = new Highcharts.StockChart(options); if (addedData[i]) { for (var n=0;n<addedData[i].length;n++) { window.chartpopup.addSeries(addedData[i][n]); }		}		setChartExtremes('popup'); chartpopup.redraw; }	$('#popupPermLink').get(0).href = permLinkHash; }

function setChartExtremes(i) { extremes = window['chart'+i].yAxis[0].getExtremes; if (extremes.dataMin * 0.95 != extremes.userMin || extremes.dataMax * 1.05 != extremes.userMax) { window['chart'+i].yAxis[0].setExtremes(extremes.dataMin * 0.95, extremes.dataMax * 1.05); if (window['chart'+i].yAxis[2]) { extremes = window['chart'+i].yAxis[1].getExtremes; window['chart'+i].yAxis[1].setExtremes(0, extremes.dataMax * 0.35); }	}	if (i == 'popup') $('#popupPermLink').get(0).href = permLinkHash; }

function addPopupPriceInfo(c) { if (($('#GEdataprices'+c).attr('data-item')||'').match(/index/i)) return false; var prices = $('#GEdataprices'+c).html.split(/,\s/); var data = []; var curprice; for (var i=0;i<prices.length;i++) { if (prices[i].replace(/\s/g,'').length) { curprice = prices[i].split(':'); data.push(parseInt(curprice[1])); }	}	var datal = data.length var curprice = data[datal-1] var priceDiffs = [], percentDiffs = []; var dayDiffs = [1,7,30,90,180]; for (var i=0;i0?'green':(n==0?'blue':'red'); }	var itemStats = ' '; $('#itemstats').html(itemStats); }

function getData(c,isSmall,avginput) { var isIndexChart = !!($('#GEdataprices'+c).attr('data-item')||'').match(/index/i); avginput = avginput||c; var itemName = $('#GEdataprices'+c).attr('data-item'); itemName = itemName || wgPageName.replace(/_/g,' ').split('/')[0].replace('Exchange:',''); var prices = $('#GEdataprices'+c).html.split(/,\s/); window.data = []; var thisprice; var volumes = []; for (var i=0;i<prices.length;i++) { if (prices[i].replace(/\s/g,'').length) { thisprice = prices[i].split(':'); data.push([ parseInt(thisprice[0])*1000, parseFloat(thisprice[1]) ]); if (thisprice[2]&&!isSmall) { volumes.push([ parseInt(thisprice[0])*1000, parseFloat(thisprice[2])*1000000 ]); //volumes are in millions }		}	}

var dataList = [{ name: itemName, data: data, lineWidth: isSmall?2:3 }]	if (itemName.toLowerCase=='blank') dataList[0].color = '#000000'; if (!isSmall&&itemName.toLowerCase!='blank') { var inputAvg = parseInt($('input#average'+avginput).val); if (inputAvg) { var newhash = location.hash.replace(/#a=[^#]*|$/,'#a='+inputAvg).replace(/ /g,'_'); if (newhash.length) location.hash = newhash }		inputAvg = inputAvg||30; dataList.push({			name: inputAvg+'-day average',			data: avg(data,inputAvg,isIndexChart?2:0),			lineWidth: 2,			dashStyle: 'shortdash',		}); if (volumes.length) { dataList.push({				name: 'Volume',				data: volumes,				type: 'area',				color: '#cc8400',				fillColor: {					linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },					stops: 0, ',				},				yAxis: 1,			}); }	}	var yAxis = {}; if (volumes.length&&!isSmall) { yAxis = [{ title: { text: 'Price history', offset: 60, style: { color: 'black', fontSize: '12px', },			},			labels: { align: 'right', x: -8, y: 4, },			allowDecimals: false, minTickInterval: 1, //1 coin showLastLabel: 1, lineWidth: 1, lineColor: '#E0E0E0', height: 225, }, {			title: { text: 'Trade volume', offset: 60, style: { color: 'black', fontSize: '12px', },			},			labels: { align: 'right', x: -8, y: 4, },			showEmpty: 0, showLastLabel: 1, offset: 0, lineWidth: 1, lineColor: '#E0E0E0', height: 75, top: 325, min: 0 }];	} else { yAxis = { title: { text: isSmall?null:'Price history', offset: 60, style: { color: 'black', fontSize: '12px', },			},			labels: { align: 'right', x: -8, y: 4, },			allowDecimals: false, minTickInterval: 1, //1 coin showLastLabel: 1, lineWidth: 1, lineColor: '#E0E0E0', }	}	return [dataList,yAxis]; }

//setting up the form and chart elements var average = parseInt((location.hash.match(/#a=([^#]*)/)||[])[1])||''; var formhtml = ' Average:  days '+(isIndexChart?:' Add more item(s): <input type="text" id="extraItem'+c+'"> Note: If you add more items, the averages will not be shown.')+' Submit <input type="reset" value="Reset'+(isIndexChart?:' all fields')+'"/> <div id="addedItems'+c+'"> ';

if (!isSmall) { $('#GEdatachart'+c).before(formhtml); }

/*GENERATING THE CHART - INITIAL LOAD*/ var data = []; var itemName = $('#GEdataprices'+c).attr('data-item'); itemName = itemName || wgPageName.replace(/_/g,' ').split('/')[0].replace('Exchange:',''); var dataList = getData(c,isSmall); var yAxis = dataList[1]; dataList = dataList[0]; if (itemName.toLowerCase=='blank') { var zoom; } else { var zoom = parseInt((location.hash.match(/#z=([^#]*)/)||[])[1]) zoom = zoom&&zoom<=6&&zoom>=0?zoom-1:(zoom==0?0:2); }

//adding in the chart properties

Highcharts.setOptions({	lang: {		resetZoom: ' reset zoom ',		rangeSelectorZoom: isSmall?'':'Zoom',		numericSymbols: ['k', 'M', 'B', 'T', 'Qd', 'Qt'],	} });

//generating the chart window['chart'+c] = new Highcharts.StockChart({	chart: {		renderTo: 'GEdatachart'+c,		backgroundColor: 'white',		plotBackgroundColor: 'white',		zoomType: isSmall?'x':,		events: {			redraw: function {				window.thisid = this.renderTo.id.replace('GEdatachart',).replace('GEpopupchart','popup');				setTimeout(function {setChartExtremes(thisid);},0);			}		},		spacingBottom: isSmall?40:15,	},	legend: {		enabled: true,		backgroundColor: 'white',		align: isSmall?'center':'right',		layout: isSmall?'horizontal':'vertical',		verticalAlign: isSmall?'bottom':'top',		y: isSmall?33:75	},	title: {		text: isSmall?'Enlarge chart</a>':'Grand Exchange Market Watch',		style: {			color: isSmall?'#666':'black',			fontSize: isSmall?'12px':'18px',		},	},	subtitle: {		text: isSmall?null:itemName,		y: 35,		style: {			color: '#666',			fontSize: '15px', },	},	rangeSelector: { enabled: !isSmall, selected: zoom, inputBoxStyle: { right: '15px', display: isSmall?'none':'block' },		inputDateFormat: "%e-%b-%Y", buttonTheme: { class: 'zoomButton', },		buttons: [{ type: 'month', count: 1, text: '1m' }, {			type: 'month', count: 2, text: '2m' }, {			type: 'month', count: 3, text: '3m' }, {			type: 'month', count: 6, text: '6m' }, {			type: 'year', count: 1, text: '1y' }, {			type: 'all', text: 'All' }]	},	plotOptions: { series: { enableMouseTracking: !isSmall, dataGrouping: { dateTimeLabelFormats: { day: ['%A, %e %B %Y', '%A, %e %B', '-%A, %e %B %Y'], week: ['Week from %A, %e %B %Y', '%A, %e %B', '-%A, %e %B %Y'], month: ['%B %Y', '%B', '-%B %Y'], year: ['%Y', '%Y', '-%Y'] }			}		}	},	tooltip: { enabled: !isSmall, yDecimals: isIndexChart?2:0, valueDecimals: 0, headerFormat: ' {point.key} ', xDateFormat: "%A, %e %B %Y", },	navigator: { xAxis: { dateTimeLabelFormats: { day: "%e-%b", week: "%e-%b", month: "%b-%Y", year: "%Y", },			minTickInterval: 24 * 3600 * 1000, //1 day },		maskFill: 'none', enabled: !isSmall },	credits: { enabled: false,//temp; change value to  isSmall   to enable again. href: 'javascript:popupChart('+c+');', text: 'Enlarge chart', position: { y: -3 },		style: { color: '#666', fontSize: '11px' }	},	xAxis: [{ lineColor: '#666', tickColor: '#666', dateTimeLabelFormats: { day: "%e-%b", week: "%e-%b", month: "%b-%Y", year: "%Y", },		minTickInterval: 24 * 3600 * 1000, //1 day }],	yAxis: yAxis, series: dataList, colors: window.GEMWChartColors||['#4572A7','#AA4643','#89A54E','#80699B','#3D96AE','#DB843D','#92A8CD','#A47D7C','#B5CA92'] });

setChartRange(c);

var items = ($('#GEChartItems'+c).html||'').split(','); for (var i=0;i<items.length;i++) { if (!items[i].match(/^\s*$/)) addItem(0,items[i]); }

/*END CODE GENERATING THE CHART - INITIAL LOAD*/

//adjusting the axes extremes (initial load) setChartExtremes(c)

//loading the chart and additional price info when the page is ready if ((wgNamespaceNumber == 112 && wgTitle.split('/')[1] == 'Data'||wgPageName == 'Grand_Exchange_Market_Watch/Chart') && document.location.hash.match('#i=')) { var hash = location.hash; var items = unescape((hash.match(/#i=([^#]*)/)||[])[1]||'').replace(/_/g,' ').split(',') for (var i=0;i<items.length;i++) { if (!items[i].match(/^\s*$/)) addItem(0,items[i]); } } }

}//exit c