var current = {
	name: 'current',
	PHENOM_FAECAL_COLIFORMS: 'Faecal coliforms (number/100ml)',
	PHENOM_FAECAL_STREP: 'Faecal Streptococci (number/100ml)',
	PHENOM_MINERAL_OILS: 'Mineral Oils (mg/l)',
	PHENOM_PHENOL: 'Phenol (mg/l as C4H3OH)',
	PHENOM_SURFACE_ACTIVANTS: 'Surface Active Substances (mg/l)',
	PHENOM_TOTAL_COLIFORMS: 'Total Coliforms (number/100ml)',
	CURRENT_STATUS_LIMIT: 4,	// Max no. of results to show for each poor beach
	poorBathingTextP: '<p>The following bathing area(s) are assessed as having poor water quality based on the most recent sample analysis results. To show the recent performance of these bathing area(s), the water quality status of the three previous samples results is provided.</p>',
	poorBathingTextN: '<p>No bathing areas in the selection are assessed as having poor water quality based on the latest sample analysis results.</p>',
	poorBathingStatus: 'Poor',
	phenoms: null,
	lastLoc: null,
	init: function(mapType) {

		DWREngine.setOrdered(true);

		current.phenoms=
		[
		    current.PHENOM_FAECAL_COLIFORMS,
		    current.PHENOM_FAECAL_STREP,
		    current.PHENOM_MINERAL_OILS,
		    current.PHENOM_PHENOL,
		    current.PHENOM_SURFACE_ACTIVANTS,
		    current.PHENOM_TOTAL_COLIFORMS,
		    'Overall'
		];

		common.setController(currentController);
		common.connectEvents();
		common.loadLocations();

		if (mapType=='gMap') {
		    epaMap.setObj(epaMapGoogle);
		}
		else {
		    epaMap.setObj(epaMapArc);
		}

		epaMap.load('map', function(beach) {
			common.disconnectEvents();
		    common.setSelect('rbSelect','NONE');
		    common.clearOptions('locationSelect');
		    common.resetSelect('locationSelect');
		    currentController.getParentLocationKey(beach, function(localAuthority){
		    	common.setSelect('countySelect', localAuthority);
		    	currentController.getSiblingLocations(beach, function(locations){
					common.addOptions('locationSelect', locations);
					common.setSelect('locationSelect', beach);
					current.updateAll();
					common.connectEvents();
				});
		    });
		}, function() {
		    // Called when the map is ready
			current.updateAll();
		}, function() {
			// Called when the map wants to reset the selection
			var locationSelection = common.getDefaultLocationSelection();
		    common.resetSelect('rbSelect');
		    common.resetSelect('countySelect');
		    common.clearOptions('locationSelect');
		    common.refreshBathingLocations(locationSelection, null);
		    current.updateAggregateView(locationSelection);
		});
	},
	updateAll: function() {
		var locationSelection = common.getLocationSelection();
		var locationType = common.getLocationType(locationSelection);
		
		common.updateMap(locationSelection, null);
		
		if (locationType == common.BATHING_LOCATION) {
			dijit.byId("rightPane").selectChild("bathingSeasonResults");
			$('#lifeguardInfo').show();
			$('#blueFlagInfo').show();
			$('#weather').show();
			$('#tide').show();
			$('#beachInfo').show();
			current.updateBeachInfo(locationSelection);
			current.updateBeachResults(locationSelection);
			current.updateMapTitle(locationSelection);
		}
		else {
			current.updateAggregateView(locationSelection);
		}
	},
	updateAggregateView: function(locationSelection) {
		dijit.byId("rightPane").selectChild("aggregateView");
//		current.updateTwitterStatus(locationSelection);
		$('#lifeguardInfo').hide();
		$('#blueFlagInfo').hide();
		$('#weather').hide();
		$('#tide').hide();
		$('#beachInfo').hide();
		current.updateMapTitle(locationSelection);
		current.updateAggregateResults(locationSelection);
	},
	addPoorRow: function (name, dte, stat) {
	    var html="";

	    html += "<tr>";

	   // if (name!==current.lastLoc) {
		html += "<td style='text-align:left'>"+name+"</td>";
	    // }
	   // else {
		//html += "<td style='text-align:left'></td>";
	    //}

	    html += "<td style='text-align:right'>"+dte+"</td>";
	    var color;
	    if (stat==='Poor') {
		color=common.COLOUR_POOR;
	    }
	    else if (stat==='Sufficient') {
		color=common.COLOUR_SUFFICIENT;
	    }
	    else {
		color=common.COLOUR_GOOD;
	    }

	    html += "<td style='text-align:right'>";
	    html += "<table><tr>";
	    html += "<td style='width: 20%'></td><td style='width:10%; font-weight: bold; color: white; background-color: "+color+"'>";
	    html += stat;
	    html += "</td>";
	    html += "</tr></table>";
	    html += "</td>";
	    html += "</tr>";

	    current.lastLoc=name;

	    return html;
	},
	updateAggregateResults: function(locationSelection) {
		currentController.queryOverallStatus(common.getBathingLocationKeys(), current.poorBathingStatus, current.CURRENT_STATUS_LIMIT, function(rms){

			var textHtml="";
			var html = "";
			var keyAmnt=rms.keys.length;
			if (keyAmnt>0) {
			    html +="<table class='epaTable' cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">";
			    html +="<tr>";
			    html += "<th style='text-align:left'>Bathing Area</th>";
			    html += "<th style='text-align:right'>Sample Date</th>";
			    html += "<th style='text-align:right'>Water Quality</th>";
			    html += "</tr>";

			    var lastLoc=null;
			    for(var i=0; i<keyAmnt; i++) {
					for (var key in rms.values[i]) {
						html += current.addPoorRow(
							    utils.camelCase(epaMapArc.getBeachName(rms.keys[i])),
							    current.formatDate(key), 
							    rms.values[i][key]);
					}
			    }
			    html +="</table>";

			    textHtml=current.poorBathingTextP;
			}
			else {
			    textHtml=current.poorBathingTextN;
			}

			$('#poorBathingAreas').html(textHtml);
			$('#poorBathingAreasTable').html(html);
		});
	},
	updateBeachResults: function(locationSelection) {
		currentController.queryLatestCurrentPhen(locationSelection, current.phenoms, function(rms){
			utils.mapify(rms);
			var html1 = "";
			var html2 = "";
			var theDate = null;
			var keyAmnt=rms.keys.length;
			if (keyAmnt>0) {
			    html1 +="<table class='epaTable' cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">";
			    html1 +="<tr>";
			    html1 += "<th style='text-align:left'>Parameters</th>";
			    html1 += "<th style='text-align:left'>Result</th>";
			    html1 += "<th style='text-align:left'></th>";
			    html1 += "<th style='text-align:left'>Status</th>";
			    html1 += "<th style='text-align:right'>EU Guide Limits</th>";
			    html1 += "<th style='text-align:right'>EU Mandatory Limits</th>";
			    html1 += "</tr>";

			    var gotFS=null;

			    for(var i=0; i<keyAmnt; i++) {
				    var phenom = rms.keys[i];
				    // We separate out Faecal Streptococci
				    if (phenom.indexOf('Faecal Streptococci')!==-1) {
						gotFS=phenom;
						continue;
				    }
				    html1 += "<tr id='la-" + i +"'>";
				    html1 += "<td style='text-align:left'>"+phenom+"</td>";
				    html1 += "<td style='text-align:left'>"+utils.noneify(rms.values[i].Meas_TextResult)+"</td>";
				    html1 += "<td style='text-align:left'></td>";
				    html1 += "<td style='text-align:left'>"+utils.noneify(rms.values[i].Status)+"</td>";
				    html1 += "<td style='text-align:right'>"+utils.noneify(rms.values[i].Prm_GuideLimit)+"</td>";
				    html1 += "<td style='text-align:right'>"+utils.noneify(rms.values[i].Prm_MandatoryLimit)+"</td>";
				    html1 += "</tr>";

				    theDate=rms.values[i].Samp_Date;
			    }
			    html1 +="</table>";

			    if (gotFS!==null) {
					html2 +="<table class='epaTable' cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">";
					html2 +="<tr>";
					html2 += "<th style='text-align:left'>Other Microbiological Parameters Sampled</th>";
					html2 += "<th style='text-align:right'>Result</th>";
					html2 += "<th style='text-align:right'>EU Guide Limit</th>";
					html2 +="</tr>";
	
					var fsVal=rms.get(gotFS);
	
					html2 += "<tr id='la-1'>";
					html2 += "<td style='text-align:left'>"+gotFS+"</td>";
					html2 += "<td style='text-align:right'>"+utils.noneify(fsVal.Meas_TextResult)+"</td>";
					html2 += "<td style='text-align:right'>"+utils.noneify(fsVal.Prm_GuideLimit)+"</td>";
					html2 += "</tr>";
				    html2 +="</table>";
			    }
			} else {
				html1 = "<span style='margin-left:10px;'>No results available</span>";
			}
			$('#latestReading').html(html1);
			$('#previousReadings').html(html2);

			if (theDate===null) {
			    $('#bathingSeasonResultsDate').text("");
			}
			else {
			    $('#bathingSeasonResultsDate').text(theDate.getDate()+"/"+
								parseInt(theDate.getMonth()+1)+"/"+
								theDate.getFullYear());
			}
		});

		currentController.queryCurrentStatus(locationSelection, current.phenoms, function(rms){
			utils.mapify(rms);

			var html = "";

			var keyAmnt=rms.keys.length;
			if (keyAmnt>0) {

			    html+="<table class='epaTable' cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">";
			    html+="<tr>";
			    html += "<th style='text-align:left'>Date</th>";
			    html += "<th style='text-align:left'>Overall Status</th>";
			    html += "<th style='text-align:left'>Total Coliforms</th>";
			    html += "<th style='text-align:left'>Faecal Coliforms</th>";
			    html += "<th style='text-align:left'>Mineral Oils</th>";
			    html += "<th style='text-align:left'>Surface Active Substances</th>";
			    html += "<th style='text-align:left'>Phenols</th>";
			    html += "</tr>";

			    var gotFS=null;

			    for(var i=keyAmnt-1; i>=0; i--) {
				    var phenom=rms.keys[i];

				    html += "<tr>";

				    var theDate=current.formatDate(rms.keys[i]);
				    html += "<td style='text-align:left'>"+theDate+"</td>";
				    html += "<td style='text-align:left'>"+current.blankify(rms.values[i].Overall)+"</td>";
				    html += "<td style='text-align:left'>"+current.blankify(rms.values[i][current.PHENOM_TOTAL_COLIFORMS])+"</td>";
				    html += "<td style='text-align:left'>"+current.blankify(rms.values[i][current.PHENOM_FAECAL_COLIFORMS])+"</td>";
				    html += "<td style='text-align:left'>"+current.blankify(rms.values[i][current.PHENOM_MINERAL_OILS])+"</td>";
				    html += "<td style='text-align:left'>"+current.blankify(rms.values[i][current.PHENOM_SURFACE_ACTIVANTS])+"</td>";
				    html += "<td style='text-align:left'>"+current.blankify(rms.values[i][current.PHENOM_PHENOL])+"</td>";

				    html += "</tr>";
			    }

			    html+="</table>";
			} else {
				html = "<span style='margin-left:10px;'>No results available</span>";
			}
			
			$('#allReadings').html(html);
		});
	},
	blankify: function(str) {
		return str===undefined || str===null?"":str;
	},
	formatDate: function(oldDate) {
		return oldDate.substring(8, 10)+'/'+
			oldDate.substring(5, 7)+'/'+
			oldDate.substring(2, 4);
	},
	updateTwitterStatus: function(locationSelection) {
		currentController.getTwitterStatus(locationSelection, function(status) {
			$('#twitterStatus').text(status);
		});
	},
	updateMapTitle: function(locationSelection) {
		$('#mapTitle1').text("Latest Status ");
		$('#mapTitle2').text(common.getLocationName(locationSelection).replace("County","").replace("Council",""));
	},
	updateBeachInfo: function(locationSelection) {
		currentController.getBeachInfo(locationSelection, function(beachInfo){
			$('#lifeguard').text(beachInfo.lifeguard ? "Yes" : "No");
			current.updateLifeguardInfo(beachInfo);
			$('#blueFlag').text(beachInfo.blueFlag);
			current.updateWeatherWidget(beachInfo);
			$('#beachPhoto').attr("src", "media/photos/" + beachInfo.idbw + ".jpg");
			$('#beachDescription').html(beachInfo.description);
		});
		currentController.getTwitterStatus(locationSelection, function(twitterStatus){
			if (twitterStatus !== null) {
				$('#twitter').text("Lifeguard Update: " + twitterStatus);
			} else {
				$('#twitter').text("");
			}
		});
	},
	updateLifeguardInfo: function(beachInfo) {
		if (beachInfo.lifeguard && beachInfo.lifeguardInfo !== null) {
			$('#lifeguardWhen').attr("href", beachInfo.lifeguardInfo); 
			$('#lifeguardWhen').show();
		} else {
			$('#lifeguardWhen').hide();
		}
	},
	updateWeatherWidget: function(beachInfo) {
		var str = Return_RunNetWeather("id", "netWxV2", "minversion", "8,0,0,0", "movie","http://www.accuweather.com/adcbin/netweather_v2/netWx-V28?zipcode="+ beachInfo.weatherKey +"&customtheme=&theme=clouds&metric=1&target=_self&lang=uke&url=&video=&category=&logo=1&tStyle=normal&partner=netweather&myspace=0","src", "http://www.accuweather.com/adcbin/netweather_v2/netWx-V28?zipcode=" + beachInfo.weatherKey +"&customtheme=&theme=clouds&metric=1&target=_self&lang=uke&url=&video=&category=&logo=1&tStyle=normal&partner=netweather&myspace=0", "width", "180","height", "135", "name", "netWxV2", "wmode","transparent");
		$('#weatherDiv').html("<div style='width: 100%; height: 150px;'>" +
				"<div id='weatherWidgetContainer' style='height: 138px; background-color: #C0E5EE'>" +
				str +
				"</div>" +
				"<div style='margin-left:35px; font-family: arial, helvetica, verdana, sans-serif; font-size: 10px; line-height: 12px; color: #FFFFFF;'>" +
				"	<a style='color: #FFFFFF' href='http://www.accuweather.com/world-index-forecast.asp?partner=netweather&locCode=" + utils.trim(beachInfo.weatherKey)  + "&metric=1' target='_blank'>Weather Forecast</a>" +
				"	| <a style='color: #FFFFFF' href='http://www.accuweather.com/maps-satellite.asp' target='_blank'>Weather Maps</a>" +
				"</div></div>");
	}
};
