var Tracks = Class.create( {
    initialize: function() {
	this.columns = new Array('title','artist','album');
	this.template = $('trackoutput');
	this.trackfile = '/tracks.xml';
	this.pollid = '';
	this.searchLoc = 'http://www.allmusic.com/search/artist/';
	//this.searchLoc = 'http://www.discogs.com/artist/';
    },
    fetch: function() {	
	new Ajax.Request(this.trackfile,
	{
	    method:'get',
	    onSuccess: function(transport){
		var response = transport.responseXML || "no response text";
		this.parse(response);
		this.poll();
	    }.bind(this),
	    onFailure: function(){ //alert('Something went wrong...')
		//console.log('Error requesting');
		window.clearTimeout(this.pollid);

	    }
	});
    },
    parse: function(x) {
	var table = new Element('div');
	table.addClassName('table border');
	var head = new Element('div');
	head.addClassName('table-header-group greyline table-row');
	for(var i=0;i<this.columns.length;i++) {
	    var c = new Element('div');
	    c.addClassName('table-cell');
	    c.update(this.columns[i]);
	    head.insert(c);
	}	
	table.insert(head);
	try{
	    var t = x.getElementsByTagName('track');
	    for (var i = (t.length-1); i > 0; i--) {
		var track = t[i];
		var cn = '';
		switch(Math.abs(i) % 2) { 
		case 1 : cn = " greyline"; 
		} 
		var trow = new Element('div');
		trow.addClassName('table-row' + cn);
		for(var j = 0; j<this.columns.length; j++) {
		    var tcell = new Element('div');
		    tcell.addClassName('table-cell');
		    var n = track.getElementsByTagName(this.columns[j]);
		    var v = n[0].childNodes[0];
		    var finalv = 'Unknown';
		    if(v!=null) {
			finalv = v.nodeValue;
			if(this.columns[j]=='artist') {
			    finalv = '<a href = "' + this.searchLoc + encodeURI(finalv) + '" target="spawn">' + finalv + '</a>';
			}
		    }
		    tcell.update(finalv )
		      
		    trow.insert(tcell);
		}
		table.insert(trow);
	    }
	    this.template.update(table);
	} catch(e) { 
//	    console.log(e) 
	};
    },
    poll: function() {
	this.pollid = this.fetch.bind(this).delay(30);
    }
});

