var warningSortArray = []; //Temporary array for sorting warnings by severity

var mountainNames = [];
mountainNames['eh'] = "East Highland";
mountainNames['we'] = "West Highland";
mountainNames['ld'] = "Lake District";
mountainNames['pd'] = "Peak District";
mountainNames['sn'] = "Snowdonia";
mountainNames['bb'] = "Brecon Beacons";
mountainNames['yd'] = "Yorkshire Dales";

var regionNames = [];
regionNames['uk'] ='United Kingdom';
regionNames['os'] ="Orkney & Shetland";
regionNames['he'] ="Highlands & Eilean Siar";
regionNames['gr'] ="Grampian";
regionNames['st'] ="Strathclyde";
regionNames['ta'] ="Central, Tayside & Fife";
regionNames['dg'] ="Dumfries, Galloway, Lothian & Borders";
regionNames['ni'] ="Northern Ireland";
regionNames['wl'] ="Wales";
regionNames['nw'] ="North West England";
regionNames['ne'] ="North East England";
regionNames['yh'] ="Yorkshire & Humber";
regionNames['wm'] ="West Midlands";
regionNames['em'] ="East Midlands";
regionNames['ee'] ="East of England";
regionNames['sw'] ="South West England";
regionNames['se'] ="South East England";

var wxDesc = [];
wxDesc["0"]="Clear sky (night)";
wxDesc["1"]="Sunny";
wxDesc["2"]="Partly cloudy (night)";
wxDesc["3"]="Sunny intervals";
wxDesc["4"]="Dust";
wxDesc["5"]="Mist";
wxDesc["6"]="Fog";
wxDesc["7"]="Medium-level cloud";
wxDesc["8"]="Low-level cloud";
wxDesc["9"]="Light rain shower (night)";
wxDesc["10"]="Light rain shower (day)";
wxDesc["11"]="Drizzle";
wxDesc["12"]="Light rain";
wxDesc["13"]="Heavy rain shower (night)";
wxDesc["14"]="Heavy rain shower (day)";
wxDesc["15"]="Heavy rain";
wxDesc["16"]="Sleet shower (night)";
wxDesc["17"]="Sleet shower (day)";
wxDesc["18"]="Sleet";
wxDesc["19"]="Hail shower (night)";
wxDesc["20"]="Hail shower (day)";
wxDesc["21"]="Hail";
wxDesc["22"]="Light snow shower (night)";
wxDesc["23"]="Light snow shower (day)";
wxDesc["24"]="Light snow";
wxDesc["25"]="Heavy snow shower (night)";
wxDesc["26"]="Heavy snow shower (day)";
wxDesc["27"]="Heavy snow";
wxDesc["28"]="Thundery shower (night)";
wxDesc["29"]="Thundery shower (day)";
wxDesc["30"]="Thunder storm";
wxDesc["31"]="Tropical storm";
wxDesc["33"]="Haze";

var wndDir = [];
wndDir["VRB"] = "VRB";
wndDir["N"] = "N";
wndDir["NNE"] = "NNE";
wndDir["NE"] = "NE";
wndDir["ENE"] = "ENE";
wndDir["E"] = "E";
wndDir["ESE"] = "ESE";
wndDir["SE"] = "SE";
wndDir["SSE"] = "SSE";
wndDir["S"] = "S";
wndDir["SSW"] = "SSW";
wndDir["SW"] = "SW";
wndDir["WSW"] = "WSW";
wndDir["W"] = "W";
wndDir["WNW"] = "WNW";
wndDir["NW"] = "NW";
wndDir["NNW"] = "NNW";

var inventCache = "/public/data/InventCache/";
var pageOrder = [];
var warnFile=inventCache+"ItemList/WeatherWarning/Valid/Now/Latest";
var timeInfoFile = inventCache+"Item/DaylightSaving";
var extHrs;
$.get(timeInfoFile,function(extHrsAdd){extHrs = extHrsAdd;});
var currentView;
var warningsDoc;
var wLevels = [];

var pageData = null;//Contents of config file
var langPath="/public/pws/lib/javascript/lang/";
var pageId = null;
var panelsConfDir = "panelsconf/";

var pageTempUnits = "C";
var pageSpeedUnits = "M";
var pagePresUnits = "H";

var units = [];
var customiseHTML;
var mtExtras =[];



if($.cookie('MOWxUnits')){pageTempUnits = $.cookie('MOWxUnits');}
if($.cookie('MOWxSpeedUnits')){pageSpeedUnits = $.cookie('MOWxSpeedUnits');}
if($.cookie('MOWxPresUnits')){pagePresUnits = $.cookie('MOWxPresUnits');}

var wxImgFormat = ".png";
var msie6 = (jQuery.browser.msie);
var msie7 = ($.browser.msie&& !/MSIE 6\.0/i.test(window.navigator.userAgent)&& /MSIE 7\.0/i.test(window.navigator.userAgent)&& !/MSIE 8\.0/i.test(window.navigator.userAgent));
if (msie6){wxImgFormat = ".gif";}
var temp;
var langPanelsDisplay = "";
var langPanels = [];
var langAvbl = false;
var unitsPanelsDisplay = "";
var unitsPanels = [];
var unitsAvbl = false;

