/**
 * Create an instance of VCMSearchModal
 * @classDescription VCM Search Modal
 * @param {VCMPage} page Reference to the VCMPage
 * @return A new instance of VCMSearchModal
 * @constructor
 */
function VCMSearchModal(page) {
	this._page = page;
}

VCMSearchModal.prototype = {
	/**
	 * Reference to the VCMPage instance
	 * @type {VCMPage}
	 */
	_page: null,
	
	/**
	 * Locale for the jdPicker
	 * TODO: Locale should not be hardcoded in JS
	 * @type {Object}
	 */
	_jdPickerLocale: {FR:{
		month_names: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Decembre"],
		short_month_names: ["Jan", "Fev", "Mar", "Avr", "Mai", "Jun", "Jui", "Aou", "Sep", "Oct", "Nov", "Dec"],
		short_day_names: ["D", "L", "M", "M", "J", "V", "S"],
		error_out_of_range: "La date sélectionnée n'est pas autorisée",
		date_format: "YYYY-mm-dd"
	},EN:{
		// The jdPicker is already in english.
		date_format: "YYYY-mm-dd"
	}},
	
	_jTabs: null,
	_jDisciplines: null,
	_jDateFrom: null,
	_jDateFromClearer: null,
	_jDateTo: null,
	_jDateToClearer: null,
	_jLastMinute: null,
	_jAddSector: null,
	_jSectors: null,
	_jAddLocation: null,
	_jLocations: null,
	_jClose: null,
	_jShowResults: null,
	_jLocationSearch: null,
	_txtLocationSearch: null,
	_jAddDiscipline: null,
	_jAddEvent: null,
	_jEvents: null,
	_jRatings: null,
	_jArrows: null,
	
	_tabs: ['Discipline', 'Location', 'Sector', 'Event', 'Rating'],
	_params: null,
	_currentTab: null,
	_tabParams: null,
	_locations: null,
	_sectors: null,

	_jDateFromCalendar: null,
	_jDateToCalendar: null,
	
	/**
	 * Initialise the Search Modal
	 */
	init: function() {
		console.log('VCMSearchModal.init()');
		// Init data
		this._params = {};
		this._currentTab = 0;
		this._tabParams = [{}, {}, {}, {}, {}];
		this._locations = null;
		this._sectors = null;
		// Load content
		$.get(VCMUtils.prepareCommand({command:'displaySearch'}), $.proxy(this, '_init'));
	},
	
	_init: function(html) {
		console.log('VCMSearchModal._init(...)');
		this._page.getModal().show(html, $.proxy(this, 'destroy'));
		// Get jQuery reference
		this._jTabs = $('#searchModalTabs > a.btn').click($.proxy(this, 'onTabClick'));
		this._jClose = $('#searchModalFooter > a.btn:last').click($.proxy(this, 'onCloseClick'));
		this._jShowResults = $('#searchModalFooter > a.btn:first').click($.proxy(this, 'onShowResultsClick'));
		this._jArrows = $('.modalLeftArrow, .modalRightArrow').click($.proxy(this, 'onArrowClick'));
		this._jDateFromCalendar = $('.searchModalDateFromCalendar').click($.proxy(this, 'onDateFromCalendarClick'));
		this._jDateToCalendar = $('.searchModalDateToCalendar').click($.proxy(this, 'onDateToCalendarClick'));
		// Init tab
		this.initTab();
	},
	
	initTab: function() {
		console.log('VCMSearchModal.initTab()');		
		this.initArrows();
		// Highlight the current tab
		this._jTabs.filter(':eq(' + this._currentTab + ')').addClass('selected');
		// Display the current tab content
		$('#searchModalTabsContainer > .searchModalTabContent:eq(' + this._currentTab + ')').show();
		// Use saved params
		this._params = this._tabParams[this._currentTab];
		// Initialize component
		this['init' + this._tabs[this._currentTab]]();
	},
	
	/**
	 * Initialise the arrows
	 */
	initArrows: function() {
		// Reset
		this._jArrows.hide();
		// Left
		if (this._currentTab > 0) {
			this._jArrows.first().show();
		}
		// Right
		if (this._currentTab < this._tabs.length - 1) {
			this._jArrows.last().show();
		}
	},
	
	initDiscipline: function() {
		console.log('VCMSearchModal.initDiscipline()');
		this._jDisciplines = $('#cbDisciplines').change($.proxy(this, 'onDisciplineChange'));
		this.initDateFrom('#disciplineDateFrom', 'DateFrom');
		this.initDateTo('#disciplineDateTo', 'DateTo');
		this._jLastMinute = $('#chkLastMinute').click($.proxy(this, 'onLastMinuteClick'));
		this._jAddSector = $('#chkAddSector').click($.proxy(this, 'onAddSectorClick'));
		this._jSectors = $('#cbSectors').change($.proxy(this, 'onSectorChange'));
		this._jAddLocation = $('#chkAddLocation').click($.proxy(this, 'onAddLocationClick'));
		this._jLocations = $('#cbLocations').change($.proxy(this, 'onLocationChange'));		
	},
	
	initLocation: function() {
		console.log('VCMSearchModal.initLocation()');
		this._jLocationSearch = $('#locationSearch').keyup($.proxy(this, 'onLocationSearchKeyUp'))
				.focus($.proxy(this, 'onLocationSearchFocus')).blur($.proxy(this, 'onLocationSearchBlur'));
		this.initDateFrom('#locationDateFrom', 'DateFrom');
		this.initDateTo('#locationDateTo', 'DateTo');
		this._jLastMinute = $('#chkLocationLastMinute').click($.proxy(this, 'onLastMinuteClick'));
		// Retreive locations
		if (this._locations == null) {
			$.getJSON(VCMUtils.prepareCommand({url:'doJSON',command:'GetListItems','for':'locations'}), $.proxy(this, 'onLocationsJSON'));
		}
	},
	
	initSector: function() {
		console.log('VCMSearchModal.initSector()');
		this._jSectors = $('#cbSectorSectors').change($.proxy(this, 'onSectorSectorChange'));
		this.initDateFrom('#sectorDateFrom', 'DateFrom');
		this.initDateTo('#sectorDateTo', 'DateTo');
		this._jLastMinute = $('#chkSectorLastMinute').click($.proxy(this, 'onLastMinuteClick'));
		this._jAddDiscipline = $('#chkSectorAddDiscipline').click($.proxy(this, 'onAddDisciplineClick'));
		this._jDisciplines = $('#cbSectorDisciplines').change($.proxy(this, 'onSectorDisciplineChange'));
		this._jAddLocation = $('#chkSectorAddLocation').click($.proxy(this, 'onAddLocationClick'));
		this._jLocations = $('#cbSectorLocations').change($.proxy(this, 'onLocationChange'));
		this._jAddEvent = $('#chkSectorAddEvent').click($.proxy(this, 'onAddEventClick'));
		this._jEvents = $('#cbSectorEvents').change($.proxy(this, 'onEventChange'));
		
		if (this._sectors == null) {
			$.getJSON(VCMUtils.prepareCommand({url:'doJSON',command:'GetListItems','for':'sectors'}), $.proxy(this, 'onSectorsJSON'));
		}
	},
	
	initEvent: function() {
		console.log('VCMSearchModal.initEvent()');
		this.initDateFrom('#eventDateFrom', 'EventDateFrom');
		this.initDateTo('#eventDateTo', 'EventDateTo');
		this._jEvents = $('#cbEvents').change($.proxy(this, 'onSearchEventChange'));
		this._jLastMinute = $('#eventLastMinute').click($.proxy(this, 'onLastMinuteClick'));
		
		this.fetchItemList('event', this._jEvents, $.proxy(this, 'onSearchEventFetch'));
	},
	
	initRating: function() {
		this._jRatings = $('#cbRatings').change($.proxy(this, 'onRatingChange'));
		this.initDateFrom('#ratingDateFrom', 'DateFrom');
		this.initDateTo('#ratingDateTo', 'DateTo');
		this._jLastMinute = $('#ratingLastMinute').click($.proxy(this, 'onLastMinuteClick'));
		this._jAddSector = $('#ratingAddSector').click($.proxy(this, 'onAddSectorClick'));
		this._jSectors = $('#ratingSectors').change($.proxy(this, 'onSectorChange'));
		this._jAddDiscipline = $('#ratingAddDiscipline').click($.proxy(this, 'onAddDisciplineClick'));
		this._jDisciplines = $('#ratingDisciplines').change($.proxy(this, 'onSectorDisciplineChange'));
	},
	
	initDateFrom: function(id, evtName) {
		var lang = VCMUtils.getLang();
		this._jDateFrom = $(id).change($.proxy(this, 'on' + evtName + 'Change')); 
		if ($(id + ' ~ .date_clearer').length == 0) this._jDateFrom.jdPicker(this._jdPickerLocale[lang]);
		this._jDateFromClearer = $(id + ' ~ .date_clearer').click($.proxy(this, 'on' + evtName + 'ClearerClick'));
	},
	
	initDateTo: function(id, evtName) {
		var lang = VCMUtils.getLang();
		this._jDateTo = $(id).change($.proxy(this, 'on' + evtName + 'Change')); 
		if ($(id + ' ~ .date_clearer').length == 0) this._jDateTo.jdPicker(this._jdPickerLocale[lang]);
		this._jDateToClearer = $(id + ' ~ .date_clearer').click($.proxy(this, 'on' + evtName + 'ClearerClick'));
	},
	
	/**
	 * Destroy tab
	 * @TODO Don't use a global destroyer
	 */
	destroyTab: function() {
		console.log('VCMSearchModal.destroyTab()');
		// Unhighligth current tab
		this._jTabs.removeClass('selected');
		// Save current tab params
		this._tabParams[this._currentTab] = this._params;
		// Hide current tab content
		$('#searchModalTabsContainer > .searchModalTabContent:visible').hide();		
		// Remove events
		if (this._jDisciplines) this._jDisciplines.unbind('change');
		if (this._jDateFrom) this._jDateFrom.unbind('change');
		if (this._jDateFromClearer) this._jDateFromClearer.unbind('click');
		if (this._jDateTo) this._jDateTo.unbind('change');
		if (this._jDateToClearer) this._jDateToClearer.unbind('click');
		if (this._jLastMinute) this._jLastMinute.unbind('click');
		if (this._jAddSector) this._jAddSector.unbind('click');
		if (this._jSectors) this._jSectors.unbind('change');
		if (this._jAddLocation) this._jAddLocation.unbind('click');
		if (this._jLocations) this._jLocations.unbind('change');
		if (this._jLocationSearch) this._jLocationSearch.unbind('keyup');
		if (this._jAddDiscipline) this._jAddDiscipline.unbind('click');
		if (this._jAddEvent) this._jAddEvent.unbind('click');
		if (this._jEvents) this._jEvents.unbind('change');
		if (this._jRatings) this._jRatings.unbind('change');
		// Destroy jQuery reference
		this._jDisciplines = null;
		this._jDateFrom = null;
		this._jDateFromClearer = null;
		this._jDateTo = null;
		this._jDateToClearer = null;
		this._jLastMinute = null;
		this._jAddSector = null;
		this._jSectors = null;
		this._jAddLocation = null;
		this._jLocations = null;
		this._jLocationSearch = null;
		this._jAddDiscipline = null;
		this._jAddEvent = null;
		this._jEvents = null;
		this._jRatings = null;
	},

	/**
	 * Destroy the search modal
	 */
	destroy: function() {
		console.log('VCMSearchModal.destroy()');
		this.destroyTab();
		// Remove events
		this._jTabs.unbind('click');		
		this._jClose.unbind('click');
		this._jShowResults.unbind('click');
		this._jDateFromCalendar.unbind('click');
		this._jDateToCalendar.unbind('click');
		// Destroy jQuery reference
		this._jTabs = null;
		this._jDisciplines = null;
		this._jDateFrom = null;
		this._jDateFromClearer = null;
		this._jDateTo = null;
		this._jDateToClearer = null;
		this._jLastMinute = null;
		this._jAddSector = null;
		this._jSectors = null;
		this._jAddLocation = null;
		this._jLocations = null;
		this._jClose = null;
		this._jShowResults = null;
		this._jLocationSearch = null;
		this._jAddDiscipline = null;
		this._jAddEvent = null;
		this._jEvents = null;
		this._jRatings = null;
		this._jDateFromCalendar = null;
		this._jDateToCalendar = null;
		// Destroy data
		this._params = null;
		this._currentTab = null;
		this._tabParams = null;
		this._sectors = null;
		this._locations = null;
	},

	getSearchParams: function(params) {
		console.log('VCMSearchModal.getSearchParams(', params, ')');
		return $.extend({url: 'doJSON', command: 'Search'}, this._params, params);
	},
	
	fetchResults: function(type) {
		console.log('VCMSearchModal.fetchResults(', type,')');
		$.getJSON(VCMUtils.prepareCommand(this.getSearchParams()), function(data) {
			$('.searchModalTabContent:visible .searchModalResult').text(data.results);
		});
		if (this._jAddSector && this._jAddSector.attr('checked') && type !== 'sector') {
			this.fetchItemList('sector', this._jSectors, $.proxy(this, 'onSectorFetch'));
		}
		if (this._jAddLocation && this._jAddLocation.attr('checked') && type !== 'location') {
			this.fetchItemList('location', this._jLocations, $.proxy(this, 'onLocationFetch'));
		}
		if (this._jAddDiscipline && this._jAddDiscipline.attr('checked') && type !== 'discipline') {
			this.fetchItemList('discipline', this._jDisciplines, $.proxy(this, 'onDisciplineFetch'));
		}
		if (this._jAddEvent && this._jAddEvent.attr('checked') && type !== 'event') {
			this.fetchItemList('event', this._jEvents, $.proxy(this, 'onEventFetch'));
		}
	},

	fetchItemList: function(type, jEl, callback) {
		console.log('VCMSearchModal.fetchItemList(', type, jEl, callback, ')');
		var me = this;
		$.getJSON(VCMUtils.prepareCommand(this.getSearchParams({type:type})), function(json) {
			if (json && json[type + 's']) {
				var value = jEl.val();
				me.emptyItemList(jEl);
				me.fillItemList(jEl, json[type + 's']);
				jEl.val(value);
				if ($.isFunction(callback)) callback();
			}
		});
	},
	
	emptyItemList: function(jEl, keepFirst) {
		console.log('VCMSearchModal.emptyItemList(', jEl, keepFirst, ')');
		if (keepFirst === undefined) keepFirst = true;
		jEl.children().each(function(index, element) {
			if (index > 0 || !keepFirst) {
				$(element).remove();
			}
		});
	},
	
	fillItemList: function(jEl, items) {
		console.log('VCMSearchModal.fillItemList(', jEl, items, ')');
		var content = '';
		for(var value in items) {
			content += '<option value="' + value + '">' + items[value] + '</option>';
		}
		jEl.append(content);
	},
	
	resetItemList: function(jEl, paramName) {
		console.log('VCMSearchModal.resetItemList(', jEl, paramName, ')');
		this.emptyItemList(jEl);
		jEl.attr('disabled', true);
		delete this._params[paramName];
	},

	/**
	 * Convert a String to a Date
	 * @param {String} str A string representing a date in the format YYYY/MM/DD
	 * @return {Date} A Date object or null if the string cannot be converted
	 */
	stringToDate: function(str) {
		var re = new RegExp(/^(\d{4})\/(\d{1,2})\/(\d{1,2})$/);
		var matches = str.match(re);
		if (matches && matches.length == 4) {
			return new Date(matches[1], parseInt(matches[2]-1), matches[3]);
		}
		else {
			return null;
		}
	},

	/**
	 * Check if the date from is after the date to.
	 * If it's the case, put date from into date to.
	 */
	checkDateFromAfterDateTo: function() {
		var startDate = this.stringToDate(this._jDateFrom.val());
		var endDate = this.stringToDate(this._jDateTo.val());
		if (startDate && endDate && startDate.getTime() > endDate.getTime()) {
			this._jDateTo.val(this._jDateFrom.val());
			this._params.endDate = this._jDateTo.val();
		}
	},
	
	/**
	 * Check if the date to is before the date from.
	 * If it's the case, put date to into date from.
	 */
	checkDateToBeforeDateFrom: function() {
		var startDate = this.stringToDate(this._jDateFrom.val());
		var endDate = this.stringToDate(this._jDateTo.val());
		if (startDate && endDate && endDate.getTime() < startDate.getTime()) {
			this._jDateFrom.val(this._jDateTo.val());
			this._params.startDate = this._jDateFrom.val();
		}
	},

	/* ==================== EVENTS ==================== */
	/**
	 * On arrow click
	 * @param {Event} evt The Event object
	 * @return false
	 */
	onArrowClick: function(evt) {
		var jEl = $(evt.currentTarget);
		// Destroy current tab
		this.destroyTab();
		// Switch tab
		if (jEl.hasClass('modalLeftArrow')) {
			this._currentTab--;
		} else {
			this._currentTab++;
		}
		this.initTab();
		// Cancel default event
		return false;
	},
	
	/**
	 * On tab click
	 * @param {Object} evt The Event object
	 */
	onTabClick: function(evt) {
		console.log('VCMSearchModal.onTabClick(', evt, ')');
		this.destroyTab();
		this._currentTab = VCMUtils.findNumber($(evt.currentTarget).attr('id'));
		this.initTab();
		// Cancel default event
		return false;
	},
	
	onLocationsJSON: function(json) {
		console.log('VCMSearchModal.onLocationsJSON(', json, ')');
		if (json) {
			this._locations = json.locations;
		}
	},
	
	onSectorsJSON: function(json) {
		console.log('VCMSearchModal.onSectorsJSON(', json, ')');
		if (json) {
			var sectors = this._sectors = json.sectors;
			for(var id in sectors) {
				this._jSectors.append('<option value="' + id + '">' + sectors[id] + '</option>');
			}
		}
	},
	
	onLocationSearchKeyUp: function(evt) {
		console.log('VCMSearchModal.onLocationSearchKeyUp(', evt, ')');
		var txt = this._jLocationSearch.val();
		if (txt.length > 0) {
			var re = new RegExp(txt, 'i'),
				results = '',
				cpt = 0;
			for(var key in this._locations) {
				var value = this._locations[key];
				if (value.search(re) != -1) {
					results += '<a style="display:block;" href="#" id="lacr' + key + '">' + value + '</a>';
					cpt++;
				}
				if (cpt >= 15) break;
			}
			$('#locationResults').html(results).show();
			$('#locationResults > a').click($.proxy(this, 'onLocationClick'));
		} else {
			$('#locationResults').hide();
			this._jDateFrom.attr('disabled', true);
			this._jDateTo.attr('disabled', true);
			this._jLastMinute.attr('disabled', true);
		}
	},
	
	onLocationSearchFocus: function(evt) {
		console.log('VCMSearchModal.onLocationSearchFocus(', evt, ')');
		if (this._jLocationSearch.hasClass('empty')) {
			this._txtLocationSearch = this._jLocationSearch.val();
			this._jLocationSearch.val('');
			this._jLocationSearch.removeClass('empty');
		} else if (this._jLocationSearch.val().length > 0) {
			// TODO
			this.onLocationSearchKeyUp(evt);
		}
	},
	
	onLocationSearchBlur: function(evt) {
		console.log('VCMSearchModal.onLocationSearchBlur(', evt, ')');
		if (this._jLocationSearch.val() == '') {
			this._jLocationSearch.val(this._txtLocationSearch);
			this._jLocationSearch.addClass('empty');
		}
		$('#locationResults').delay(250).hide(0);
	},
	
	onLocationClick: function(evt) {
		console.log('VCMSearchModal.onLocationClick(', evt, ')');
		var jEl = $(evt.target);
		this._jLocationSearch.val(jEl.text());
		this._params.location = VCMUtils.findNumber(jEl.attr('id'));
		this.fetchResults();
		//
		this._jDateFrom.attr('disabled', false);
		this._jDateFrom.val('');
		this._jDateTo.attr('disabled', false);
		this._jDateTo.val('');
		this._jLastMinute.attr('disabled', false);
		this._jLastMinute.attr('checked', false);
	},
	
	onDisciplineChange: function(evt) {
		console.log('VCMSearchModal.onDisciplineChange(', evt, ')');
		// Reset everything else
		this.resetDateFrom();
		this.resetDateTo();
		this.resetLastMinute();
		this.resetAddSector();
		this.resetItemList(this._jSectors, 'sector');
		this._jAddLocation.attr('checked', false);
		delete this._params.addLocation;
		this.resetItemList(this._jLocations, 'location');
		//
		var discipline = this._jDisciplines.val();
		if (discipline == '') {
			delete this._params.discipline;
			this._jDateFrom.attr('disabled', true);
			this._jDateTo.attr('disabled', true);
			this._jLastMinute.attr('disabled', true);
			this._jAddSector.attr('disabled', true);
			this._jAddLocation.attr('disabled', true);
			$('.searchModalResult').text('');
		} else {
			this._params.discipline = discipline;
			this._jDateFrom.attr('disabled', false);
			this._jDateTo.attr('disabled', false);
			this._jLastMinute.attr('disabled', false);
			this._jAddSector.attr('disabled', false);
			this._jAddLocation.attr('disabled', false);
			this.fetchResults();
		}
	},
	
	onDateFromChange: function(evt) {
		console.log('VCMSearchModal.onDateFromChange(', evt, ')');
		this.checkDateFromAfterDateTo();
		this._params.startDate = this._jDateFrom.val();
		this.fetchResults();
	},
	
	onDateFromClearerClick: function(evt) {
		console.log('VCMSearchModal.onDateFromClearerClick(', evt, ')');
		this.resetDateFrom();
		this.fetchResults();
	},
	
	onDateToChange: function(evt) {
		console.log('VCMSearchModal.onDateToChange(', evt, ')');
		this.checkDateToBeforeDateFrom();
		this._params.endDate = this._jDateTo.val();
		this.fetchResults();
	},
	
	onDateToClearerClick: function(evt) {
		console.log('VCMSearchModal.onDateToClearerClick(', evt, ')');
		this.resetDateTo();
		this.fetchResults();
	},
	
	onLastMinuteClick: function(evt) {
		console.log('VCMSearchModal.onLastMinuteClick(', evt, ')');
		if (this._jLastMinute.attr('checked')) {
			this._params.lastMinute = 1;
		} else {
			this.resetLastMinute();
		}
		this.fetchResults();
	},
	
	onAddSectorClick: function(evt) {
		console.log('VCMSearchModal.onAddSectorClick(', evt, ')');
		if (this._jAddSector.attr('checked')) {
			this._jSectors.attr('disabled', false);
			this.fetchItemList('sector', this._jSectors, $.proxy(this, 'onSectorFetch'));
		} else {
			this.resetItemList(this._jSectors, 'sector');
			this.fetchResults();
		}
	},
	
	onSectorFetch: function(evt) {
		console.log('VCMSearchModal.onSectorFetch(', evt, ')');
		if (this._jSectors.val() == '') {
			delete this._params.sector;
			//this.fetchResults('sector');
		}
	},
	
	onSectorChange: function(evt) {
		console.log('VCMSearchModal.onSectorChange(', evt, ')');
		var sector = this._jSectors.val();
		if (sector == '') {
			delete this._params.sector;
		} else {
			this._params.sector = sector;
		}
		this.fetchResults('sector');
	},
	
	onAddLocationClick: function(evt) {
		console.log('VCMSearchModal.onAddLocationClick(', evt, ')');
		if (this._jAddLocation.attr('checked')) {
			this._jLocations.attr('disabled', false);
			this.fetchItemList('location', this._jLocations, $.proxy(this, 'onLocationFetch'));			
		} else {
			this.resetItemList(this._jLocations, 'location');
			this.fetchResults();
		}
	},
	
	onLocationFetch: function(evt) {
		console.log('VCMSearchModal.onLocationFetch(', evt, ')');
		if (this._jLocations.val() == '') {
			delete this._params.location;
			//this.fetchResults('location');
		}
	},
	
	onLocationChange: function(evt) {
		console.log('VCMSearchModal.onLocationChange(', evt, ')');
		var location = this._jLocations.val();
		if (location == '') {
			delete this._params.location;
		} else {
			this._params.location = location;
		}
		this.fetchResults('location');
	},
	
	onSectorSectorChange: function(evt) {
		console.log('VCMSearchModal.onSectorSectorChange(', evt, ')');
		// Reset everything else
		this.resetDateFrom();
		this.resetDateTo();
		this.resetLastMinute();
		this.resetAddDiscipline();
		this.resetItemList(this._jDisciplines, 'discipline');
		this._jAddLocation.attr('checked', false);
		delete this._params.addLocation;
		this._jAddEvent.attr('checked', false);
		delete this._params.addEvent;
		this.resetItemList(this._jEvents, 'event');
		//
		var sector = this._jSectors.val();
		if (sector == '') {
			delete this._params.sector;
			this._jDateFrom.attr('disabled', true);
			this._jDateTo.attr('disabled', true);
			this._jLastMinute.attr('disabled', true);
			this._jAddDiscipline.attr('disabled', true);
			this._jAddLocation.attr('disabled', true);
			this._jAddEvent.attr('disabled', true);
			$('.searchModalResult').text('');
		} else {
			this._params.sector = sector;
			this._jDateFrom.attr('disabled', false);
			this._jDateTo.attr('disabled', false);
			this._jLastMinute.attr('disabled', false);
			this._jAddDiscipline.attr('disabled', false);
			this._jAddLocation.attr('disabled', false);
			this._jAddEvent.attr('disabled', false);
			this.fetchResults();
		}
	},
	
	onAddDisciplineClick: function(evt) {
		console.log('VCMSearchModal.onAddDisciplineClick(', evt, ')');
		if (this._jAddDiscipline.attr('checked')) {
			this._jDisciplines.attr('disabled', false);
			this.fetchItemList('discipline', this._jDisciplines, $.proxy(this, 'onDisciplineFetch'));			
		} else {
			this.resetItemList(this._jDisciplines, 'discipline');
			this.fetchResults();
		}
	},
	
	onDisciplineFetch: function(evt) {
		console.log('VCMSearchModal.onDisciplineFetch(', evt, ')');
		if (this._jDisciplines.val() == '') {
			delete this._params.discipline;
			//this.fetchResults('discipline');
		}
	},
	
	onSectorDisciplineChange: function(evt) {
		console.log('VCMSearchModal.onSectorDisciplineChange(', evt, ')');
		var discipline = this._jDisciplines.val();
		if (discipline == '') {
			delete this._params.discipline;
		} else {
			this._params.discipline = discipline;
		}
		this.fetchResults('discipline');		
	},
	
	onAddEventClick: function(evt) {
		console.log('VCMSearchModal.onAddEventClick(', evt, ')');
		if (this._jAddEvent.attr('checked')) {
			this._jEvents.attr('disabled', false);
			this.fetchItemList('event', this._jEvents, $.proxy(this, 'onEventFetch'));			
		} else {
			this.resetItemList(this._jEvents, 'event');
			this.fetchResults();
		}		
	},
	
	onEventFetch: function(evt) {
		console.log('VCMSearchModal.onEventFetch(', evt, ')');
		if (this._jEvents.val() == '') {
			delete this._params.event;
			//this.fetchResults('event');
		}
	},
	
	onEventChange: function(evt) {
		console.log('VCMSearchModal.onEventChange(', evt, ')');
		var event = this._jEvents.val();
		if (event == '') {
			delete this._params.event;
		} else {
			this._params.event = event;
		}
		this.fetchResults('event');
	},
	
	onSearchEventChange: function(evt) {
		console.log('VCMSearchModal.onSearchEventChange(', evt, ')');
		this.resetLastMinute();
		var searchEvent = this._jEvents.val();
		if (searchEvent == '') {
			delete this._params.event;
			this._jLastMinute.attr('disabled', true);
			$('.searchModalResult').text('');
		} else {
			this._params.event = searchEvent;
			this._jLastMinute.attr('disabled', false);
			this.fetchResults();
		}
	},
	
	onSearchEventFetch: function(evt) {
		console.log('VCMSearchModal.onSearchEventFetch(', evt, ')');
		if (this._jEvents.val() == '') {
			delete this._params.event;
			//this.fetchResults('event');
		}
	},
	
	onEventDateFromChange: function(evt) {
		console.log('VCMSearchModal.onDateFromChange(', evt, ')');
		this.checkDateFromAfterDateTo();
		this._params.startDate = this._jDateFrom.val();
		this.fetchItemList('event', this._jEvents, $.proxy(this, 'onSearchEventFetch'));
	},
	
	onEventDateFromClearerClick: function(evt) {
		console.log('VCMSearchModal.onDateFromClearerClick(', evt, ')');
		this.resetDateFrom();
		this.fetchItemList('event', this._jEvents, $.proxy(this, 'onSearchEventFetch'));
	},
	
	onEventDateToChange: function(evt) {
		console.log('VCMSearchModal.onDateToChange(', evt, ')');
		this.checkDateToBeforeDateFrom();
		this._params.endDate = this._jDateTo.val();
		this.fetchItemList('event', this._jEvents, $.proxy(this, 'onSearchEventFetch'));
	},
	
	onEventDateToClearerClick: function(evt) {
		console.log('VCMSearchModal.onDateToClearerClick(', evt, ')');
		this.resetDateTo();
		this.fetchItemList('event', this._jEvents, $.proxy(this, 'onSearchEventFetch'));
	},
	
	onRatingChange: function(evt) {
		console.log('VCMSearchModal.onRatingChange(', evt, ')');
		// Reset everything else
		this.resetDateFrom();
		this.resetDateTo();
		this.resetLastMinute();
		this.resetAddSector();
		this.resetItemList(this._jSectors, 'sector');
		this.resetAddDiscipline();
		this.resetItemList(this._jDisciplines, 'discipline');
		//
		var rating = this._jRatings.val();
		if (rating == '') {
			delete this._params.rating;
			this._jDateFrom.attr('disabled', true);
			this._jDateTo.attr('disabled', true);
			this._jLastMinute.attr('disabled', true);
			this._jAddSector.attr('disabled', true);
			this._jAddDiscipline.attr('disabled', true);
			$('.searchModalResult').text('');
		} else {
			this._params.rating = rating;
			this._jDateFrom.attr('disabled', false);
			this._jDateTo.attr('disabled', false);
			this._jLastMinute.attr('disabled', false);
			this._jAddSector.attr('disabled', false);
			this._jAddDiscipline.attr('disabled', false);
			this.fetchResults();
		}		
	},
	
	/**
	 * On close click
	 * @param {Object} evt The Event object
	 */
	onCloseClick: function(evt) {
		console.log('VCMSearchModal.onCloseClick(', evt, ')');
		// Close the modal
		this._page.getModal().close();
		// Cancel default event
		return false;
	},
	
	/**
	 * On show result click
	 * @param {Object} evt The Event object
	 */
	onShowResultsClick: function(evt) {
		console.log('VCMSearchModal.onShowResultsClick(', evt, ')');
		// Load the result of the search in the content
		this._page.getContent().load(this.getSearchParams({url:'doAjax'}), true);
		// Close the modal
		this._page.getModal().close();
		// Select all dates
		this._page.getHeader().deselectDay();
		$('#allDates').addClass('selected');
		// Cancel default event
		return false;
	},
	
	/**
	 * Reset date from
	 */
	resetDateFrom: function() {
		// Reset form
		this._jDateFrom.val('');
		// Reset param
		delete this._params.startDate;
	},
	
	/**
	 * Reset date to
	 */
	resetDateTo: function() {
		// Reset form
		this._jDateTo.val('');
		// Reset param
		delete this._params.endDate;
	},
	
	/**
	 * Reset last minute
	 */
	resetLastMinute: function() {
		// Reset form
		this._jLastMinute.attr('checked', false);
		// Reset param
		delete this._params.lastMinute;
	},
	
	/**
	 * Reset add sector
	 */
	resetAddSector: function() {
		// Reset form
		this._jAddSector.attr('checked', false);
		// Reset param
		delete this._params.addSector;
	},
	
	/**
	 * Reset add discipline
	 */
	resetAddDiscipline: function() {
		// Reset form
		this._jAddDiscipline.attr('checked', false);
		// Reset param
		delete this._params.addDiscipline;
	},
	
	onDateFromCalendarClick: function(evt) {
		if (this._jDateFrom && !this._jDateFrom.attr('disabled')) {
			this._jDateFrom.focus();
		}
		return false;
	},
	
	onDateToCalendarClick: function(evt) {
		if (this._jDateTo && !this._jDateTo.attr('disabled')) {
			this._jDateTo.focus();
		}
		return false;
	}
};


