function getColorFromCat(catogry) {
	switch (catogry) {
	
		case "SLIGHT":
			return '#92D050';
		break;
		
		case "MODERATE":
			return '#FFC000';
		break;
		
		case "HIGH":
			return '#FF6600';
		break;
		
		case "SEVERE":
			return '#FF0000';
		break;
	
		case "EXTREMELY SEVERE":
			return '#FF00FF';
		break;
		
		case "No Convective Activity":
			return '#FFFFFF';
		break;
		
		case "Watch":
			return '#FFCC33';
		break;
		
		case "Thunderstorms":
			return '#FFFF00';
		break;
		
		case "Severe":
			return '#00FE00';
		break;
	
		case "Extreme":
			return '#FE0000';
		break;
		
		default:
		return '';
	}
}

var InteractiveMap = {
	/*
	 UKASF - Forecast Map
	*/
	
	'map': 		null,
	'config':	null,
	'URL':		'http://ukasf.co.uk',
	'markers':	new Array(),
	'poly':		new Array(),
	'cached':	{forecast: false, strikes: false, radar: false},
	
	'initialize': function(options) {
		InteractiveMap.config = options;
		InteractiveMap.initializeMap();
		InteractiveMap.addControl();
	},
	
	'initializeMap': function() {
		var myOptions = {
			zoom: InteractiveMap.config.map.defaultZoom,
			center: new google.maps.LatLng(InteractiveMap.config.map.center[0], InteractiveMap.config.map.center[1]),
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			streetViewControl: false,
			mapTypeControl: true,
			mapTypeControlOptions: {
				style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
			},
			zoomControl: true,
			zoomControlOptions: {
				style: google.maps.ZoomControlStyle.SMALL
			}
		};
		
		var selectedDiv = document.getElementById(InteractiveMap.config.map.mapDivId);
		InteractiveMap.map = new google.maps.Map(selectedDiv, myOptions);
		
		var allowedBounds = new google.maps.LatLngBounds(
			new google.maps.LatLng(InteractiveMap.config.map.bounds[0][0], InteractiveMap.config.map.bounds[0][1]),
			new google.maps.LatLng(InteractiveMap.config.map.bounds[1][0], InteractiveMap.config.map.bounds[1][1])
		);

		google.maps.event.addListener(InteractiveMap.map,'dragend',function() { InteractiveMap.util.checkBounds(allowedBounds); });
			
	},
	
	'addControl': function() { //Private
		var items = [];
		
		for (i in InteractiveMap.config.controls) {
			var overlay = InteractiveMap.config.controls[i];
			items.push({
				'label':    overlay.label,
				'checked':  overlay.checked,
				'overlay':  overlay,
				'action':   function(i, item, checked) {
					switch (item.label) {
						case "Forecast":
							InteractiveMap.overlays.toggleForecast(checked);
						break;
						case "Lightning":
							InteractiveMap.overlays.toggleLightning(checked);
						break;
						case "Radar":
							InteractiveMap.overlays.toggleRadar(checked);
						break;
					}
				}
			});
		}
		
		InteractiveMap.util.createDropDown('Overlays', items);
	},
	
	 'overlays': {

		'toggleLightning' : function(checked) {
			if(checked) {		
				if(!InteractiveMap.cached.strikes) {
					if (InteractiveMap.config.archive) {
						var url = InteractiveMap.URL + '/api/lightning.php?start=' + InteractiveMap.config.forecast.start + '&end=' + InteractiveMap.config.forecast.end;
					} else {
						var url = InteractiveMap.URL + '/api/lightning.php';
					}
					$.ajax({
						type: "GET",
						url: url,
						dataType: "xml",
						success: function(xml){
							InteractiveMap.util.processStrikes(xml);
						}
					});
					InteractiveMap.cached.strikes = true;
				} else {
				InteractiveMap.util.toggleMarkers('category','strikes')
				}
			} else {
				InteractiveMap.util.toggleMarkers('category','strikes')
			}
		}, //toggleLightning
		
		'toggleForecast' : function(checked) {
			if(checked) {		
				if(!InteractiveMap.cached.forecast) {
				
				if(InteractiveMap.config.forecast.ID) {
					var url = InteractiveMap.URL +  '/api/mapXml.php?type=' + InteractiveMap.config.forecast.type + '&id=' + InteractiveMap.config.forecast.ID;
				} else {
					var url = 'http://data.weather2day.com/UKASF/Today';
				}
					$.ajax({
						type: "GET",
						url: url,
						dataType: "xml",
						success: function(xml){
							InteractiveMap.util.processForecast(xml);
						}
					});
					InteractiveMap.util.togglepoly(checked);
					InteractiveMap.cached.forecast = true;
				} else {
					InteractiveMap.util.togglepoly(checked);
				}
			} else {
				InteractiveMap.util.togglepoly(checked);
			}
		}, //toggleForecast
		
		'toggleRadar' : function(checked) {
			if(checked) {							
				RadarLayer = {
					getTileUrl : function (a,b) { 
						return  "http://mapserver.weather2day.com/radar2/tile/" + InteractiveMap.config.radar + "-" + InteractiveMap.util.quadKey(a.x,a.y,b) + ".png"; 
					},
					isPng: true,
					opacity: 0.7,
					tileSize: new google.maps.Size(256,256),
					name: "Radar",
					minZoom:13,
					maxZoom:20
				}

				// Now we have the options for the tile layer, we create the 
				// layer and add it to the main google.maps.Map (map)
				var RADARMapType = new google.maps.ImageMapType( RadarLayer );
				InteractiveMap.map.overlayMapTypes.setAt(1, null);
				InteractiveMap.map.overlayMapTypes.insertAt(1, RADARMapType);
			} else {
				InteractiveMap.map.overlayMapTypes.setAt(1, null);
			}
		}, //toggleRadar

	}, //overlays
	
	 'util': { //internal functions

        'createDropDown': function(title, items) {
            var control = document.createElement('DIV');
            // let's let a style sheet do most of the styling here
            $(control).addClass('customControl');

            var controlText = document.createElement('DIV');
            controlText.innerHTML = title;
			
			var arrow = document.createElement('img');
			arrow.src = 'http://maps.gstatic.com/mapfiles/arrow-down.png';
			arrow.className = "arrow";

            var controlBorder = document.createElement('DIV');
            $(controlBorder).addClass('top');
            control.appendChild(controlBorder);
            controlBorder.appendChild(controlText);
			controlBorder.appendChild(arrow);
			
            var dropdownDiv = document.createElement('DIV');
            $(dropdownDiv).addClass('dropDown');
            control.appendChild(dropdownDiv);
            dropdownDiv.innerHTML='';

            // add the functionality to toggle visibility of the items
            $(controlText).click(function() {
                    $(controlBorder).toggleClass('top-active');
                    $(dropdownDiv).toggle();
                });

            // add that control box we've made back to the map.
            InteractiveMap.map.controls[google.maps.ControlPosition.TOP_RIGHT].push(control);

            for(i in items) {
                // create the visible elements of the item
                var item = items[i];
                var itemDiv = document.createElement('div');
                var itemInput = document.createElement('input');
                itemInput.type='checkbox';

                // give it a name
                $(itemInput).data('label',item.label);
                jQuery(itemInput).click((function(local_idx, local_item) {
                                     return function(e) {
                                         item.action(local_idx, local_item, e.target.checked);
                                     };
                                 })(i, item));

                // if its checked, its gotta do something, do that here.
                if (item.checked) {
                    itemInput.checked = true;
                    item.action(i, item, item.checked);
                }
                dropdownDiv.appendChild(itemDiv);
                itemDiv.appendChild(itemInput);
                var textNode = document.createElement('text');
                if(item.icon) {
                    textNode.innerHTML = '<img width="15" height="15" src="' +
                        item.icon + '">' + item.label + '<br/>';
                } else {
                    textNode.innerHTML = item.label + '<br/>';
                }

                itemDiv.appendChild(textNode);
            }
        }, // createDropDown
		
		'processStrikes': function(xmlData) {
			var markerData = { category: 'strikes' };
			$(xmlData).find("strike").each(function() {
				var image = new google.maps.MarkerImage('http://ukasf.co.uk/modules/Storm/images/strike_old.png',
					new google.maps.Size(11, 19),
					new google.maps.Point(0,0),
					new google.maps.Point(3, 19));
					
				var myLatLng = new google.maps.LatLng($(this).attr("lat"), $(this).attr("lon"));
				
				var strike = new google.maps.Marker({
					position: myLatLng,
					data: markerData,
					map: InteractiveMap.map,
					icon: image
				});
				
				InteractiveMap.markers.push(strike);
			});
		}, //processStrikes
		
		'processForecast' : function(xmlData) {
			$(xmlData).find("poly").each(function() {
			var TempPloyLatLon = new Array();
			var PolyColor = getColorFromCat($(this).attr("cat"));
						
			$(this).find("point").each(function() {
				TempPloyLatLon.push(new google.maps.LatLng($(this).attr("lat"), $(this).attr("lon")))
			});	
					
			if($(this).attr("type") == "Ploygon") {
				var TempPloyLine = new google.maps.Polygon({
					paths: TempPloyLatLon,
					strokeColor: PolyColor,
					strokeOpacity: 0.9,
					strokeWeight: 3,
					fillColor: PolyColor,
					fillOpacity: 0.6
				});
				} else {
				var TempPloyLine = new google.maps.Polyline({
					path: TempPloyLatLon,
					strokeColor: PolyColor,
					strokeOpacity: 0.9,
					strokeWeight: 3
				});
				}	
				InteractiveMap.poly.push(TempPloyLine)
			});	

			for(i in InteractiveMap.poly) {
				InteractiveMap.poly[i].setMap(InteractiveMap.map);
			}
			
		}, //processForecast
		
		'quadKey': function(x, y, zoom) {
			var quad = "";
			for (var i = zoom; i > 0; i--) {
				var mask = 1 << (i - 1);
				var cell = 0;
				if ((x & mask) != 0)
					cell++;
				if ((y & mask) != 0)
					cell += 2;
				quad += cell;
			}
			return quad;
		}, // quadKey
		
		
		'toggleMarkers' : function(attr,val) {
			if (InteractiveMap.markers){
				for (i in InteractiveMap.markers) {
					if(InteractiveMap.markers[i].data[attr] == val){
						var visibility = (InteractiveMap.markers[i].getVisible() == true) ? false : true;
						InteractiveMap.markers[i].setVisible(visibility);
					}
				}
			}
		}, //toggleMarkers
		
		'togglepoly' : function(checked) {
			if (InteractiveMap.poly){
				for(i in InteractiveMap.poly) {
					if(checked) {
						InteractiveMap.poly[i].setMap(InteractiveMap.map);
					} else {
						InteractiveMap.poly[i].setMap(null);
					}	
				}
			}
		}, //togglepoly
		
		
		'checkBounds' : function(allowedBounds) {    
			if(! allowedBounds.contains(InteractiveMap.map.getCenter())) {
				var C = InteractiveMap.map.getCenter();
				var X = C.lng();
				var Y = C.lat();

				var AmaxX = allowedBounds.getNorthEast().lng();
				var AmaxY = allowedBounds.getNorthEast().lat();
				var AminX = allowedBounds.getSouthWest().lng();
				var AminY = allowedBounds.getSouthWest().lat();

				if (X < AminX) {X = AminX;}
				if (X > AmaxX) {X = AmaxX;}
				if (Y < AminY) {Y = AminY;}
				if (Y > AmaxY) {Y = AmaxY;}

				InteractiveMap.map.setCenter(new google.maps.LatLng(Y,X)); 
			}
		} //checkBounds
	}	
}





