(function($) {
	
	var ec3,
	cal,
	month,
	year,
	cat='',
	
	settings = {
		prev: '#ec3_prev',
		next: '#ec3_next',
		month: '#month',
		loader: '#ec3_loader'
	};

	ec3 = jQuery.fn.eventcalendar = function() {
			
		cal = this;
	
		_init = function(){
		
			var date_data = $('table:first',cal).attr('id').split('_');
			month = parseFloat(date_data[2]);
			year = parseFloat(date_data[1]);
			
			$(settings.prev,cal).unbind('click').bind('click',function(){
				ec3._prev_month();
				return false;
			});
			
			$(settings.next,cal).unbind('click').bind('click',function(){
				ec3._next_month();
				return false;
			});
			
			var xcat = new RegExp('&cat=[0-9]+$');
			var match = xcat.exec( $(settings.month,cal).attr('href') );
			if(match) cat=match[0];
			
			ec3._end_load();
			
		}
		
		ec3._prev_month = function(){
		
			//ec3._start_load();
			
			month--;
			if(month==0){
				year--;
				month = 12;
			}
			
			ec3._create_calendar();
			
			
			
		}
		
		ec3._next_month = function(){
		
			//ec3._start_load();
			
			month++;
			if(month==13){
				year++;
				month = 1;
			}
			
			ec3._create_calendar();
			
		}
			
		ec3._create_calendar = function(){
			
			// Hide all tables
			$('table',cal).hide();
			
			// Change the month's URL
			if(month<10){
				href=_ec3.home+'/?m='+year+'0'+month+cat;
			} else {
				href=_ec3.home+'/?m='+year+month+cat;
			}			
			$(settings.month,cal).html( _ec3.month_abbrev[month-1] + " " + year ).attr({'href':href});
			
			// Check to see if table exists - show if it does			
			if( $('#ec3_'+year+'_'+month,cal).length ){
				$('#ec3_'+year+'_'+month,cal).show();
				return false;
			}
			
			// Show loading spinner
			ec3._start_load();
			
			// Create new table if does not already exist
			var newcal = $('table:first',cal).clone();
			$(cal).append(newcal);
			
			// Change table ID
			$(newcal).show().attr({'id':'ec3_'+year+'_'+month});
			
			// Empty calendar content
			$('tbody',newcal).empty();
			
			// Create date object
			var date = new Date(year,month-1,1, 12,00,00);
				
			// Start creating table elements
			var tr = $('<tr>');
		    var td,div;
		    $('tbody',newcal).append( $(tr) );
		    var day_count=0;
		    var col=0;
		    
		    // Loop through days
		    while(date.getMonth() == (month-1) && day_count<40) {
				var day = (date.getDay()+7-_ec3.start_of_week)%7;
				if(col>6) {
					tr = $('<tr>');
					$('tbody',newcal).append( $(tr) );
					col=0;
				}
				if(col<day) {
					// Insert padding
					td = $('<td>');
					$(td).attr({'colspan':day-col});
					$(td).addClass('pad');
					$(tr).append( $(td) );
					col = day;
				}
				// Insert day
				td = $('<td>');
				$(td).html( date.getDate() );
				$(td).attr({'id':'ec3_'+year+'_'+month+'_'+date.getDate()});
				$(tr).append( $(td) );
				col++;
				day_count++;
				date.setDate(date.getDate()+1);
			}
			// Insert padding
			if(col<7) {
				td = $('<td>');
				$(td).attr({'colspan':7-col});
				$(td).addClass('pad');
				$(tr).append( $(td) );
			}
			
			ec3._process_xml();

		}
		
		ec3._process_xml = function(){
			$.ajax({
				url:ec3.home+'/?ec3_xml='+year+'_'+month,
				type:"GET",
				dataType:"xml",
				success:function(xml){
				    $(xml).find('day').each(function(){
				    	var td = $('td#'+$(this).attr('id'),cal);
				      	
				        var txt = $(td).html();
				        $(td).addClass('ec3_postday').empty();
				        
				        var a = $('<a>');
				        $(a).attr({ 'href':$(this).attr('link') });
				  		var title = $(this).attr('titles');
				  		
				  		ec3._tooltip(a,title);
						
				        if( $(this).attr('is_event') ){
							$(td).addClass('ec3_eventday');
							$(a).addClass('eventday');
				        }
				        $(a).html(txt);
				        $(td).append( $(a) );
				    });
				        
					ec3._end_load();
				},
				error:function(){
					ec3._end_load();
				}
			});
		}
		
		ec3._tooltip = function(a,title){
			var tooltip = '<ul>';
	  		var title_data = title.split(', ');
	  		var alt = '';
	  		$(title_data).each(function(){
	  			var time_data = this.split('@');
	  			tooltip += '<li'+alt+'>'+time_data[0]+'<span>'+time_data[1]+'</span></li>';
	  			if( alt=='' ){
	  				alt = ' class="alt"';
	  			} else {
	  				alt = '';
	  			}
	  		});
	  		tooltip += '</ul>';
	  		
	  		$(a).tooltip({
				bodyHandler: function() {
					return tooltip;
				},
				left:-185,
				track: true,
				delay:0,
				showURL: false
			});
		}
		
		ec3._start_load = function(){		
			$(settings.loader,cal).show();			
		}
		
		ec3._end_load = function(){		
			$(settings.loader,cal).stop(true,true).fadeOut(200);			
		}
		
		_init();
		return this;
	
	};
	
})(jQuery);

jQuery(document).ready(function($){
	$('#wp-calendar').eventcalendar();
	$('#wp-calendar table a').each(function(){
		var title = $(this).attr('title');		
		$.fn.eventcalendar._tooltip(this,title);	
	});       
});