function setLangVariables() {	
  customiseHTML = "";
  metOfficeNoResp=$.sprintf(_("The Met Office is not responsible for the content of external sites. If you would like us to consider adding a link to your webcam, please <a %(link)s>contact us</a>."),{link:"href='/corporate/contact/contact.html'"});
  mtExtras = {
      "snowdonia": {
          "temperatureHeight": 900,
          "valleyDescription": _('Valleys'),
          "content": "<style>.caveat {color:gray;}</style><div><h3>"+_('Related observations')+"</h3><p><a target='_blank' href='http://www.metoffice.gov.uk/weather/uk/wl/capel_curig_latest_weather.html'>"+_('Capel Curig')+"</a></p><h3>"+_('Webcams')+"</h3><p>"+$.sprintf(_('The following webcams are available from the %(name)s website:'),{name:_('Snowdonia National Park')})+"</p><p><a target='_blank' href='http://www.eryri-npa.gov.uk/home/visiting/webcams.htm'>"+_('Snowdon Webcam')+"</a><br /><a target='_blank' href='http://www.eryri-npa.gov.uk/home/visiting/webcams/llyn_tegid_webcam.htm'>"+_('Llyn Tegid Webcam')+"</a></p><p class='caveat'>"+metOfficeNoResp+"</p></div>" 
      },
      "westhighland": {
          "temperatureHeight": 900,
          "valleyDescription": _('Glens'),
          "content": "<style>.caveat {color:gray;}</style><div><h3>"+_('Related observations')+"</h3><p><a target='_blank' href='http://www.metoffice.gov.uk/weather/uk/he/altnaharra_latest_weather.html'>"+_('Altnaharra')+"</a><br/><a target='_blank' href='http://www.metoffice.gov.uk/weather/uk/he/loch_glascarnoch_latest_weather.html'>"+_('Loch Glascarnoch')+"</a><br/><a target='_blank' href='http://www.metoffice.gov.uk/weather/uk/he/skye_lusa_latest_weather.html'>"+_('Skye Lusa')+"</a><br/><a target='_blank' href='http://www.metoffice.gov.uk/weather/uk/he/aultbea_latest_weather.html'>"+_('Aultbea')+"</a><br/><a target='_blank' href='http://www.metoffice.gov.uk/weather/uk/he/tulloch_bridge_latest_weather.html'>"+_('Tulloch Bridge')+"</a></p><h3>"+_('Scottish Avalanche Information Service')+"</h3><p><a target='_blank' href='http://www.sais.gov.uk/page_glencoe.asp'>"+_('Glencoe')+"</a><br/><a target='_blank' href='http://www.sais.gov.uk/page_lochaber.asp'>"+_('Lochaber')+"</a></p><h3>"+_('Webcams')+"</h3><p>"+_('The following webcams are available:')+"</p><p><a target='_blank' href='http://www.fortwilliamscotland.com/cms/assets/frontend/images_custom/cam1_bennevis_00001.jpg'>"+_('Ben Nevis')+"</a><br /><a target='_blank' href='http://www.winterhighland.info/cams/glencoe/index.php#ssc'>"+_('Glencoe')+"</a><br /><a target='_blank' href='http://www.scottish-highland.co.uk/ispy.jpg'>"+_('Kyle of Lochalsh')+"</a></p><p class='caveat'>"+metOfficeNoResp+"</p></div>" 
      },
      "yorkshiredales": {
          "temperatureHeight": 700,
          "valleyDescription": _('Valleys'),
          "content": "<style>.caveat {color:gray;}</style><div><h3>"+_('Webcams')+"</h3><p>"+$.sprintf(_("A range of webcams are available on the <a %(link)s>%(name)s website</a>"),{link:"target='_blank' href='http://www.yorkshiredales.org.uk/webcams'", name:_('Yorkshire Dales National Park')})+"</p><p class='caveat'>"+metOfficeNoResp+"</p></div>" 
      },
      "breconbeacons": {
          "temperatureHeight": 800,
          "valleyDescription": _('Valleys'),
          "content": "<style>.caveat {color:gray;}</style><div><h3>"+_('Webcams')+"</h3><p>"+$.sprintf(_("A range of webcams are available on the <a %(link)s>%(name)s website</a>"),{link:"target='_blank' href='http://www.breconbeacons.org/pages/livewebcam'",name:_('Brecon Beacons National Park')})+"</p><p class='caveat'>"+metOfficeNoResp+"</p></div>" 
      },
      "easthighland": {
          "temperatureHeight": 900,
          "valleyDescription": _('Glens'),
          "content": "<style>.caveat {color:gray;}</style><div><h3>"+_('Related observations')+"</h3><p><a target='_blank' href='http://www.metoffice.gov.uk/weather/uk/he/aviemore_latest_weather.html'>"+_('Aviemore')+"</a><br/><a target='_blank' href='http://www.metoffice.gov.uk/weather/uk/gr/aboyne_latest_weather.html'>"+_('Aboyne')+"</a></p><h3>"+_('Scottish Avalanche Information Service')+"</h3><p><a target='_blank' href='http://www.sais.gov.uk/page_northern%20cairngorms.asp'>"+_('Northern Cairngorms')+"</a><br /><a target='_blank' href='http://www.sais.gov.uk/page_southern%20cairngorms.asp'>"+_('Southern Cairngorms')+"</a></p><h3>"+_('Webcams')+"</h3><p>"+_('The following webcams are available:')+"</p><p><a target='_blank' href='http://www.cairngormmountain.com/webcam/basestation.jpg'>"+_('Cairngorm Base Station')+"</a><br /><a target='_blank' href='http://www.cairngormmountain.com/webcam/ptarmigan.jpg'>"+_('Cairngorm - Ptarmigan Restaurant')+"</a><br /><a target='_blank' href='http://www.winterhighland.info/cams/cairngorm-mountain/morlich.php'>"+_('Loch Morlich (close to Aviemore)')+"</a><br /><a target='_blank' href='http://www.winterhighland.info/cams/cairngorm-mountain/'>"+_('Cairngorm mid-station')+"</a></p><p class='caveat'>"+metOfficeNoResp+"</p></div>" 
      },
      "lakedistrict": {
          "temperatureHeight": 900,
          "valleyDescription": _('Valleys'),
          "content": "<style>.caveat {color: gray;}</style><div><h3>"+_('Related observations')+"</h3><p><a target='_blank' href='http://www.metoffice.gov.uk/weather/uk/nw/keswick_latest_weather.html'>"+_('Keswick')+"</a><br/><a target='_blank' href='http://www.metoffice.gov.uk/weather/uk/nw/shap_latest_weather.html'>"+_('Shap')+"</a></p><h3>"+_('Webcams')+"</h3><p>"+$.sprintf(_("A range of webcams are available on the <a %(link)s>%(name)s website</a>"),{link:"target='_blank' href='http://www.lakedistrict.gov.uk/index/enjoying/webcams.htm'",name:_('Lake District National Park')})+"</p><p class='caveat'>"+metOfficeNoResp+"</p></div>"
      },
      "peakdistrict": {
          "temperatureHeight": 600 ,
          "valleyDescription": _('Valleys'),
          "content": "<style>.caveat {color: gray;}</style><div><h3>"+_('Related observations')+"</h3><p><a target='_blank' href='http://www.metoffice.gov.uk/weather/uk/wm/leek_thorncliffe_latest_weather.html'>"+_('Leek Thorncliffe')+"</a></p><h3>"+_('Webcams')+"</h3><p>"+$.sprintf(_("A selection of webcams are available from the <a %(link)s>%(name)s website</a>"),{link:"target='_blank' href='http://www.peakdistrictonline.co.uk/content.php?categoryId=2491'", name:'Peak District Online'})+"</p><p class='caveat'>"+metOfficeNoResp+"</p></div>" 
      }
  };
  setUnitVariables();

  $('#bc').html('<span id="here">'+_('You are here')+':</span> <a href="/">'+_('Home')+'</a><a href="/public/pws/invent/">'+_('Invent')+'</a> '+_('Text view'));
  $('#indexNoScript').html(_('Sorry, this page is currently unavailable without Javascript. Please click the links above to navigate to a different page.'));

}

