var currentWeatherPath = 'england';
var WalesWeather = {

	isReady: false,

	Panels: {
	},
	
	Reload: function(){
		window.location.reload();
	},


	EnhanceWeather: function(){
		WalesWeather.Add.EditWeather();
		WalesWeather.Localise.SetEvents();
		WalesWeather.Userfeedback.LoadPanels();
		WalesWeather.isReady=true;
	},

	Add: {
		EditWeather: function(){
			glow.events.addListener(
				'#weatheredit',
				'click',
				function(){ glow.dom.get('#weather-edit-container').toggleClass('nodisplay'); return false; }
			);

			glow.events.addListener(
				'#weatherCancel',
				'click',
				function(){ glow.dom.get('#weather-edit-container').addClass('nodisplay'); return false; }
			);						

		},
		Panel: function(id, oPanel){
			WalesWeather.Panels[id] = oPanel;
		}			     
	},


	Localise: {
		SetEvents: function(){
			glow.events.addListener(
				'#weatherSaveChanges',
				'click',
				function(){WalesWeather.Localise.MakeRequest(glow.dom.get('#weatherpostcode').val()); return false;}
			);							
		},

		MakeRequest: function(loc){
			//glow.net.get("testdata/postcoder/cardiff.xml",
			glow.net.get("/cgi-perl/whereilive/query/place.pl?loc="+ loc +"&customer=postcoder",
			{
				onLoad: function(response){
					var numResults = {length:0};
					if (response.text().match(/<result>/g)){numResults = response.text().match(/<result>/g);}
					WalesWeather.Localise.Response = response.xml();

					switch(numResults.length){

						case 0: //No results
							if (!glow.dom.get('#weathermultiplelocation').hasClass('nodisplay')){
								glow.dom.get('#weathermultiplelocation').addClass('nodisplay');
							}
							glow.dom.get('#weathernolocation').removeClass('nodisplay');
							break;

						case 1: //1 result found
							//Insert result text into panel
							glow.dom.get('#weatherselectedlocation').text(response.xml().getElementsByTagName('result')[0].getElementsByTagName('name')[0].firstChild.data +', ' + response.xml().getElementsByTagName('result')[0].getElementsByTagName('hint')[0].firstChild.data);
							WalesWeather.Userfeedback.ShowPanel('weatherconfirmlocation');
							break;

						default: //more than 1 found
							glow.dom.get('#weathermultireslist').children().remove();								
							for (var i=0; i<response.xml().getElementsByTagName('result').length; i++){
								var multilink = glow.dom.create('<li id="'+ response.xml().getElementsByTagName('result')[i].getElementsByTagName('id')[0].firstChild.data +'"><a href="/'+currentWeatherPath+'">' + response.xml().getElementsByTagName('result')[i].getElementsByTagName('name')[0].firstChild.data + ', ' + response.xml().getElementsByTagName('result')[i].getElementsByTagName('hint')[0].firstChild.data +'</a></li>');
								glow.events.addListener(
									multilink,
									'click',
									function(){WalesWeather.Localise.MakeRequest(this.id);return false;}
								);
								glow.dom.get('#weathermultireslist').append(multilink);
							}
							if (!glow.dom.get('#weathernolocation').hasClass('nodisplay')){
								glow.dom.get('#weathernolocation').addClass('nodisplay');
							}
							glow.dom.get('#weathermultiplelocation').removeClass('nodisplay');
					}
									

				},
				onError: function(response){
					try{
						console.log(response.statusText());
					}
					catch(e){}
				}
			}
			);
		}
	},

	Userfeedback: {
		LoadPanels: function(){
			glow.net.get('/'+currentWeatherPath+'/ssi/panels-weather.sssi', 
				{
					onLoad: function(response){
						WalesWeather.Panels.status = response.statusText();
						glow.dom.get('#blq-container').append(glow.dom.create(response.text()));

						glow.events.addListener (
							'#weatherconfirmlocationyes',
							'click',
							function(){
								WalesWeather.Cookie.Build(WalesWeather.Localise.Response);
								WalesWeather.Userfeedback.HidePanel('weatherconfirmlocation');
								window.location.reload();
							}
						);

						glow.events.addListener (
							'#weatherconfirmlocationno',
							'click',
							function(){
								WalesWeather.Userfeedback.HidePanel('weatherconfirmlocation');
								return false;
							}
						);

						glow.events.addListener (
							'#weatherresetlocationyes',
							'click',
							function(){
								document.cookie = 'BBCpostcoder=;expires=Thu, 01-Jan-1970 00:00:01 GMT;path="/";domain="bbc.co.uk"';
								WalesWeather.Userfeedback.HidePanel('weatherresetlocation');
								window.location.reload();
								return false;
							}
						);

						glow.events.addListener (
							'#weatherresetlocationno',
							'click',
							function(){
								WalesWeather.Userfeedback.HidePanel('weatherresetlocation');
							}
						);										

						WalesWeather.Add.Panel('weatherconfirmlocation', new glow.widgets.Panel('#weatherconfirmlocation'));
						WalesWeather.Add.Panel('weatherresetlocation', new glow.widgets.Panel('#weatherresetlocation'));

					},
					onError: function(response){
						WalesWeather.Panels.status = response.statusText();
					}						
						
				}
			);
	
		},

		ShowPanel: function(panelId){
			if (WalesWeather.Panels[panelId]){
				WalesWeather.Panels[panelId].opts.x=((glow.dom.get("#header").offset().top)-36) + "px";
				WalesWeather.Panels[panelId].opts.y=((glow.dom.get("#header").offset().left)+20) + "px";
				WalesWeather.Panels[panelId].show();
			}
		},
		
		HidePanel: function(panelId){
			if (WalesWeather.Panels[panelId]){
				WalesWeather.Panels[panelId].hide();
			}
		}			    
	},
	Cookie: {
	
		PCLookup: [
			{ CookieVal: 'PST', Lookup:['result', 'postcode'] },
			{ CookieVal: 'QRY', Lookup:['result','name']},
			{ CookieVal: 'LEA', Lookup:['lea','id'] },
			{ CookieVal: 'TVR', Lookup:['bbctv','id'] },
			{ CookieVal: 'WEA', Lookup:['weather','id'] },
			{ CookieVal: 'CCI', Lookup:['county_council','id'] },
			{ CookieVal: 'CON', Lookup:['constituency','id'] },
			{ CookieVal: 'CTY', Lookup:['county','id'] },
			{ CookieVal: 'DST', Lookup:['result','district'] },
			{ CookieVal: 'EUR', Lookup:['euro_region','id'] },
			{ CookieVal: 'LAU', Lookup:['local_authority','id'] },
			{ CookieVal: 'LST', Lookup:['listings','id'] },
			{ CookieVal: 'NHS', Lookup:['health_authority','id'] },
			{ CookieVal: 'TWN', Lookup:['post_town','id'] },
			{ CookieVal: 'RAD', Lookup:['radio','id'] },
			{ CookieVal: 'WRD', Lookup:['ward','id'] },
		/*	{ CookieVal: 'TIM', Lookup:' id' },*/
			{ CookieVal: 'WIL', Lookup:['wil','id'] },
			{ CookieVal: 'MAT', Lookup:['result','match_type'] }
		],
		
		Build: function(oXml){
			var myCookie = 'BBCpostcoder=';				
			var date = new Date();
			date.setTime(date.getTime()+(100*24*60*60*1000));
			var properties = "; expires="+date.toGMTString();
			properties += '; domain=bbc.co.uk; path=/';
		
			for (i in WalesWeather.Cookie.PCLookup){
				myCookie += WalesWeather.Cookie.PCLookup[i].CookieVal +oXml.getElementsByTagName(WalesWeather.Cookie.PCLookup[i].Lookup[0])[0].getElementsByTagName(WalesWeather.Cookie.PCLookup[i].Lookup[1])[0].firstChild.data +':';
			}
			document.cookie = myCookie + properties;
		}
	}		      
}
