(function(jQuery){
	jQuery.fn.liveDepartureBoard = function(options)
		{
		    var options = jQuery.extend(jQuery.fn.liveDepartureBoard.defaults, options || {});

			return this.each(
				function()
				{
					var container = jQuery(this);
					container.options = options;

					container.wrapInner('<div class="board-content"></div>');
					container.append('<div class="board-loading" style="display: none;"></div>');

					setTimeout(function() { jQuery.fn.liveDepartureBoard.update(container); }, options.refresh);
				}
				);
		};

	jQuery.fn.liveDepartureBoard.update = function(element)
		{
			var loader = element.find('> div.board-loading');
			var content = element.find('> div.board-content');

			loader.show();
			content.hide();
			
			jQuery.ajax(
				{
					type: 'GET',
					url: interfaceBaseURI + '/custom/get_live_departure_board',
					data:
						{
							type: element.options.type,
							station_code: element.options.stationCode,
							item_limit: element.options.itemLimit
						},
					success: function(jsonString)
						{
							try
							{
								response = eval('(' + jsonString + ')');

								var html = '';
								html = '<table cellspacing="0">';
								html += '<tr>';
								html += '<th>Station</th>';
								html += '<th>Scheduled</th>';
								html += '<th>Expected</th>';
								html += '</tr>';

								for(var i = 0; i < response.train_service_list.length; i ++)
								{
									html += '<tr>';
									html += '<td' + ((i == (response.train_service_list.length - 1)) ? ' class="last"' : '') + '>' + response.train_service_list[i].destination.station_name + '</td>';
									html += '<td' + ((i == (response.train_service_list.length - 1)) ? ' class="last"' : '') + '>' + response.train_service_list[i].departure_time_scheduled + '</td>';
									html += '<td class="no-right-border"' + ((i == (response.train_service_list.length - 1)) ? ' last' : '') + '">' + response.train_service_list[i].departure_time_estimated + '</td>';
									html += '</tr>';
								}

								html += '</table>';

								content.html(html);
							}
							catch(e)
							{
							}

							loader.hide();
							content.show();
							setTimeout(function() { jQuery.fn.liveDepartureBoard.update(element); }, element.options.refresh);
						}
				}
				);
		}

	// Default options
	jQuery.fn.liveDepartureBoard.defaults =
		{
	        type: 'departure',
	        stationCode: '',
	        itemLimit: 10,
			refresh: 60000
		};
})(jQuery);