function setUnitVariables() {
  units = '<form name="unitsSelTemp"><fieldset id="temperatureUnits"><legend>'+_('Temperature units')+'</legend><input id="temperatureUnitsC" type="radio" value="C" name="temperatureUnits" onClick ="changeUnits(\'temperature\')"/>';
  units = units+ '<label for="temperatureUnitsC">'+_("&deg;C")+' ('+_("Celsius")+')</label>';
  units = units+ '<input id="temperatureUnitsF" type="radio" value="F" name="temperatureUnits" onClick ="changeUnits(\'temperature\')"/>';
  units = units+ '<label for="temperatureUnitsF">'+_("&deg;F")+' ('+_("Fahrenheit")+')</label></fieldset></form>';    
  units = units+ '<form name="unitsSelSpeed"><fieldset id="speedUnits">';
  units = units+ '<legend>'+_('Wind speed units')+'</legend>';
  units = units+ '<input id="speedUnitsM" type="radio" value="M" name="speedUnits" onClick ="changeUnits(\'speed\')"/>';
  units = units+ '<label for="speedUnitsM">'+_('m.p.h.')+'</label>';
  units = units+ '<input id="speedUnitsK" type="radio" value="K" name="speedUnits" onClick ="changeUnits(\'speed\')"/>';
  units = units+ '<label for="speedUnitsK">'+_('km/h')+'</label>';
  units = units+ '<input id="speedUnitsN" type="radio" value="N" name="speedUnits" onClick ="changeUnits(\'speed\')"/>';
  units = units+ '<label for="speedUnitsN">'+_('knots')+'</label></fieldset></form>';
  units = units+ '<form name="unitsSelPres"><fieldset id="pressureUnits"><legend>'+_('Pressure units')+'</legend><input id="pressureUnitsH" type="radio" value="H" name="pressureUnits" onClick ="changeUnits(\'pressure\')"/>';
  units = units+ '<label for="pressureUnitsH">'+_('hPa')+'</label>';
  units = units+ '<input id="pressureUnitsI" type="radio" value="I" name="pressureUnits" onClick ="changeUnits(\'pressure\')"/>';
  units = units+ '<label for="pressureUnitsI">'+_('Ins (Inches)')+'</label></fieldset></form>';    
}

