/**
 * The files containing the news for each year. 
 * The file entries musst be in following JSON-format: 
 * {"quater":"1","categoryId": "1","content": "html content"}
 */
var $news_files = new Array();

/**
 * The currently displayed news entries retrieved 
 * from JSON-file.
 */
var _news = new Array();

/**
 * The currently selected filter options.
 */
var _selectedFilter = { 
		"year": "-1",
		"quarter": "0",
		"categoryId": "-1"
};

/**
 * The controlls to filter and display the news data.
 */
var $controlls = {
		"year": "",
		"quarter": "",
		"category": "",
		"table": "",
		"options":
		{
			"no_entries": "",
			"error": ""
		}
};

/**
 * Initializing the table an bind the listeners 
 * to the selectboxes.
 */
jQuery(document).ready(function() {
	setupControlls();
	initDefaults();
	initSelectBoxes();
	loadNews();
});

/**
 * This function initializes the default values based 
 * on the available options in the year selectbox.
 */
function initDefaults() {
	// Getting current date and year
	var currentDate = new Date();
	var currentYear = currentDate.getFullYear();

	// Determine the maximum available value in the year select box
	// and set it as default value.
	var availableMaxYear = -1;
	if(!$controlls.year.isNull) {
		$controlls.year.each(function () {
			 jQuery('option', this).each(function() {
					if(jQuery(this).val() > availableMaxYear) {
						availableMaxYear = jQuery(this).val();
					}
				  })
		});
	}
	
	// If the available maximum of the year select box is lower than 
	// the current year set the selected quarter to 4 and the year to the maximum 
	// otherwise use the current year and current quarter.
	if(availableMaxYear >= currentYear || availableMaxYear == -1) {
		_selectedFilter.year = currentYear;
//		_selectedFilter.quarter = Math.floor((currentDate.getMonth() / 3)) + 1;
	}
	else {
		_selectedFilter.year = availableMaxYear;
//		_selectedFilter.quarter = 4;
	}
}


/**
 * Sets up the select boxes used to filter the table
 * and the table itself.
 */
function setupControlls() {
	$controlls.year = jQuery('#selectboxYear');
	$controlls.quarter = jQuery('#selectboxQuarter');
	$controlls.category = jQuery("#selectboxCategory");
	$controlls.table = jQuery("#news_arch_tab tbody");
}

/**
 * Binds the event listeners to the selectboxes and set 
 * the default options based on the previously determined
 * values.
 */
function initSelectBoxes() {
	if (!$controlls.year.isNull) {
		$controlls.year.val(_selectedFilter.year);
		// bind the select box to select the year.
		$controlls.year.bind('change', function() {
			var year = $controlls.year.val()
			if (year != null && year != _selectedFilter.year
					&& year <= new Date().getFullYear()) {
				_selectedFilter.year = year;
				resetQuarterFilter();
				loadNews();
			}
		});
	}

	if (!$controlls.quarter.isNull) {
		$controlls.quarter.val(_selectedFilter.quarter);
		// bind the select box to select the quarter.
		$controlls.quarter.bind('change', function() {
			var quarter = $controlls.quarter.val();
			if (quarter != null && 
				quarter != _selectedFilter.quarter && 
				quarter >= 0 && quarter <= 4) {
				_selectedFilter.quarter = quarter;
				updateTable();
			}
		});
	}
	if (!$controlls.category.isNull) {
		// bind the select box to select categories
		$controlls.category.bind('change', function() {
			var categoryId = $controlls.category.val();
			if (categoryId != null) {
				_selectedFilter.categoryId = categoryId;
				resetQuarterFilter();
				updateTable();
			}
		});
	}
}

/**
 * Loads the news from the given json file containing 
 * the news for one year and updates the table. 
 */
function loadNews() {
	// Only load the news for one year if nessacary
	// otherwise just update the table.
	if(_news[_selectedFilter.year] == null) {
		// Create a new Array for the news content of one year.
		_news[_selectedFilter.year] = new Array();
		jQuery.getJSON($news_files[_selectedFilter.year], function(data) {
			jQuery.each(data, function(key, val) {
				_news[_selectedFilter.year].push(val);
			});
	
		}).complete(function() {
			// Update table content after loading is complete.
			updateTable();
		}).error(function() {
			_news[_selectedFilter.year] = "ERROR";
			updateTable();
		});
	}
	else {
		updateTable();
	}
}

/**
 * Clears the news table and insert all news entries
 * that fit the selected filter.
 */
function updateTable() {
	if(!$controlls.table.isNull) {
		//Clear the table
		$controlls.table.children().remove();
		if(_news[_selectedFilter.year] != "ERROR") {
			var counter = 0;
			// Add all entries that fit the selected filter
			jQuery.each(_news[_selectedFilter.year], function(i, entry) {
				if ((entry.quarter == _selectedFilter.quarter || _selectedFilter.quarter == 0)
						&& (entry.categoryId == _selectedFilter.categoryId || _selectedFilter.categoryId == -1)) {
					$controlls.table.append(entry.content);
					counter++
				}
			});
			if(counter == 0) {
				// Print note for no entries in table.
				$controlls.table.append($controlls.options.no_entries);
			}
		} else {
			// Print error note.
			$controlls.table.append($controlls.options.error);
		}
	}
}

/**
 * Resets the filter for the quater of a year.
 */
function resetQuarterFilter() {
	if(!$controlls.quarter.isNull) {
		$controlls.quarter.val(0);
		$controlls.quarter.trigger('change');
	}
}
