Utils={iconLocation:"http://google-maps-icons.googlecode.com/files/",imageLocation:ServerVars.serverPath+"/images/",getQueryParams:function(){var qsParm=[];var query=window.location.search.substring(1);var parms=query.split('&');for(var i=0;i<parms.length;i++){var pos=parms[i].indexOf('=');if(pos>0){var key=parms[i].substring(0,pos);var val=parms[i].substring(pos+1);qsParm[key]=val;}}
return qsParm;},getPageName:function(){var pathName=window.location.pathname;var start=pathName.lastIndexOf('/')+1;var end=pathName.indexOf('.');return pathName.slice(start,end);},getPath:function(){var pathName=window.location.pathname;var end=pathName.lastIndexOf('/')+1;return pathName.slice(0,end);},latlongtoNews:function(lat,lng){var pos=Math.abs(lat);var dir=(lat>0?'N':'S');var deg=Math.floor(pos);var min=Math.floor((pos-deg)*60);var sec=Math.floor((pos-deg-min/60)*3600);var ns=deg+'\u00B0'+min+"'"+sec+'"'+dir;pos=Math.abs(lng);dir=(lng>0?'E':'W');deg=Math.floor(pos);min=Math.floor((pos-deg)*60);sec=Math.floor((pos-deg-min/60)*3600);var ew=deg+'\u00B0'+min+"'"+sec+'"'+dir;return ns+', '+ew+' ('+(Math.round(lat*10000)/10000)+', '+(Math.round(lng*10000)/10000)+')';},showPanel:function(panel){document.getElementById(panel+'Panel').style.display="";},hidePanel:function(panel){document.getElementById(panel+'Panel').style.display="none";return true;},getViewport:function(){var e=window,a='inner';if(!('innerWidth'in window)){a='client';e=document.documentElement||document.body;}
return{width:e[a+'Width'],height:e[a+'Height']};},showTooltip:function(ttText,x,y){var windowWidth=Utils.getViewport().width;var o=document.getElementById('tooltip');o.innerHTML=ttText;var ew;if(o.offsetWidth){ew=o.offsetWidth;}else{if(o.clip.width){ew=o.clip.width;}}
y=y+16;x=x-(ew/4);if(x<2){x=2;}else if(x+ew>windowWidth){x=windowWidth-ew-4;}
o.style.left=x+'px';o.style.top=y+'px';o.style.visibility='visible';},hideTooltip:function(){document.getElementById('tooltip').style.visibility='hidden';},gotoCoords:function(){var lat=document.getElementById("lat").value;var lng=document.getElementById("long").value;Map.Markers.addMarker(lng,lat);},jsCallify:function(func,text){return'<span class="jscall" onclick="'+func+'">'+text+'</span>';}};StatusLog={logDiv:null,msgs:{'init':'Initialising map','mapsetup':'Setting up map','gdata':'GData feed loading','geoload':'GeoJSON feed loading','maploaded':'Map loaded. '+Utils.jsCallify("StatusLog.logDiv.hide();return","Close")},init:function(div){this.logDiv=document.getElementById(div);this.logMsg('init');},logMsg:function(msg,param){if(msg=='fetch'){this.msgs[msg]='Fetching '+param+' data';}
if(msg=='loaded'){this.msgs[msg]=param+' data loaded';}
this.logDiv.innerHTML+=this.msgs[msg]+'<br />';},endMsg:function(){this.logMsg('maploaded');setTimeout(function(){StatusLog.logDiv.style.display='none';},5000);}};Dialogs={divs:{},params:{},urls:{},functions:{},setups:{},setup:function(dialogType){jQuery('body').append(this.divs[dialogType]);var dialogId='#'+dialogType;jQuery(dialogId).dialog(this.params[dialogType]);},open:function(dialogType,reuse){var dialogId='#'+dialogType;if(this.urls[dialogType]){var url=(this.urls[dialogType].match('http://'))?ServerVars.serverPath+"/prox.html?url="+this.urls[dialogType]:ServerVars.serverPath+this.urls[dialogType];if(reuse||jQuery(dialogId+':empty')[0]){jQuery(dialogId).load(url,this.functions[dialogType]);}}
jQuery(dialogId).dialog('open');}};Feed={worksheetCount:0,createScript:function(id,url){var old=document.getElementById(id);if(old!==null){old.parentNode.removeChild(old);}
url=url.replace(/amp;/g,'');var script=document.createElement('script');script.id=id;script.type='text/javascript';script.charset='utf-8';script.src=url;document.getElementsByTagName('head')[0].appendChild(script);},Json:{getPlaces:function(){var place=document.getElementById("place").value;var url='http://api.geonames.org/searchJSON?maxRows=10&username=peterrobins&isNameRequired=true&continentCode=eu&featureClass=P&style=full&callback=Feed.Json.showPlaces&q='+place;Feed.createScript('places',url);},showPlaces:function(feed){if(feed===null){alert("Nothing returned from geonames.org");return;}
var geonames=feed.geonames;if(geonames.length===0){alert("No such place on geonames.org");return;}
var lat,lng;if(geonames.length==1){lat=geonames[0].lat;lng=geonames[0].lng;Map.Markers.addMarker(lng,lat);}
else{var html='';for(var i=0;i<geonames.length;i++){var geoname=geonames[i];lat=geoname.lat;lng=geoname.lng;var fullName=geoname.name+', '+geoname.adminName1+', '+geoname.adminName2+', '+geoname.adminName3+', '+geoname.adminName4;html=html+Utils.jsCallify("Map.Markers.addMarker("+lng+", "+lat+")",fullName)+'<br />';}
document.getElementById('searchResults').innerHTML=html;}},getWikipedia:function(lng,lat){var url='http://api.geonames.org/findNearbyWikipediaJSON?callback=Feed.Json.showWikipedia&username=peterrobins&lat='+lat+'&lng='+lng;Feed.createScript('wiki',url);},showWikipedia:function(feed){var html='';if(typeof feed.geonames=='undefined'){html="No nearby Wikipedia entries or service unavailable";}
else{var geonames=feed.geonames;if(geonames.length===0){alert("No Wikipedia entries");return;}
for(var i=0;i<geonames.length;i++){var geoname=geonames[i];html+='<b>'+geoname.title+'</b> ('+geoname.lat+', '+geoname.lng+': '+geoname.distance+'km away)';html+='<br />'+geoname.summary;html+='<br />'+Utils.jsCallify("Map.Markers.addMarker("+geoname.lng+","+geoname.lat+")","Show on map")+' | <a href="http://'+geoname.wikipediaUrl+'" target="_blank">View Wikipedia page</a><br />';}}
document.getElementById('wikiResults').innerHTML=html;},getMetar:function(lng,lat){var url='http://api.geonames.org/findNearByWeatherJSON?callback=Feed.Json.showMetar&username=peterrobins&lat='+lat+'&lng='+lng;Feed.createScript('metar',url);},showMetar:function(feed){var html;if(typeof feed.weatherObservation=='undefined'){html="No nearby weather stations or report unavailable";}
else{var weather=feed.weatherObservation;html='<b>'+weather.stationName+'</b> ('+weather.ICAO+')';html+='<br />'+weather.lat+', '+weather.lng+'; altitude: '+weather.altitude;html+='<br />'+weather.datetime;html+='<br />'+weather.weatherCondition+'; '+weather.clouds+'; '+weather.temperature+'&deg;C; '+weather.hectoPascAltimeter+' hPa; humidity: '+weather.humidity+'%; wind: '+weather.windDirection+'&deg; @ '+weather.windSpeed+' knots';}
document.getElementById('weatherResults').innerHTML=html;}}};;jQuery.noConflict();OpenLayers.ImgPath=ServerVars.serverPath+"/css/img/";Map={wgs84:new OpenLayers.Projection("EPSG:4326"),map:null,baseLayers:{},specifics:{},features:false,create:function(){StatusLog.init('status');var controls;if(ServerVars.mobile){controls=[new OpenLayers.Control.TouchNavigation({dragPanOptions:{enableKinetic:true}}),new OpenLayers.Control.ZoomPanel(),new OpenLayers.Control.Attribution()]}else{controls=[new OpenLayers.Control.Navigation(),new OpenLayers.Control.KeyboardDefaults(),new OpenLayers.Control.PanZoomBar(),new OpenLayers.Control.Attribution()]};var options={controls:controls,theme:null,zoomToFeatures:false,defaultLonglat:new OpenLayers.LonLat(0,0),defaultZoom:0};OpenLayers.Util.extend(options,this.baseLayers.mapOptions);this.map=new OpenLayers.Map('map',options);var layers=this.baseLayers.get();for(var i=0;i<layers.length;i++){this.map.addLayer(layers[i]);if(this.baseLayers.afterAdd){this.baseLayers.afterAdd(layers[i]);}}
if(this.baseLayers.getLogoControl){this.map.addControl(this.baseLayers.getLogoControl());}
if(layers.length>1){this.Controls.switcher=true;}
this.map.defaultLonglat=new OpenLayers.LonLat(this.baseLayers.defaultCentre[0],this.baseLayers.defaultCentre[1]);this.map.defaultZoom=this.baseLayers.defaultCentre[2];if(this.map.projection!="EPSG:4326"){this.map.displayProjection=this.wgs84;this.map.defaultLonglat.transform(this.map.displayProjection,this.map.baseLayer.projection);if(this.map.projection!="EPSG:3857"){this.map.addControl(new OpenLayers.Control.ScaleLine());}
if(!ServerVars.mobile){this.map.addControl(new OpenLayers.Control.MousePosition({id:"m_mouse",prefix:this.baseLayers.m_mousePrefix,displayProjection:this.map.baseLayer.projection,numDigits:0}));}}
if(!ServerVars.mobile){this.map.addControl(new OpenLayers.Control.MousePosition({id:"ll_mouse",formatOutput:function(lonLat){return Utils.latlongtoNews(lonLat.lat,lonLat.lon);}}));}
var panel=this.Controls.getPanel();this.map.addControl(panel);if(this.specifics.setupVectorOptions){var mapProjs={};if(this.map.projection!="EPSG:4326"){mapProjs={int:this.map.baseLayer.projection,ext:this.wgs84};}
this.doVectors(mapProjs);}
controls=this.specifics.controls||[];for(i=0;i<controls.length;i++){if(controls[i]=='perma'){this.map.addControl(new OpenLayers.Control.Permalink(null,null,{id:'thisPerma',title:"Link to display this map again"}));}
if(controls[i]=='argparser'){this.map.addControl(new OpenLayers.Control.ArgParser());}
if(controls[i]=='search'){var buttons=this.Controls.getSearch();buttons[1].trigger=this.Markers.clearMarkers;panel.addControls(buttons);this.specifics.markers=true;}
if(controls[i]=='positionClick'){var clickControl=this.Controls.addPositionClick();this.map.addControl(clickControl);clickControl.activate();jQuery("a:not(.ui-dialog-titlebar-close)").mousedown(function(event){clickControl.deactivate();});}
if(controls[i]=='bbox'){this.map.addControl(this.specifics.getBboxControl());}}
if(this.specifics.markers){this.map.addLayer(this.Markers.getLayer());}
if(this.addGeolocate){this.addGeolocate();if(this.Controls.getRefresh){panel.addControls([this.Controls.getRefresh()]);}
panel.addControls([this.Controls.getClear()]);}
if(this.specifics.vectorControls){controls=this.getVectorControls(this.specifics.vectorControls);panel.addControls(controls);}
if(this.Controls.switcher){this.map.addControl(new OpenLayers.Control.LayerSwitcher({title:"Switch/add/remove layers",roundedCorner:false}));}
if(this.map.zoomToFeatures===false&&!ServerVars.zoom&&!this.addGeolocate){this.map.setCenter(this.map.defaultLonglat,this.map.defaultZoom);}
if(location.search){var args=OpenLayers.Util.getParameters();if(args.mark=='y'){this.Markers.addMarker(args.lon,args.lat,false);}}
if((this.map.zoomToFeatures===false&&this.features===false)||this.addGeolocate){StatusLog.endMsg();}},addMarker:function(lng,lat,title,isMapProj){var lonlat=new OpenLayers.LonLat(lng,lat);if(isMapProj!==true){if(this.map.projection!="EPSG:4326"){lonlat.transform(this.map.displayProjection,this.map.baseLayer.projection);}}
var bounds=this.map.getMaxExtent();if(bounds.containsLonLat(lonlat)){if(!title){var zoom=this.map.getZoom();if(zoom<3){zoom=zoom+3;}
this.map.setCenter(lonlat,zoom);}
var imgTitle=title?title:'Lat '+lat+', long '+lng;if(isMapProj===true){imgTitle='x '+lng+', y '+lat;}
this.map.getLayersByName('Search markers')[0].addMark(lonlat,imgTitle);}
else{alert("Coordinates not on map!");}},Controls:{getClick:function(trigger){return new this.ClickControl({'trigger':trigger});},addPositionClick:function(){Dialogs.divs.position='<div id="position" title="Position clicked" style="font-size: 10px"></div>';Dialogs.params.position={maxHeight:300,position:'top',autoOpen:false};Dialogs.setup('position');var click=this.getClick(this.positionDisplay);return click;},positionDisplay:function(event){var map=event.object;var lonlat=map.getLonLatFromViewPortPx(event.xy);if(map.projection!="EPSG:4326"){lonlat.transform(map.baseLayer.projection,map.displayProjection);}
var lat=Math.round(lonlat.lat*1000000)/1000000;var lon=Math.round(lonlat.lon*1000000)/1000000;var html='You clicked at latitude '+lat+', longitude '+lon;html+='<p>Get '+Utils.jsCallify("Feed.Json.getMetar("+lon+", "+lat+")","METAR weather report")+' from nearest station</p>';html+='<div id="weatherResults"></div>';html+='<p>Show nearby '+Utils.jsCallify("Feed.Json.getWikipedia("+lon+", "+lat+")","Wikipedia entries")+'</p>';html+='<div id="wikiResults"></div>';jQuery('#position').html(html);jQuery('#position').dialog('open');},getPanel:function(){if(ServerVars.helpUrl){Dialogs.urls.help=ServerVars.helpUrl;Dialogs.divs.help='<div id="help" title="Help: click on heading to hide/show details" style="font-size: 10px"></div>';}
Dialogs.params.help={maxHeight:300,width:300,position:'top',autoOpen:false};Dialogs.functions.help=function(){jQuery('#help').find('p,ol,ul').hide().end().find('h4').click(function(){jQuery(this).nextUntil('h4').slideToggle();});};Dialogs.setup('help');var panel=new OpenLayers.Control.Panel();panel.addControls([new OpenLayers.Control.Button({displayClass:'helpButton',trigger:function(){Dialogs.open('help');},title:"Help"})]);return panel;},getSearch:function(){Dialogs.divs.search='<div id="search" title="Search for coordinates/placenames" style="font-size: 10px"></div>';Dialogs.params.search={position:'top',autoOpen:false};Dialogs.urls.search='/searchPanel.html';Dialogs.setup('search');return[new OpenLayers.Control.Button({displayClass:'searchButton',trigger:function(){Dialogs.open('search');},title:"Search for coords/placename"}),new OpenLayers.Control.Button({displayClass:'clearButton',title:"Clear search markers"})];},ClickControl:OpenLayers.Class(OpenLayers.Control,{defaultHandlerOptions:{'single':true,'double':false,'pixelTolerance':0,'stopSingle':false,'stopDouble':false},initialize:function(options){this.handlerOptions=OpenLayers.Util.extend({},this.defaultHandlerOptions);OpenLayers.Control.prototype.initialize.apply(this,arguments);this.handler=new OpenLayers.Handler.Click(this,{'click':options.trigger},this.handlerOptions);}})}};