function setPageSpecificLangVariables() {
  if(pageData.page.panels.panel.mountaindetail)
  {
    pageData.page.panels.panel.mountaindetail.params.temperatureHeight = mtExtras[pageId].temperatureHeight;
    pageData.page.panels.panel.mountaindetail.params.valleyDescription = mtExtras[pageId].valleyDescription;
  }
  if(pageData.page.panels.panel.linksandwebcams)
  {
    pageData.page.panels.panel.linksandwebcams.params.content = mtExtras[pageId].content;
  }
}

function arrayIndexOf(array, obj, start) {
	var i, j;
	for (i = (start || 0), j = array.length; i < j; i++) {
		if (array[i] == obj) {return i;}
	}
	return -1;
}

$(document).ready(function () {
	$('#hnav .sub').bgiframe();
	//getWarnings();
	initialize();
	try {
		$('.searchField').corner();
		$('#logoBar').corner('top');
		$('#footer').corner('bottom');
    }catch(err){return false;}
});

function initialize() {
	// get the name of the configuration
	pageId = document.location.search.substring(1);
	if (pageId !== null&&pageId !== "") {
		$('#defaultText').html("");
	} else {
		pageId = 'uk';
	}
	// render the page
	loadLanguages(function(){  
	  loadPage(pageId);
      $('.panel').bgiframe();
    });	
}

function addExtHrs(oldDate){
	//fullTime is DD/MM/YYYY/hh/mm
	var newDate = oldDate;
	newDate.setHours(newDate.getHours()+eval(extHrs));
	return newDate;
}
	
function toDateObj(oldDate) {
	hour = oldDate.slice(11,13);min = oldDate.slice(14,16);ndate = oldDate.slice(8,10);year = oldDate.slice(0,4);monthNumber = oldDate.slice(5,7)-1;month = month_name[monthNumber];
	newDate = new Date(year, monthNumber, ndate, hour, min);

	return newDate;
}

function calcWarnLevel(r,e) {
	var col;
	if (e === 0) {if (r<40) {col=0;} else if (r>39&&r<60) {col=1;} else if (r>59) {col=3;}}
	if (e == 1) {if (r<20) {col=0;} else if (r>19&&r<40) {col=1;} else if (r>39&&r<60) {col=2;} else if (r>59) {col=4;}}

	return col;
}

function loadPage(pageId) {
  if (parseInt(pageId) > 0){
			MetOffice.locations.getLocList(function() {
				
				var loc = MetOffice.locations.getLocation(pageId), obsSite;
					if(loc){
						MetOffice.locations.getObsList(function() {
						if (loc.o == 1) {obsSite = loc;} else {obsSite = MetOffice.locations.getNNearest(loc.l, loc.g, 1, MetOffice.locations.obsList);}
						$.getJSON(panelsConfDir+"site.txt", function(data) {
							//TODO: locations need to know what region they are in, currently using static value below
							data.page.title = loc.n;
							data.page.panels.panel.wel.params.lat = loc.l;
							data.page.panels.panel.wel.params.lng = loc.g;
							data.page.panels.panel.wel.params.alt = loc.a;
							data.page.panels.panel.cfv.params.area = loc.r;
							data.page.panels.panel.ssfc.params.id = loc.i;
							data.page.panels.panel.ssfc.params.name = loc.n;
							data.page.panels.panel.warnings.params.area = loc.r;
							data.page.panels.panel.tFc.params.area = loc.r;
							data.page.panels.panel.probs.params.id = loc.i;
							data.page.panels.panel.probs.params.name = loc.n;
							data.page.panels.panel.hrObs.params.id = obsSite.i;
							data.page.panels.panel.hrObs.params.name = obsSite.n;
							if (loc.p!==""){
								data.page.panels.panel.nationalParks.titleSpecifics = loc.n;
								data.page.panels.panel.nationalParks.params.area = loc.r;
								data.page.panels.panel.nationalParks.params.park = loc.p;
							} else {
								data.page.panels.panel.nationalParks = null;
							}
							if (loc.m!==""){
								data.page.panels.panel.mountains.titleSpecifics = loc.n;
								data.page.panels.panel.mountains.params.area = loc.m;
							} else {
								data.page.panels.panel.mountains= null;
							}
							data.page.panels.panel.Ext.params.area = loc.r;
							pageData = data;
							loadUserPrefs();
							changePageTitle();
							setUnitVariables();
							setupCustomisePanel();
							displayPageContent();
						});
					});
				}
			});
		//location ID
		} else {
		if (MetOffice.region.validate(pageId)){
			//region ID
				var reg = MetOffice.region.getById(pageId);
				$.getJSON(panelsConfDir+"region.txt", function(data) {
					data.page.title = reg.n;
					data.page.panels.panel.wel.params.lat = reg.l;
					data.page.panels.panel.wel.params.lng = reg.g;
					data.page.panels.panel.cfv.params.area = reg.i;
					data.page.panels.panel.warnings.params.area = pageId;
					data.page.panels.panel.tFc.params.area = pageId;
					if (reg.p!==""){
						data.page.panels.panel.nationalParks.titleSpecifics = reg.n;
						data.page.panels.panel.nationalParks.params.area = reg.p;
					} else {
						data.page.panels.panel.nationalParks = null;
					}
					if (reg.m!==""){
						data.page.panels.panel.mountains.titleSpecifics = reg.n;
						data.page.panels.panel.mountains.params.area = reg.m;
					} else {
						data.page.panels.panel.mountains= null;
					}
					data.page.panels.panel.ro.params.area = pageId;
					data.page.panels.panel.Ext.params.area = pageId;
					pageData = data;
					loadUserPrefs();
					changePageTitle();
					setUnitVariables();
					setupCustomisePanel();
					displayPageContent();
				});
			} else {
			//Mountain ID - CHECK IF MO Mountain REGION
			if(MetOffice.mountain.validate(pageId)){
				var mount = MetOffice.mountain.getById(pageId);
				$.getJSON(panelsConfDir+"mountain.txt", function(data) {
					data.page.title = mount.n;
					data.page.panels.panel.wel.params.lat = mount.l;
					data.page.panels.panel.wel.params.lng = mount.g;
					data.page.panels.panel.mountainoverview.params.mountain = mount.n;
					data.page.panels.panel.mountaindetail.params.temperatureHeight = mtExtras[pageId].temperatureHeight;
					data.page.panels.panel.mountaindetail.params.valleyDescription = mtExtras[pageId].valleyDescription;
					data.page.panels.panel.mountaindetail.params.mountain = mount.n;
					data.page.panels.panel.linksandwebcams.params.content = mtExtras[pageId].content;
					for (var t = 0 ; t < (mount.w).length; t++){
						var area = "warnings"+(mount.w)[t];
						data.page.panels.panel[area] = {};
						data.page.panels.panel[area].closable= true;
						data.page.panels.panel[area].visible= true;
						data.page.panels.panel[area].minimised= false;
						data.page.panels.panel[area].draggable= true;
						data.page.panels.panel[area].translatable= true;
						data.page.panels.panel[area].convertable= false;
						data.page.panels.panel[area].savedincookie= true;
						data.page.panels.panel[area].title= 'Severe Weather Warnings';
						data.page.panels.panel[area].shortTitle = 'Severe Weather';
						data.page.panels.panel[area].page= "warnings.html";
						data.page.panels.panel[area].style ="background-color: #cf3";
						data.page.panels.panel[area].params= {"area": (mount.w)[t]};
						data.page.panels.panel[area].callback="initWarnings";
					}
					pageData = data;
					loadUserPrefs();
					setPageSpecificLangVariables();
					changePageTitle();
					setUnitVariables();
					setupCustomisePanel();
					displayPageContent();	
				});
			
			} else {

				var reg = MetOffice.region.getById("uk");
				$.getJSON(panelsConfDir+"region.txt", function(data) {
					data.page.title = reg.n;
					data.page.panels.panel.wel.params.lat = reg.l;
					data.page.panels.panel.wel.params.lng = reg.g;
					data.page.panels.panel.warnings.params.area = pageId;
					data.page.panels.panel.tFc.params.area = pageId;
					data.page.panels.panel.nationalParks = null;
					data.page.panels.panel.ro.params.area = pageId;
					data.page.panels.panel.Ext.params.area = pageId;
					
					pageData = data;
					loadUserPrefs();
					changePageTitle();
					setUnitVariables();
					setupCustomisePanel();
					displayPageContent();
				});
			}
		}
	}
}

