var ProjectFilter = new Class({
	initialize: function(map) {
		this.conditions = new Hash({});
		this.searchSummary =$('searchTerms');
		this.resetButton = $('reset');
		this.fieldEntries = $('projectList');
		this.searchSummery = $('searchSummery');
		this.totalProjects = $('totalProjects');
		this.resultsNumber = $('resultsNumber');
		this.markersProjectLink = null;
		this.validDate = false;
		this.prepareFacets();
		this.map = map;
		this.getTotalProjects();
		this.setDefaultConditions();
		this.updatePagingEvents();
	},
	
	resetAllFilters: function() {
		this.setDefaultConditions();
		this.removeCondition({}, 'continent');
		this.map.goToPage(1);
	},
	
	isIE6: function() {
		var arVersion = navigator.appVersion.split("MSIE")
		var version = parseFloat(arVersion[1])
		
		if ((version >= 5.5) && (document.body.filters))  {
			return true;
		} else {
			return false;
		}
	},
	
	setDefaultConditions: function() {
		this.conditions.empty();
		this.conditions.set('monthFinishedFromField', 1);
		this.conditions.set('monthFinishedToField', 12);
		this.conditions.set('siteroot', $('siteRootId').getText()); 
	},
	
	getTotalProjects: function() {
		var getRequest = new Json.Remote('/sbeos/ajax/JsonCall.php',
			{
				onComplete: function(result) {
					this.totalProjects.setHTML(result.count);
					this.resultsNumber.setHTML(result.count);
				}.bind(this)
			}
		).send({
			action: 'IUCNGetProjectCount'
		});
	},
	
	upadteProjectCount: function() {
		var postObject = new Hash({
			action: 'IUCNGetProjectCount'
		});
		postObject.merge(this.getConditions());
		var getRequest = new Json.Remote('/sbeos/ajax/JsonCall.php',
			{
				onComplete: function(result) {
					this.resultsNumber.setHTML(result.count);
				}.bind(this)
			}
		).send(postObject.obj);
	},
	
	prepareFacets: function() {
		$$('div.facet ul li').each(function(item) {
			item.addEvents({
				mouseover: this.facetItemMouseOver,
				mouseleave: this.facetItemMouseLeave,
				click: this.facetItemMouseClick.bindAsEventListener(this, item)
			});
		}.bind(this));
		
		this.resetButton.addEvent('click', this.resetAllFilters.bindAsEventListener(this));
		
		this.dateSelectionFields =$$('.dateSelection select'); 
		this.dateSelectionFields.each(function(item) {
			item.addEvent('change', this.dateChanged.bindAsEventListener(this, item));
		}.bind(this));
	},
	
	facetItemMouseOver: function() {
		this.addClass('hover');
	},
	
	facetItemMouseLeave: function() {
		this.removeClass('hover');
	},
	
	facetItemMouseClick: function(event, item) {
		this.addFacetCondition(item.getParent().getProperty('id'), item.getText().trim());
		if (item.getParent().getProperty('id') != 'continent') {
			this.refreshProjects();
		}
	},
	
	addFacetCondition: function(type, value) {
		//console.log(type);
		if (type == 'continent' && this.conditions.hasKey(type)) {
			//console.log('continent');
			if (this.conditions.hasKey('country')) {
				//console.log('remove country');
				this.removeCondition([], 'country', true);
			}
		}
		this.conditions.set(type, value);
		this.updateSearchSummary();
		if (!['monthFinishedFromField','monthFinishedToField','yearFinishedFromField','yearFinishedToField'].contains(type)) {
			this.upadteProjectCount();
			if (type != 'country') {
				this.map.goToPage(1);
			} else {
				//console.log('removeProjectMarkers');
				this.map.removeProjectMarkers();
			}
			
		}
	},
	
	updateSearchSummary: function() {
		this.searchSummary.empty();
		this.conditions.each(function(value, key) {
			if (!['monthFinishedFromField','monthFinishedToField','yearFinishedFromField','yearFinishedToField','siteroot'].contains(key) && value.trim() != '') {
				var elem = new Element('li', {
					'id': key
				});
				elem.setHTML(value);
				var span = new Element('span',{
					'events': {
						'click': this.removeCondition.bindAsEventListener(this,key)
					}
				});
				span.setHTML(' x');
				span.injectInside(elem);
				elem.injectInside(this.searchSummary);
			}
			else if (['yearFinishedFromField','yearFinishedToField'].contains(key)) {
				if ($('date')) {
					$('date').remove();
				}
				if ((this.conditions.hasKey('yearFinishedFromField') && this.conditions.get('yearFinishedFromField') != '')
					&& (this.conditions.hasKey('yearFinishedToField') && this.conditions.get('yearFinishedToField') != '')) {
					var elem = new Element('li', {
						'id': 'date'
					});
					elem.setHTML(this.conditions.get('yearFinishedFromField')+' - '+this.conditions.get('yearFinishedToField'));
					var span = new Element('span',{
						'events': {
							'click': this.removeCondition.bindAsEventListener(this,key)
						}
					});
					span.setHTML(' x');
					span.injectInside(elem);
					elem.injectInside(this.searchSummary);
				}
			}
		}.bind(this));
	},
	
	removeCondition: function(event, key, noRefresh) {
		this.conditions.remove(key);
		this.updateSearchSummary();
		if (['yearFinishedFromField','yearFinishedToField'].contains(key)) {
			$('yearFinishedFromField').value = '';
			$('yearFinishedToField').value = '';
		}
		if (key == 'country') {
			this.markersProjectLink = null;
			this.map.removeProjectMarkers();
			this.map.showCurrentMarker();
			this.map.goToCoordinates(this.map.currentContinentLoaction, 3);
		}
		
		if (key == 'continent') {
			this.removeCondition(event, 'country', noRefresh);
			this.map.reset();
		} else {
			if (!noRefresh) {
				this.refreshProjects();
			}
			this.upadteProjectCount();
			this.map.goToPage(1);
		}
	},
	
	dateChanged: function(event, item) {
		var valid = true;
		this.dateSelectionFields.each(function(dateSelect) {
			if (dateSelect.getProperty('value') == '') {
				valid = false;
			}
			this.addFacetCondition(dateSelect.getProperty('id'), dateSelect.getProperty('value'));
		}.bind(this));
		if (valid === true || this.validDate === true) {
			this.refreshProjects();
			this.upadteProjectCount();
			this.map.goToPage(1);
		}
		this.validDate = valid;
	},
	
	refreshProjects: function() {
		this.map.refreshProjects(this.conditions);
	},
	
	getConditions: function() {
		var copy = this.conditions.obj;
		return copy;
	},
	
	updateFieldEntries: function(pages, projectMarkers) {
		this.fieldEntries.setHTML(pages);
		this.updatePagingEvents();
		if (projectMarkers.pageingMarkers) {
			this.markersProjectLink = new Hash(projectMarkers.pageingMarkers);
		}
		if (this.markersProjectLink && this.markersProjectLink.length > 0) {
			this.markersProjectLink.each(function(item, markerId) {
				item.markers.each(function(projectId) {
					if ($('project_'+projectId)) {
						// on this page
						if (item.type == 'normal') {
							type = 'id';
						} else {
							type = 'idCollection';
						}
						var image = new Element('img', {
							src: '/images/countIcon.php?type='+type+'&size='+markerId,
							alt: 'Project '+markerId,
							width: 58,
							height: 50
						});
						image.addClass('projectIcon');
						image.injectTop($('project_'+projectId));
						if (this.isIE6()) {
							
							pngFix(image);
						}
					}
				}.bind(this));
			}.bind(this));
		}
	},
	
	updatePagingEvents: function() {
		$$('.projectPaging li a').each(function(item) {
			item.addEvent('click', this.goToPage.bindAsEventListener(this, item));
		}.bind(this));
	},
	
	goToPage: function(event, page) {
		var re = new RegExp('#page(.*)', 'gi');
		var pages = re.exec(page);
		this.map.goToPage(pages[1]);
	},
	
	clearFieldEntry: function() {
		this.fieldEntries.empty();
	}
});