var epa = {
	name:'epa',

	init: function(mapType) {
		common.setController(historyController);
		common.connectEvents();
		common.loadDates();
		common.loadLocations();
		dijit.byId('rightPane').selectChild('compliance');
		if (mapType==='gMap') {
		    epaMap.setObj(epaMapGoogle);
		}
		else {
		    epaMap.setObj(epaMapArc);
		}

		dojo.connect(dijit.byId("mandatoryVsGuideComplianceChartTab").controlButton,"onClick", epa.updateTrendChart);
		dojo.connect(dijit.byId("mandatoryVsGuideComplianceTreeTab").controlButton,"onClick", epa.updateGuideVsMandatoryTable);

		epaMap.load('map', function(beach) {
			common.disconnectEvents();
		    common.setSelect('rbSelect','NONE');
		    common.clearOptions('locationSelect');
		    common.resetSelect('locationSelect');
		    historyController.getParentLocationKey(beach, function(localAuthority){
		    	common.setSelect('countySelect', localAuthority);
				historyController.getSiblingLocations(beach, function(locations){
					common.addOptions('locationSelect', locations);
					common.setSelect('locationSelect', beach);
					epa.updateAll();
					common.connectEvents();
				});
		    });
		}, function() {
		    // Called when the map is ready
		    epa.updateAll();
		}, function() {
		    // Called when the map wants to reset the selection
			var dateRange = common.getDateRange();
			var locationSelection = common.getDefaultLocationSelection();
		    common.resetSelect('rbSelect');
		    common.resetSelect('countySelect');
		    common.clearOptions('locationSelect');
		    common.refreshBathingLocations(locationSelection, dateRange);
		    epa.updateAggregateView(locationSelection, dateRange);
		});
	},
	updateAll: function() {
		if(!common.validateDateRange()){
			return;
		}
		var locationSelection = common.getLocationSelection();
		var dateRange = common.getDateRange();
		var locationType = common.getLocationType(locationSelection);
		
		epa.updateAssessmentText(locationSelection, dateRange);
		common.updateMap(locationSelection, dateRange);
		
		if (locationType == common.BATHING_LOCATION) {
			dijit.byId("rightPane").selectChild("beach");
			epa.updateBeachTable(locationSelection, dateRange);
			epa.updateBeachPhenomenonTable(locationSelection, dateRange);
			epa.updateMapTitle(locationSelection, dateRange);
		}
		else {
			epa.updateAggregateView(locationSelection, dateRange);
		}
	},
	updateAggregateView: function(locationSelection, dateRange) {
		dijit.byId("rightPane").selectChild("compliance");
		$('#pieChartYear').text(dateRange.to);
		charts.updatePieChart(locationSelection, dateRange);
		if (dijit.byId('tabPane2').selectedChildWidget.id == 'mandatoryVsGuideComplianceChartTab') {
			charts.updateTrendChart(locationSelection, dateRange);
		} else if (dijit.byId('tabPane2').selectedChildWidget.id == 'mandatoryVsGuideComplianceTreeTab') {
			epa.updateComplianceTable(locationSelection, dateRange);
		}
		epa.updateTable(locationSelection, dateRange);
		epa.updateMapTitle(locationSelection, dateRange);
	},
	updatePieChart: function() {
		charts.updatePieChart(common.getLocationSelection(), common.getDateRange());
	},
	updateTrendChart: function() {
		charts.updateTrendChart(common.getLocationSelection(), common.getDateRange());
	},
	updateGuideVsMandatoryTable: function() {
		epa.updateComplianceTable(common.getLocationSelection(), common.getDateRange());
	},
	updateMapTitle: function(locationSelection, dateRange) {
		$('#mapTitle1').text(dateRange.to + " ");
		$('#mapTitle2').text(common.getLocationName(locationSelection).replace("County","").replace("Council",""));
	},
	updateAssessmentText: function(locationSelection, dateRange) {
		historyController.getAssessmentText(locationSelection, dateRange, function(text){
//			dijit.byId('assessmentText').attr('value', text);
			$('#assessmentText').html(text);
		});
	},
	updateTable: function(locationSelection, dateRange) {
		historyController.getTable(locationSelection, dateRange, function(table){
			var html = "<tr><th scope=\"col\">Water Quality</th>";
			var years = table.headings;
			for(var i=0; i<years.length; i++) {
				html += "<th scope=\"col\">" + years[i].data.getFullYear() + "</th>";
			}
			html += "</tr>";
			var rows = table.rows;
			for(i=0; i<rows.length; i++) {
				html += "<tr>";
				var fields = rows[i].fields;
				for (var j=0; j<fields.length; j++) {
					if (j == 0){
						html += "<td><img src='media/" + fields[j].data + "Key.png' height='10' width='10'/>&nbsp;" + fields[j].data + "</td>";
					} else {
						html += "<td>" + fields[j].data + "</td>";
					}
				}
				html += "</tr>";
			}
			dojo.byId('dataTableDiv').innerHTML = "<table class='epaTable' cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">"+html+"</table>";
		});
	},
	updateComplianceTable: function(locationSelection, dateRange) {
		historyController.getComplianceTable(locationSelection, dateRange, function(table){
			var html = "";
			var rows = table.rows;
			html += "<tr><td style='font-weight:bold; padding:3px'>Local Authority</td><td></td>";
			html += "<td style='background-color:#00adef; font-weight:bold; color:#fff; padding:3px'>Good</td>";
			html += "<td style='background-color:#4cbd38; font-weight:bold; color:#fff; padding:3px'>Sufficient</td>";
			html += "<td style='background-color:#ed1c24; font-weight:bold; color:#fff; padding:3px'>Poor</td>";
			for(i=0; i<rows.length; i++) {
				html += "<tr " + "id=\"" + rows[i].id + "\"";
				if (rows[i].parentId !== null) {
					html += " class=\"child-of-" + rows[i].parentId + "\"";
				}
				html += ">";
				var fields = rows[i].fields;
				for (var j=0; j<fields.length; j++) {
					if (fields[j].flag) {
						html += "<td><img src='media/" + fields[j].data + ".gif' style='height:18px; width:18px' /></td>";
					}
					else {
						html += "<td>" + fields[j].data + "</td>";
					}
				}
				html += "</tr>";
			}
			dojo.byId('complianceTableDiv').innerHTML = "<table class='epaTable' cellpadding=\"0\" cellspacing=\"0\" id=\"complianceTable\" width=\"100%\">"+html+"</table>";
			
			var state = 'collapsed';
			var locationType = common.getLocationType(locationSelection);
			if (locationType == common.COUNTY) {
				state = 'expanded';
			}
			$("#complianceTable").treeTable({initialState: state});
		});
	},
	updateBeachTable: function(locationSelection, dateRange) {
		historyController.getBathingLocationStatusTable(locationSelection, dateRange, function(table){
			var html = "";
			var years = table.headings;
			var rows = table.rows;
			html+="<tr>";
			for(i=0; i<years.length; i++) {
				html += "<th style='text-align:center'>" + years[i].data.getFullYear() + "</th>";
			}
			html += "</tr>";
			for(var i=0; i<rows.length; i++) {
				html += "<tr>";
				var fields = rows[i].fields;
				for (var j=0; j<fields.length; j++) {
					html += "<td style='text-align:center'>";
					if (fields[j].data !== null) {
						html += "<img height='25' width='25' src='media/";
						html += fields[j].data;
						html += ".gif' />";
					}
					html += "</td>";
				}
				html += "</tr>";
			}
			dojo.byId('compStatusTableDiv').innerHTML = "<table class='epaTable' cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">"+html+"</table>";
		});
	},
	updateBeachPhenomenonTable: function(locationSelection, dateRange) {
		historyController.getBathingLocationPhenomenonTable(locationSelection, dateRange, function(table){
			var html = "";
			var rows = table.rows;
			for(var i=0; i<rows.length; i++) {
				html += "<tr>";
				var fields = rows[i].fields;
				for (var j=0; j<fields.length; j++) {
					if (i === 0) { /* header row */
						if (j === 0) {
							html += "<th style='text-align:left;'>" + fields[j].data + "</th>";
						} else {
							html += "<th style='text-align:left;'>" + fields[j].data + "</th>";
						}
					} else {
						if (j === 0) {
							html += "<td style='text-align:left'>" + fields[j].data.getFullYear() + "</td>";
						} else {
							html += "<td style='text-align:left'>" + fields[j].data + "</td>";
						}
					}
				}
				html += "</tr>";
			}
			dojo.byId('phenStatusTableDiv').innerHTML = "<table class='epaTable' cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">"+html+"</table>";
		});
	},
	getTrend: function(values) {
		var length = values.length;
		if (length < 2) {
			return common.TREND_UP;
		}
		var currentStatus = values[length - 1];
		var previousStatus = values[length - 2];
		if (currentStatus === previousStatus) {
			return common.TREND_STATIC;
		}
		if (currentStatus === common.KEY_POOR) {
			return common.TREND_DOWN;
		} 
		if (currentStatus === common.KEY_SUFFICIENT) {
			if (previousStatus === common.KEY_POOR) {
				return common.TREND_UP;
			} else {
				return common.TREND_DOWN;
			}
		} 
		if (currentStatus === common.KEY_GOOD) {
			if (previousStatus === common.KEY_POOR || previousStatus === common.KEY_SUFFICIENT) {
				return common.TREND_UP;
			} else {
				return common.TREND_DOWN;
			}
		} 
		if (currentStatus === common.KEY_EXCELLENT) {
			if (previousStatus === common.KEY_POOR || previousStatus === common.KEY_SUFFICIENT ||  previousStatus === common.KEY_GOOD) {
				return common.TREND_UP;
			} else {
				return common.TREND_DOWN;
			}
		} 
		return common.TREND_UP;
	},
	getDownloadParams: function() {
		dojo.byId('locationSelectionParam').value = dojo.toJson(common.getLocationSelection());
		dojo.byId('dateRangeParam').value = dojo.toJson(common.getDateRange());
	}
};
