function createCookie(name, value, days) {
	var expires = '';
	if (days) {
		var date = new Date();
		date.setTime( date.getTime() + (days*24*60*60*1000) );
		expires = '; expires=' + date.toGMTString();
	}
	document.cookie = name + '=' + value + expires +'; path=/';
}

function readCookie(name) {
	var nameEQ = name + '=';
	var ca = document.cookie.split(';');
	for(var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

// As there is no API or easy way to link directly to an ITMS song while getting commission, on the first click set the LinkShare session
function initiTMS(section) {
	var loaded = loaded ? true : readCookie('loaded');
	var affiliate = 'http://click.linksynergy.com/fs-bin/click?id=J1cS9bwFLqI&amp;offerid=78941.544851214&amp;type=10&amp;subid=';

	if (!document.getElementById) return false;
	if (!document.getElementById(section)) return false;
	var block = document.getElementById(section);

	if (!block.getElementsByTagName) return false;
	if (!block.getElementsByTagName('a')) return false;
	var links = block.getElementsByTagName('a');

	for ( var i = 0; i < links.length; i++) {		
		var link = links[i];
		link.onclick = function() {
			if (loaded !== true && this.className != 'lastfm') {
				createCookie('loaded', true, 60);
				loaded = true;
				window.location.href = affiliate;
				return false;
			} else {
				return true;
			}
		};
	}
	
}

$(function() {
	initiTMS('countdown');

	$('#topartistschart p').remove(); // delete the JavaScript warning, it's working

	function pushIt(data, filling, count) {
		for (var i = 0; i < count; i++) {
			data.push(filling); 
		}
		return data;
	}
	function incrIt(data, init, multi, count) { // (not used, but a handy function - I'll know where it is if I leave it here
		for (var i = 0; i < count; i++) {
			var filling = init + (multi * i);
			data.push(filling); 
		}
		return data;
	}
	function toNumber(str) { // expecting: "(23)", return: 23
		str = $.trim(str);
		str = str.match(/\d+/g);
		return parseInt( str.join(''), 10 );
	}
	function trimLength(str, length) {
		str = $.trim(str);
		str = str.slice(0, length);
		return str;
	}

	var chatele = 'topartistschart';
	if ( $('#' + chatele).length !== 0 ) { // test to see if the data has been outputted inthe HTML
		var r = Raphael(chatele),
			counts = [],
			artists = [],
			tracks = [],
			pos = [],
			xs = [],
			ys = [],
			data = [];
	
		$('#topartistschart tbody tr').each(function() {
			counts.push( parseInt( $.trim( $(this).find('.count').text() ), 10 ) );
			artists.push( trimLength( $(this).find('.artist').text(), 16) );
			$(this).find('.tracks li').each(function() {
				tracks.push( $(this).find('.track').text() );
				pos.push( toNumber( $(this).find('.pos').text() ) );	
			});
		});

		// fake it: fill one at the extreme row with data so the chart knows the width
		xs.push(100);
		ys.push(1);
		data.push(0); // 0 so you can't see it

		// x-axis & data
		for (var i = 0; i < pos.length; i++) {
				var thepos = pos[i];
				xs.push(thepos);
				data.push(101 - thepos); // reverse to make a #1 bigger than #100
		}

		// y-axis
		for (var j = 0; j < counts.length; j++) {
				ys = pushIt(ys, counts.length - j, counts[j]);
		}

		var axisy = artists.reverse(),
			axisx = ['1', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100'],
			cheight = (50 * artists.length) + 100;
		cheight = (cheight > 400) ? 400 : cheight;
		r.g.txtattr.font = '11px "Fontin Sans", Fontin-Sans, sans-serif';
		
		r.g.dotchart(10, 10, 550, cheight, xs, ys, data, {symbol: 'o', max: 10, heat: true, axis: '0 0 1 1', axisxstep: 10, axisystep: artists.length - 1, axisxlabels: axisx, axisxtype: ' ', axisytype: ' ', axisylabels: axisy}).hover(function() {
			if (this.value > 0) {
				var num = (101 - this.value),
					track = tracks[pos.indexOf(num)],
					label = num + '. ' + track;
				this.tag = this.tag || (this.value > 0) ? r.g.tag(this.x, this.y, label, 15, this.r + 2).insertBefore(this) : '';
				this.tag.show();
			}
		}, function() {
			this.tag && this.tag.hide();
		});
	}
});
