var common = {
	name: 'common',
	NONE: 'NONE',
	year: null,
	COLOUR_POOR:'#ed1c24',
	COLOUR_SUFFICIENT:'#4cbd38',
	COLOUR_GOOD: '#00adef',
	NOT_SPECIFIED: 'Not specified',
	RIVER_BASIN: 'riverBasin',
	COUNTY: 'county',
	NATIONAL: 'ireland',
	BATHING_LOCATION: 'beach',
	KEY_POOR: "Poor",
	KEY_SUFFICIENT: "Sufficient",
	KEY_GOOD: "Good",
	KEY_UNDEFINED: "Undefined",
	TREND_UP: 1,
	TREND_STATIC: 0,
	TREND_DOWN: -1,
	connections: null,
	controller: null,
	bathingLocations: [],
	setController: function(controller) {
		common.controller = controller;
	},
	connectEvents: function() {
		common.connections = [];
		common.connections[0] = dojo.connect(dijit.byId("rbSelect"), "onChange", common.filterLocationsByBasin);
		common.connections[1] = dojo.connect(dijit.byId("countySelect"), "onChange", common.filterLocationsByCounty);
	},
	disconnectEvents: function() {
		dojo.forEach(common.connections, dojo.disconnect);
	},
	populateBathingLocations: function(locations) {
		common.bathingLocations=locations.slice(1);
	},
	getBathingLocationKeys: function() {
		var keys=[];
//i changed 1 to 0 for i variable 
		for (var i=0; i<common.bathingLocations.length; i++) {
		    keys[i]=common.bathingLocations[i].key;
		}

		return keys;
	},
	getBathingLocationName: function(key) {
		for (var i=0; i<common.bathingLocations.length; i++) {
		    if (common.bathingLocations[i].key===key) {
			return common.bathingLocations[i].value;
		    }
		}
		return null;
	},
	loadDates: function() {
		var startYear = 2003;
		var lastYear =common.year===null?new Date().getFullYear() -1:common.year;
		for (i=startYear; i<=lastYear; i++) {
			common.addToOptionList('yearFrom', i, i);
			common.addToOptionList('yearTo', i, i);
		}
		dijit.byId('yearFrom').store.fetch();
		dijit.byId('yearTo').store.fetch();
		dijit.byId('yearFrom').setValue(startYear);
		dijit.byId('yearTo').setValue(lastYear);
	},
	loadLocations: function() {
		common.controller.getRiverBasins(function(basins){
			common.addOptions('rbSelect', basins);
			dijit.byId('rbSelect').store.fetch();
			common.resetSelect('rbSelect');
		});
		common.controller.getCounties(function(counties){
			common.addOptions('countySelect', counties);
			dijit.byId('countySelect').store.fetch();
			common.resetSelect('countySelect');
		});
	},
	filterLocationsByCounty: function() {
		common.disconnectEvents();
		common.resetSelect('rbSelect');
		common.clearOptions('locationSelect');
		common.controller.getLocationsForParent(dijit.byId('countySelect').getValue(), function(locations) {
			common.populateBathingLocations(locations);
			common.addOptions('locationSelect', locations);
			common.resetSelect('locationSelect');
			common.connectEvents();
		});
	},
	filterLocationsByBasin: function() {
		common.disconnectEvents();
		common.resetSelect('countySelect');
		common.clearOptions('locationSelect');
		common.controller.getLocationsForParent(dijit.byId('rbSelect').getValue(), function(locations) {
			common.populateBathingLocations(locations);
			common.addOptions('locationSelect', locations);
			common.resetSelect('locationSelect');
			common.connectEvents();
		});
	},
	validateDateRange: function() {
		var yearFrom = dojo.byId('yearFrom');
		var yearTo = dojo.byId('yearTo');
		var thisYear = new Date().getFullYear();
		var result = true;
		if (yearFrom.value > yearTo.value) {
			result = false;
		}
		return result;
	},
	resetSelect: function(selectId) {
		common.setSelect(selectId, common.NONE);
	},
	setSelect: function(selectId, value) {
		dijit.byId(selectId).setValue(value);
	},
	clearOptions: function(selectId) {
		dijit.byId(selectId).store.root.innerHTML = "";
	},
	addOptions: function(selectId, locations) {
		for(i=0; i<locations.length; i++) {
			common.addToOptionList(selectId, locations[i].key, locations[i].location);
		}
	},
	addToOptionList: function(selectId, optionValue, optionText) {
		var l = dijit.byId(selectId).store.root.options.length;
		dijit.byId(selectId).store.root.options[l] = new Option(optionText, optionValue);
	},
	isNotSpecified: function(name) {
		return (name === null || name === common.NONE || name === common.NOT_SPECIFIED || name === '');
	},
	getDefaultLocationSelection: function() {
		return {
		    riverBasin: null, 
		    riverBasinName: common.NOT_SPECIFIED, 
		    county: null,
		    countyName: common.NOT_SPECIFIED, 
		    bathingLocation: null,
		    bathingLocationName: common.NOT_SPECIFIED
		};
	},
	getLocationSelection: function() {
		var locationSelection = {
		    riverBasin:dijit.byId('rbSelect').getValue(), 
		    riverBasinName:dijit.byId('rbSelect').getDisplayedValue(), 
		    county:dijit.byId('countySelect').getValue(),
		    countyName:dijit.byId('countySelect').getDisplayedValue(), 
		    bathingLocation:dijit.byId('locationSelect').getValue(),
		    bathingLocationName:dijit.byId('locationSelect').getDisplayedValue()
		};

		if (locationSelection.riverBasin === null && locationSelection.county === null) {
			return {
				    riverBasin: null, 
				    riverBasinName: common.NOT_SPECIFIED, 
				    county: null,
				    countyName: common.NOT_SPECIFIED, 
				    bathingLocation: null,
				    bathingLocationName: common.NOT_SPECIFIED
			};
		}
		return locationSelection;
	},
	getLocationType: function(locationSelection) {
		if (common.isNotSpecified(locationSelection.riverBasin) && common.isNotSpecified(locationSelection.county) &&
				common.isNotSpecified(locationSelection.bathingLocation)){
			return common.NATIONAL;
		}
		if (!common.isNotSpecified(locationSelection.bathingLocation)){
			return common.BATHING_LOCATION;
		}
		if (!common.isNotSpecified(locationSelection.riverBasin)){
			return common.RIVER_BASIN;
		}
		if (!common.isNotSpecified(locationSelection.county)){
			return common.COUNTY;
		}
		return common.NATIONAL;
	},
	getLocationName: function(locationSelection) {
		if (common.getLocationType(locationSelection) === common.NATIONAL) {
			return "Ireland";
		} else if (common.getLocationType(locationSelection) === common.RIVER_BASIN) {
			return locationSelection.riverBasinName;
		} else if (common.getLocationType(locationSelection) === common.COUNTY) {
			return locationSelection.countyName;
		} else {
			return locationSelection.bathingLocationName;
		}
	},
	getDateRange: function() {
		return {from:dojo.byId('yearFrom').value, to:dojo.byId('yearTo').value};
	},
	getDatesFromDateRange: function() {
		var dateRange = common.getDateRange();
		var dates = [];
		var i=0;
		var year = dateRange.from;
		while(year <= dateRange.to) {
			dates[i] = new Date();
			dates[i++].setFullYear(year++);
		}
		return dates;
	},
	updateMap: function(locationSelection, dateRange) {
		common.controller.getMapPosition(locationSelection, function(position) {
			var key = common.getLocationKeyAndType(locationSelection).key;
			var type = common.getLocationKeyAndType(locationSelection).type;
			var zoom = common.getZoomLevel(locationSelection);
			var lat = (position === null) ? null : position.lat;
			var lon = (position === null) ? null : position.lon;
			epaMap.to(key, type, lat, lon, zoom);
		});
		common.refreshBathingLocations(locationSelection, dateRange);
	},
	refreshBathingLocations: function(locationSelection, dateRange) {
		common.controller.getBathingLocations(locationSelection, dateRange, function(locationStatusSet){
			epaMap.clearbeaches();
			for ( var i = 0; i < locationStatusSet.length; i++) {
				var locationStatus = locationStatusSet[i];
				var location = locationStatus.location;
				if (locationStatus.statusSeries === null) {
					continue;
				}
				var values = locationStatus.statusSeries.values;
				if (location.position !== null) {
					var status = (values.length > 0) ? values[values.length - 1] : null;
					epaMap.addbeach(location, status, 0);
				}
			}
		});
	},
	getZoomLevel: function(locationSelection) {
		var locationType = common.getLocationType(locationSelection);
		if (locationType === common.NATIONAL) {
			return 6;
		}
		else if (locationType === common.RIVER_BASIN) {
			return 7;
		}
		else if (locationType === common.COUNTY) {
			return 8;
		}
		else {
		    return 12;
		}
	},
	getLocationKeyAndType: function(locationSelection) {
		if(common.isBlank(locationSelection.bathingLocation) && common.isBlank(locationSelection.riverBasin) && common.isBlank(locationSelection.county)) {
			return {type:"IRELAND", key:'IRELAND'};
		}
		if (common.isBlank(locationSelection.bathingLocation)) {
			return common.isBlank(locationSelection.riverBasin) ? {type:"COUNTY", key:locationSelection.county} : {type:"RBD", key:locationSelection.riverBasin};
		}
		return {type:"BEACH", key:locationSelection.bathingLocation};
	},
	isBlank: function(str) {
	    return str===null || str===undefined || str==='' || str==='NONE';
	},
	updateBeachPopupInfo: function(idbw) {
		common.controller.getBeachInfoFromKey(idbw, function(beachInfo){
			$('#blueFlagPopup').text(beachInfo.blueFlag);
		});
	}
};