function loadUserPrefs() {
	var cookie = $.cookie("MOWx" + pageData.page.type);
	if (cookie === null) {
	} else {
		var saved = cookie.split("&");
		//Modify visibilities based upon cookie contents
		for (var i=0,len=saved.length;i<len;i++) {
			pageOrder.push(saved[i].split('|')[0]);	// use the order from the cookie as the display order. 
			if (pageData.page.panels.panel[saved[i].split('|')[0]]) {
				pageData.page.panels.panel[saved[i].split('|')[0]].visible = (saved[i].split('|')[1]==="true");
				pageData.page.panels.panel[saved[i].split('|')[0]].minimised = (saved[i].split('|')[2]==="true");
			}
		}
	}

	// Add any pages that aren't in the cookie, but that are in the panel config for this page, 
	// e.g. mountains aren't in the SW region, but are in the WL region.  
	var tempPageOrder = pageOrder.toString();
	for (var p in pageData.page.panels.panel) {
		if (p !== null && tempPageOrder.indexOf(p) === -1) {
			pageOrder.push(p);	// if there was no cookie, the display order becomes that of 
								// the panel's configuration.
		}
	}
 }
 
 function redrawObs(){
	try{if (obGraphShowing===true){obBuildGraph(obType);}}catch(err){}
 }

 function panelsMoved() {
	currentView = $('.panel');
	// first, save the position of the panels
	saveUserPrefs(currentView);
	
 	// update the pageOrder variable, as this is useful in the configuration panel.  
	pageOrder = [];
	for (var i=0,len=currentView.length;i<len;i++) {
		pageOrder.push($(currentView[i]).attr('id').substring(6));
	}
 }
 
function saveUserPrefs() {
	currentView = $('.panel');
	// first, save the cookie.
	var cookieString="";
	for (var i=0,len=currentView.length;i<len;i++) {
		if (pageData.page.panels.panel[$(currentView[i]).attr('id').substring(6)].savedincookie) {
			cookieString = cookieString + "&" + $(currentView[i]).attr('id').substring(6) + "|";
			cookieString = cookieString + ($(currentView[i]).css('display')==="block") + "|";
			cookieString = cookieString + ($(currentView[i]).children('.content').css('display')==="none") + "|";
		}
	}
	$.cookie('MOWx' + pageData.page.type, cookieString.substring(1), { expires: 30});
}

