/*
 * jQuery Tour Dates 1.0.0 - URL TBC
 *
 * Atlantic Records tour dates render plugin
 *
 * Copyright (C) 2008 HUGE (info@hugeinc.com)
 * 
 * Configuration parameters
 *		url: relative URL to data path
 *		artistName: The name of the artist
 *		filter: Whether the drop down filter is generated (true/false)
 *		dateClass: class applied to date table data cell
 *		venueClass: class applied to date table data cell
 *		buyClass: class applied to date table data cell
 *		noDatesStr: Error message if no tour date data could be sourced
 *		debug: Turns on debugging information for Firebug console if true
 *
 * Usage
 *		$('#tour-dates').tourdates({params});
 */

(function($){

	var tD,
	html="",
	states_array = [],
	xml;

	// Set up tourdates object
	$.tourdates = {
		defaults: {
			artistName: 'this artist',
			maxDates: 999,
			dateClass: 'date',
			cityClass: 'city',
			venueClass: 'venue',
			buyClass: 'buy',
			noDatesStr: 'Sorry, no dates found.',
			debug: false
		}
	};
	
	// Extend jQuery function for tourdates
	$.fn.extend({
		tourdates: function(settings){
			settings = $.extend({},$.tourdates.defaults,settings);
			return this.each(function(){
				tD = this;
				$.data(this,"tourdates",settings);
				debug("Initializing tour dates");
				init();
			});
		}
	})
	
	// Initialization method for tour dates 
	function init(){
		if(settings(tD).tourData){
			var tour_xml = parseXML(settings(tD).tourData);
			parseData(tour_xml);
		}
	}
	
	/*	Do some basic replacements on image node,
		and convert to XMLDOM object in IE.
	*/ 
	function parseXML(xml){
		xml = settings(tD).tourData.replace(/\<!\[CDATA\[|\]\]\>/ig,'');
		xml = xml.replace(/title/ig,'tdtitle');
		if (jQuery.browser.msie){
			var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.loadXML(xml);
			xml = xmlDoc;
		}
		return xml;
	}
	
	// Parse the data
	function parseData(data){
		
		//  How many tour dates in the data object?
		dates_count = $(data).find('item').length;
		debug(dates_count + " tour dates found");

		// Check to see whether the data has any tour dates
		if(dates_count == 1 && $(data).find("item tdtitle:contains('tour events')").length){
			// No, it doesn't
			html= $('<p></p>').append(settings(tD).noDatesStr);
		}else{
			// Yes it does
			debug("Generating tour date HTML");
			var tour_loop_count = 0;
			$('item',data).each(function(){
				
				if(tour_loop_count < settings(tD).maxDates){
					// Loop through each tour date, pulling out bits of data (some RegEx stuff required) and assigning to vars
					var td_title = $(this).children('tdtitle').text();
					var td_date = trimString(td_title.match('[\\d]+\/[\\d]+'));
					var td_day_str = trimString(td_title.match('\\s[a-zA-Z]{3}\\s'));
					var td_loc = trimString(td_title.split(" in ")[1]);
					var td_st = td_title.match('\\s[A-Z]{2}\\s');
	
					states_array.push(td_st);
					var td_aw = trimString($(this).find('appearingWith').text());
					var td_vn = trimString($(this).find('venueName').text());
					var td_bl = trimString($(this).find('buylink').text());
					var tour_array = new Array(td_date,td_day_str,td_loc,td_aw,td_vn,td_bl,td_st);
					
					generateTourTable(tour_array);
					tour_loop_count++;
				}
				
			});
			if(settings(tD).filter) generateFilter();
			html+="</table>";
		}
		$(tD).append(html);
		debug($(tD).find('table tr:last').children().css('background','none'));
	}
	
	// Generate HTML for tour date
	function generateTourTable(tA){
		if(!html.length) html+='<table align="left" valign="top" summary="Tour dates for '+settings(tD).artistName+'" id="td-table">';
		html+= '<tr rel="'+tA[6]+'"><td class="'+settings(tD).dateClass+'">'+tA[1]+' '+tA[0]+'</td>';
		html+= '<td class="desc">'+'<span class="'+settings(tD).cityClass+'">'+tA[2]+'</span>';
		html+= '<span class="'+settings(tD).venueClass+'">'+tA[4]+'</span>';
		if(tA[3].length) html+='<br />w/ '+tA[3];
		'</td>';
		html+= (tA[5].length) ? '<td class="'+settings(tD).buyClass+'"><a title="Buy tickets for '+tA[4]+'" href="'+tA[5]+'" target="_blank">Buy Tickets</a></td>' : '<td>&nbsp;</td>';
	}
	
	// Generate drop down menu
	function generateFilter(){
	    debug("Generating states filter");
	    var a = [], l = states_array.length;
    	
    	// Remove duplicate states from states array
 		a = states_array.getUnique();
    	a.sort();
    	
    	// Right, we have our unique states, let's make a filter
    	var filter = $('<select id="td-filter"></select>').append($('<option value="ALL">All States</option>'));
    	for(var i=0; i<a.length; i++){
    		filter.append($('<option value="'+a[i]+'">'+a[i]+'</option>'));
    	}
    	$(tD).prepend(filter);
    	filter.bind('change',filterChange);
	}
	
	// On filter change, update data set
	function filterChange(){
		var state = $(this).val();
		debug("Filtering tour dates for "+state);
		$('#td-table tr').each(function(i, elem){
			if(state == 'ALL'){
				$(this).removeClass('hide');
			}else{
				($(this).attr('rel') != state) ? $(this).addClass('hide') : $(this).removeClass('hide');
			}
		});
	}
	
	// Trim whitespace from string and return
	function trimString(str){
		if(typeof str == 'object' || typeof str == 'string'){
			if(str){
				var new_str = $.trim(str.toString());
				return new_str;
			}else{
				return str;
			}
		}
	}
	
	// Return data array from object
	function settings(element) {
		return $.data(element,"tourdates");
	}
	
	// Debug for Firebug console (if available)
	function debug(obj){
		if(window.console && window.console.log && settings(tD).debug){
			switch(typeof obj){
				case 'string': case 'integer':
					window.console.log('Eos > '+obj); break;
				default:
					window.console.log(obj); break;
			}
		}
	}
	
	// Array prototype to get de-duped array
	Array.prototype.getUnique = function () {
		var o = new Object();
		var i, e;
		for (i = 0; e = this[i]; i++) {o[e] = 1};
		var a = new Array();
		for (e in o) {a.push (e)};
		return a;
	} 

})(jQuery);