function changePageTitle() {
	document.title = "Met Office: Invent - Weather: Text view - " + pageData.page.type + ": " + pageData.page.title;
}

function displayPageContent() {
	for (var i = 0; i < pageOrder.length; i++) {	
		if (pageData.page.panels.panel[pageOrder[i]]) {
			displayPanel(pageOrder[i]);
		}
	}
	try {
		$("#panel-container").sortable({axis: 'y', containment: 'parent', cursor: 'move', handle: 'div.handle', helper: 'clone', items: 'div.draggable', tolerance: 'pointer', update: panelsMoved, stop:redrawObs});
	}
	catch(err) {
		$(".handle").css("cursor", "auto");
	}
}

function getPanelTitle(panelId) {
  displayTitle = _(pageData.page.panels.panel[panelId].title);

  if(pageData.page.panels.panel[panelId].titleSpecifics)
  {
    displayTitle+="&nbsp;:&nbsp;"+_(pageData.page.panels.panel[panelId].titleSpecifics);
  }
  
  return displayTitle;
}

function displayPanelTitle(panelId) {
  $("#panel_" + panelId + " .handle h2").html(getPanelTitle(panelId));
}

function displayPanel(i) {
	// create a chosen panel and make visibile or not - Only load in content when panel is made visible
	$("#panel-container").append("<div id='panel_" + i + "' class='panel" + ((pageData.page.panels.panel[i].visible) ? "" : " invisible") + ((pageData.page.panels.panel[i].draggable) ? " draggable" : "") + ((pageData.page.panels.panel[i].closable) ? " closable" : "") +"'"
	+ ((pageData.page.panels.panel[i].style) ? " style='" + pageData.page.panels.panel[i].style + "'" : "") 
	+ "><div class='handle'><img class='crossImage' src='/public/pws/invent/lib/images/cross.png' /><img class='minImage' src='/public/pws/invent/lib/images/minus.gif' /><h2></h2><br class='brclear'></div><div class='content'></div>");
	
	if (msie7) {$(".panel").append("<br class='brclear'>");}
	
$("#panel_" + i + " h2").attr("style", pageData.page.panels.panel[i].style);
	$("#panel_" + i + " .handle").attr("style", pageData.page.panels.panel[i].style);
	displayPanelTitle(i);
	$("#panel_" + i + " .content").html('<img style="padding:10px;" src="lib/images/loadingSmall.gif">');
	if (pageData.page.panels.panel[i].visible) {
		$("#panel_" + i + " .content").load("panels/" + pageData.page.panels.panel[i].page, function() {
			try {
				eval(pageData.page.panels.panel[i].callback + "(\"" + i + "\")");
			} 
			catch(err) {}
		});
	}

	if (pageData.page.panels.panel[i].minimised) {
		$("#panel_" + i + ' .minImage').attr("src","/public/pws/invent/lib/images/plus.gif");
		$("#panel_" + i).children('.content').css("display","none");
	}
	else {
		$("#panel_" + i + ' .minImage').attr("src","/public/pws/invent/lib/images/minus.gif");
		$("#panel_" + i).children('.content').css("display","block");
	}
	// assigns a handler so that closing the panel is stored in the cookie.
	$("#panel_" + i + " .handle img.crossImage").click(function () {
			if(msie6){$(this).parent().parent().hide(10,saveUserPrefs);}
			else{$(this).parent().parent().slideUp(500,saveUserPrefs);}
			//$(this).parent().parent().children('.content').toggle();
			$('#option_'+$(this).parent().parent().attr('id').substring(6)).attr('checked',false);
			//saveUserPrefs();
		}
	);
	
	$("#panel_" + i + " .handle img.minImage").click(function () {
		if ($(this).attr("src") === "/public/pws/invent/lib/images/plus.gif") {
			$(this).attr("src", "/public/pws/invent/lib/images/minus.gif");
			if(msie6){$(this).parent().parent().children('.content').show(10,saveUserPrefs);}
			else{$(this).parent().parent().children('.content').slideDown(500,saveUserPrefs);}
			//redraw observation panel graphs when reopening panels
			redrawObs();
		} else {
			$(this).attr("src", "/public/pws/invent/lib/images/plus.gif");
			if(msie6){$(this).parent().parent().children('.content').hide(10,saveUserPrefs);}
			else{$(this).parent().parent().children('.content').slideUp(500,saveUserPrefs);}
		}
		//saveUserPrefs();
	});
}

function configurable() {
	$("#panelButtons").html(setupPanelButtons());
	for (var i in pageData.page.panels.panel) {
		if (pageData.page.panels.panel[i]){
			temp = pageData.page.panels.panel[i];
			if(temp.closable) {
				if ($('#panel_'+i).css('display') == "block") {
					$('#option_'+i).attr('checked',true);
				}
			}
		}
	}
	$('#welcome').parent().parent().children('.content').css('display','block');
	if ($("#panel_wel .minImage").attr("src")=="/public/pws/invent/lib/images/minus.gif") {
		$("#panel_wel .minImage").attr("src","/public/pws/invent/lib/images/plus.gif");
		$("#panel_wel i").children('.content').css("display","none");
	}
	else {
		$("#panel_wel  .minImage").attr("src","/public/pws/invent/lib/images/minus.gif");
		$("#panel_wel").children('.content').css("display","block");
		//redraw observation panel graphs
		redrawObs();
	}	
	if(msie6){$('#welNav').toggle();}else{$('#welNav').slideToggle();}
	if(msie6){$('#customPanel').toggle();}else{$('#customPanel').slideToggle();}
	//Toggle other classes which give appearance of moveable panels
}

function setupCustomisePanel() {
   langPanels = [];
    unitsPanels = [];
    langPanelsDisplay = "";
    unitsPanelsDisplay = "";

	customiseHTML = "<h2>"+$.sprintf(_('Customise %(pageType)s pages'),{pageType:_(pageData.page.type).toLowerCase()})+"</h2><p>"+_('Add or remove panels by selecting or deselecting the boxes below')+"</p>";
	for (var p = 0 ; p < pageOrder.length; p++) {
		i = pageOrder[p];
		if (pageData.page.panels.panel[i]){
			temp = pageData.page.panels.panel[i];
			if(temp.closable) {
				$('#option_'+i).live("click", function(){
					if($(this).attr("checked")) {
						tempNum = this.id.substring(7);
						if(msie6){$('#panel_'+tempNum).show();}else{$('#panel_'+tempNum).slideDown('slow');}
							saveUserPrefs();
							$("#panel_" + tempNum + " .content").load("panels/" + pageData.page.panels.panel[tempNum].page, function() {
								runCallback(tempNum);
							
						});
					} else {
						tempNum = this.id.substring(7);
						if(msie6){$('#panel_'+tempNum).hide();}else{$('#panel_'+tempNum).slideUp('slow');}
							saveUserPrefs();
						
					}  
				});
			}
		}
	}
	for (var p = 0; p < pageOrder.length; p++) {
		i = pageOrder[p];
		if (pageData.page.panels.panel[i]){
			temp = pageData.page.panels.panel[i];
			if (temp.translatable) {
				langAvbl = true;
				langPanelsDisplay = langPanelsDisplay + _(temp.title) + ",";
				langPanels.push(i);
			}
			if (temp.convertable) {
				unitsAvbl = true;
				unitsPanelsDisplay = unitsPanelsDisplay + _(temp.title) + ",";
				unitsPanels.push(i);
			}
		}
	}

	customiseHTML += setupPanelButtons();
}

function setupPanelButtons() {
	var buttonHTML = '';
	var counter = 0;
	for (var p = 0; p < pageOrder.length; p++) {
		i = pageOrder[p];
		// cheat to stop warnings showing as a choice in the selectable preferences
		if (pageData.page.panels.panel[i] && (i!=="warnings")){
			temp = pageData.page.panels.panel[i];
			if (temp.closable){
			    title = temp.title;
			    if(temp.shortTitle)
			    {
			      title=temp.shortTitle;
			    }
			    
			    title = _(title);
			    
			    buttonHTML = buttonHTML + "<li id=cust" + i + " class='customise modifyItem'><input name='option_";
			    buttonHTML = buttonHTML + i + "' id='option_" + i + "' value='" + i + "' type='checkbox'";
			    buttonHTML = buttonHTML +"><label style='width:300px;' for='option_" + i + "'>" + title;
			    buttonHTML = buttonHTML + "</label></li>";
				counter++;
				if (counter == 3 && msie6) {
				  buttonHTML += "<br class='brclear'/>";
					counter = 0;
				}
			}
		}
	}
	return '<ul id=panelButtons>'+buttonHTML+'</ul>';
}

function getLang() {
    if (document.langSel && document.langSel !== null && document.langSel.length) {
        for (var i = 0,len = document.langSel.length; i <len; i++) 
        {
            if (translations.currentLang == document.langSel.lang[i].value) 
            {
                document.langSel.lang[i].checked = true;
            }
        }
    }
}

function applyLangChange(refresh) {
  setLangVariables();   
  if(refresh)
  {
    setPageSpecificLangVariables();       
    setupCustomisePanel();
    for (var j=0,len2=langPanels.length;j<len2;j++) {
        displayPanelTitle(langPanels[j]);
        $("#panel_"+langPanels[j]+" .content").load("panels/"+pageData.page.panels.panel[langPanels[j]].page, function() {
            runCallback($(this).parent().attr("id").substring(6));
        });
    }
    
    setNotTranslatableLabels();
  }
}

function setNotTranslatableLabels() {
  if(translations && translations.currentLang != 'Eng')
  {
    $('.not-translatable').html("<p>"+_('Sorry this is only available in English')+"</p>").show();
  }
  else{
    $('.not-translatable').html("").hide();
  }
}

function addNotTranslatableLabel() {
  var label = '<div class="not-translatable"';
  if(translations && translations.currentLang != 'Eng')
  {
    label+=">"+_('Sorry this is only available in English')+"<br/>";
  }
  else{
    label+=" style='display: none;'>";
  }
  label += "</div>";
  return label;
}

function changeLang() {
  selectedLang = "";
  if (document.langSel && document.langSel !== null && document.langSel.length) {
	  for (var i = 0,len = document.langSel.length; i <len; i++) 
	  {
		if (document.langSel.lang[i].checked) 
		{
		  selectedLang = document.langSel.lang[i].value;
		  break;
		}
	  }
  }
  if (selectedLang === "") 
  {
    alert(_('No language chosen'));
  }
  else {
    if(translations.currentLang!==selectedLang)
    {
      translations.setLang(selectedLang,
          function()
  	    {
  	      applyLangChange(true);
  	    }
      );
    }
  }
}

function loadLanguages(callback){
  var transOptions = 
  {
      cookie:'MOWxLang',
      cookieExpires:30,
      cookiePath:'/',
      translationPath:'/public/pws/lib/javascript/lang/',
      translationStem:'lang',
      configPath:panelsConfDir,
      configFile:'lang.txt'
  };
  translations.init(transOptions, 
      function()
      {
        if(typeof(callback)=='function')
        {
          callback();
        }
        applyLangChange(false);
      }
  );
}

function runCallback(panel) {
	try {
	    if(pageData.page.panels.panel[panel].callback)
	    {
	      eval(pageData.page.panels.panel[panel].callback + "(\"" + panel + "\")");
	    }
	} 
	catch(err) {}
}

function changeUnits(type) {
	if (type=="temperature"){
		pageTempUnits = "";
		for (var i = 0,len = document.unitsSelTemp.length; i <len; i++) {
			if (document.unitsSelTemp.temperatureUnits[i].checked) {pageTempUnits = document.unitsSelTemp.temperatureUnits[i].value;}
		}
		if (pageTempUnits === "") {alert(_('No units chosen'));}else {
			$.cookie('MOWxUnits', pageTempUnits, { expires: 30, path: "/"}); // path of / so that other apps can access it.
			for (var j=0,len2=unitsPanels.length;j<len2;j++) {
				$("#panel_"+unitsPanels[j]+" .content").load("panels/"+pageData.page.panels.panel[unitsPanels[j]].page, function() {
					runCallback($(this).parent().attr("id").substring(6));
				});
			}
		}
	}
	if (type=="speed"){
		pageSpeedUnits = "";
		for (var i = 0,len = document.unitsSelSpeed.length; i <len; i++) {
			if (document.unitsSelSpeed.speedUnits[i].checked) {pageSpeedUnits = document.unitsSelSpeed.speedUnits[i].value;}
		}
		if (pageSpeedUnits === "") {alert(_('No units chosen'));}else {
			$.cookie('MOWxSpeedUnits', pageSpeedUnits, { expires: 30, path: "/"}); // path of / so that other apps can access it.
			for (var j=0,len2=unitsPanels.length;j<len2;j++) {
				$("#panel_"+unitsPanels[j]+" .content").load("panels/"+pageData.page.panels.panel[unitsPanels[j]].page, function() {
					runCallback($(this).parent().attr("id").substring(6));
				});
			}
		}
	}
	if (type=="pressure"){
		pagePresUnits = "";
		for (var i = 0,len = document.unitsSelPres.length; i <len; i++) {
			if (document.unitsSelPres.pressureUnits[i].checked) {pagePresUnits = document.unitsSelPres.pressureUnits[i].value;}
		}
		if (pageTempUnits === "") {alert(_('No units chosen'));}else {
			$.cookie('MOWxPresUnits', pagePresUnits, { expires: 30, path: "/"}); // path of / so that other apps can access it.
			for (var j=0,len2=unitsPanels.length;j<len2;j++) {
				$("#panel_"+unitsPanels[j]+" .content").load("panels/"+pageData.page.panels.panel[unitsPanels[j]].page, function() {
					runCallback($(this).parent().attr("id").substring(6));
				});
			}
		}
	}
}

function ctof(degc) {
	var f = ((9*degc)/5) + 32;
	f = Math.round(f*Math.pow(10,1))/Math.pow(10,1);
	return f;
}
function mphtokt(xmph) {
	var ykt = xmph * 0.868978242;
	ykt = Math.round(ykt*Math.pow(10,0))/Math.pow(10,0);
	return ykt;
}
function mphtokmh(xmph) {
	var ykmh = xmph * 1.609344;
	ykmh = Math.round(ykmh*Math.pow(10,0))/Math.pow(10,0);
	return ykmh;
}
function hPatoIns(xhpa) {
	var yins = xhpa/33.86;
	yins = Math.round(yins*Math.pow(10,2))/Math.pow(10,2);
	return yins;
}
function resetCustomisation() {
	$.cookie("MOWx"	+ pageData.page.type, null);
	document.location.reload();
}

function visToWords(vis){
  if(vis < 1) {return 'Very poor';}
  if(vis >= 1 && vis < 4) {return 'Poor';}
  if(vis >= 4 && vis < 10) {return 'Moderate';}
  if(vis >= 10 && vis < 20) {return 'Good';}
  if(vis >= 20 && vis < 40) {return 'Very good';}
  if(vis >= 40) {return 'Excellent';}
  else {return 'N/A';}
}

function capitalise(input) {
  var pattern = /(\w)(\w*)/; // a letter, and then one, none or more letters 
  var a = input.split(/\s+/g); // split the sentence into an array of words

  for (var i = 0 ; i < a.length ; i ++ ) {
      var parts = a[i].match(pattern); // just a temp variable to store the fragments in.
      var firstLetter = parts[1].toUpperCase();
      var restOfWord = parts[2].toLowerCase();
      a[i] = firstLetter + restOfWord; // re-assign it back to the array and move on
  }
  return a.join(' '); // join it back together 
}

