OpenLayers.Format.QueryStringFilter=(function(){var cmpToStr={};cmpToStr[OpenLayers.Filter.Comparison.EQUAL_TO]="eq";cmpToStr[OpenLayers.Filter.Comparison.NOT_EQUAL_TO]="ne";cmpToStr[OpenLayers.Filter.Comparison.LESS_THAN]="lt";cmpToStr[OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO]="lte";cmpToStr[OpenLayers.Filter.Comparison.GREATER_THAN]="gt";cmpToStr[OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO]="gte";cmpToStr[OpenLayers.Filter.Comparison.LIKE]="ilike";function regex2value(value){value=value.replace(/%/g,"\\%");value=value.replace(/\\\\\.(\*)?/g,function($0,$1){return $1?$0:"\\\\_";});value=value.replace(/\\\\\.\*/g,"\\\\%");value=value.replace(/(\\)?\.(\*)?/g,function($0,$1,$2){return $1||$2?$0:"_";});value=value.replace(/(\\)?\.\*/g,function($0,$1){return $1?$0:"%";});value=value.replace(/\\\./g,".");value=value.replace(/(\\)?\\\*/g,function($0,$1){return $1?$0:"*";});return value;}
return OpenLayers.Class(OpenLayers.Format,{wildcarded:false,srsInBBOX:false,write:function(filter,params){params=params||{};var className=filter.CLASS_NAME;var filterType=className.substring(className.lastIndexOf(".")+1);switch(filterType){case"Spatial":switch(filter.type){case OpenLayers.Filter.Spatial.BBOX:params.bbox=filter.value.toArray();if(this.srsInBBOX&&filter.projection){params.bbox.push(filter.projection.getCode());}
break;case OpenLayers.Filter.Spatial.DWITHIN:params.tolerance=filter.distance;case OpenLayers.Filter.Spatial.WITHIN:params.lon=filter.value.x;params.lat=filter.value.y;break;default:OpenLayers.Console.warn("Unknown spatial filter type "+filter.type);}
break;case"Comparison":var op=cmpToStr[filter.type];if(op!==undefined){var value=filter.value;if(filter.type==OpenLayers.Filter.Comparison.LIKE){value=regex2value(value);if(this.wildcarded){value="%"+value+"%";}}
params[filter.property+"__"+op]=value;params.queryable=params.queryable||[];params.queryable.push(filter.property);}else{OpenLayers.Console.warn("Unknown comparison filter type "+filter.type);}
break;case"Logical":if(filter.type===OpenLayers.Filter.Logical.AND){for(var i=0,len=filter.filters.length;i<len;i++){params=this.write(filter.filters[i],params);}}else{OpenLayers.Console.warn("Unsupported logical filter type "+filter.type);}
break;default:OpenLayers.Console.warn("Unknown filter type "+filterType);}
return params;},CLASS_NAME:"OpenLayers.Format.QueryStringFilter"});})();;OpenLayers.Filter.Spatial=OpenLayers.Class(OpenLayers.Filter,{type:null,property:null,value:null,distance:null,distanceUnits:null,evaluate:function(feature){var intersect=false;switch(this.type){case OpenLayers.Filter.Spatial.BBOX:case OpenLayers.Filter.Spatial.INTERSECTS:if(feature.geometry){var geom=this.value;if(this.value.CLASS_NAME=="OpenLayers.Bounds"){geom=this.value.toGeometry();}
if(feature.geometry.intersects(geom)){intersect=true;}}
break;default:throw new Error('evaluate is not implemented for this filter type.');}
return intersect;},clone:function(){var options=OpenLayers.Util.applyDefaults({value:this.value&&this.value.clone&&this.value.clone()},this);return new OpenLayers.Filter.Spatial(options);},CLASS_NAME:"OpenLayers.Filter.Spatial"});OpenLayers.Filter.Spatial.BBOX="BBOX";OpenLayers.Filter.Spatial.INTERSECTS="INTERSECTS";OpenLayers.Filter.Spatial.DWITHIN="DWITHIN";OpenLayers.Filter.Spatial.WITHIN="WITHIN";OpenLayers.Filter.Spatial.CONTAINS="CONTAINS";;OpenLayers.ProxyHost=ServerVars.serverPath+"/prox.html?url=";Map.Markers={getLayer:function(){var markerStyle={externalGraphic:Utils.imageLocation+"bluearrow.png",graphicWidth:16,graphicHeight:16,graphicYOffset:-16};var addMark=function(lonlat,imgTitle){var point=new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat);var feature=new OpenLayers.Feature.Vector(point,{title:imgTitle,clickable:'off'});this.addFeatures([feature]);};return new OpenLayers.Layer.Vector('Search markers',{style:markerStyle,addMark:addMark});},addMarker:function(lng,lat){Map.addMarker(lng,lat);},add:function(lat,lng,name){Map.addMarker(lng,lat,name);},clearMarkers:function(){this.map.getLayersByName('Search markers')[0].destroyFeatures();}};Map.doVectors=function(mapProjs,inputDone){var defaultInputDone=function(){if(this.feedCount==this.feedsRead){StatusLog.logMsg('mapsetup');if(this.zoomToFeatures===true){if(ServerVars.bbox){var bounds=OpenLayers.Bounds.fromString(ServerVars.bbox);if(this.projection!="EPSG:4326"){bounds.transform(this.displayProjection,this.baseLayer.projection);}
this.zoomToExtent(bounds);}else{if(this.featureExtent.bottom!==null){this.zoomToExtent(this.featureExtent);}
else{this.setCenter(this.defaultLonglat,this.defaultZoom);}}}
StatusLog.endMsg();}};this.addTooltipDiv=function(){jQuery('body').append('<div class="popup" id="tooltip" style="visibility: hidden"></div>');};OpenLayers.Util.extend(this.map,{feedsRead:0,feedCount:0,featureExtent:new OpenLayers.Bounds(),inputDone:inputDone||defaultInputDone,featureOver:function(feature){var fname=feature.attributes.name||feature.attributes.title||feature.attributes.id||feature.fid;if(feature.geometry.CLASS_NAME=="OpenLayers.Geometry.LineString"&&feature.layer.calcKm){fname+=' '+this.map.getLength(feature);}
var xy=this.map.getControl('ll_mouse').lastXy||{x:0,y:0};Utils.showTooltip(fname,xy.x,xy.y);},getLength:function(feature){return Math.round(feature.geometry.getGeodesicLength(feature.layer.map.baseLayer.projection)*0.1)/100+'km';}});if(this.specifics.addTc){this.addTc(this.specifics.addTc);}
var mapThis=this;var createVectorLayer=function(layerName,inOptions){var options;if(inOptions.passThrough){options=inOptions.passThrough;}
else{options={};}
var otherOptions={};if(inOptions.strategyTypes){options.strategies=[];for(var i=0;i<inOptions.strategyTypes.length;i++){options.strategies.push(new OpenLayers.Strategy[inOptions.strategyTypes[i]]);}}
if(inOptions.type=='FS'){options.serverLocation=window.location.hostname=="localhost"?"/test/fs/featureserver.cgi/":"/cgi-bin/fs/";inOptions.format='geo';inOptions.protocolOptions={url:options.serverLocation+inOptions.fsFile};}
options.protocolOptions=inOptions.protocolOptions||{};options.protocolOptions.format=inOptions.protocolOptions.format||createFormat(inOptions.format,inOptions.extractStyles,inOptions.mapProjs);var protocolType=inOptions.protocolType||'HTTP';options.protocol=new OpenLayers.Protocol[protocolType](options.protocolOptions);if(inOptions.defaultStyle){options.styleMap=mapThis.Styles.createStyleMap(inOptions.defaultStyle,inOptions.rulesArray,inOptions.poiStyleWanted);}
if(inOptions.includeInInitialZoom){otherOptions.includeInInitialZoom=inOptions.includeInInitialZoom;}
if(inOptions.featureAdded){otherOptions.featureAdded=inOptions.featureAdded;}
var layer=new Map.OberVector(layerName,options,otherOptions);if(layer.strategies){for(i=0;i<layer.strategies.length;i++){if(layer.strategies[i].CLASS_NAME=="OpenLayers.Strategy.Save"){layer.saveSuccess=function(event){alert('Changes saved');};layer.saveFail=function(event){alert('Error! Changes not saved');};layer.strategies[i].events.on({'success':layer.saveSuccess,'fail':layer.saveFail,scope:layer});}}}
return layer;};this.specifics.setupVectorOptions();var layerOptions=this.specifics.layerOptions;var layers=Array();for(var layerName in layerOptions){layerOptions[layerName].mapProjs=mapProjs;var layer=createVectorLayer(layerName,layerOptions[layerName]);if(this.specifics.afterAdd){this.specifics.afterAdd(layer);}
layers.push(layer);if(layerOptions[layerName].lineLayer){this.map.lineLayerId=layer.id;}
if(layerOptions[layerName].addSelect){layer.featureSelect=this.Controls.selects[layerOptions[layerName].addSelect];}}
if(this.specifics.poi===true){layerOptions=this.getPoiLayerOptions();for(layerName in layerOptions){layerOptions[layerName].mapProjs=mapProjs;layers.push(createVectorLayer(layerName,layerOptions[layerName]));}
this.specifics.switcher=true;}
if(this.specifics.placesLayer){layerOptions=this.getPlacesLayerOptions(this.specifics.placesLayer);layerOptions.mapProjs=mapProjs;layers.push(createVectorLayer('Places',layerOptions));}
this.map.addLayers(layers);OpenLayers.Util.extend(this.map,this.specifics.mapOptions);if(this.specifics.switcher===true){this.Controls.switcher=true;}
if(this.specifics.features=='n'){this.features=false;}
else{this.features=true;}
function createFormat(format,extractStyles,mapProjs){var formats={gml:OpenLayers.Format.GML,kml:OpenLayers.Format.KML,wkt:OpenLayers.Format.WKT,geo:OpenLayers.Format.GeoJSON,atom:OpenLayers.Format.Atom};var options={};if(mapProjs){options.internalProjection=mapProjs.int;options.externalProjection=mapProjs.ext;}
if(extractStyles){if(format=='kml'||format=='atom'){options.extractStyles=true;}}
if(format=='atom'){options.kmlContent=true;options.georssContent=false;}
if(format=='geo'){options.ignoreExtraDims=true;}
return new formats[format](options);}};Map.getVectorControls=function(vectorControls){var controls=Array();for(var i=0;i<vectorControls.length;i++){if(vectorControls[i]=='selectFeature'){var options=this.specifics.selectFeature;if(typeof options.selectFunction=="string"){options.selectFunction=this.Controls.selects[options.selectFunction];}
this.addTooltipDiv();if(options.dialog=='feature'){Dialogs.setups.wiki();}
if(Dialogs.setups[options.dialog]){Dialogs.setups[options.dialog]();}
var controlOptions={onSelect:options.selectFunction};if(!this.addGeolocate){controlOptions.callbacks={over:this.map.featureOver,out:Utils.hideTooltip};}
if(options.geometryTypes){controlOptions.geometryTypes=options.geometryTypes;}
var layers=this.map.getLayersByClass('OpenLayers.Layer.Vector');var selectControl=new OpenLayers.Control.SelectFeature(layers,controlOptions);this.map.addControl(selectControl);selectControl.activate();}
if(vectorControls[i]=='baselayerChange'){controls.push(this.Controls.getBaselayerChange(this.map));this.map.getOtherMap=this.Controls.getOtherMap;}
if(vectorControls[i]=='palette'){controls.push(this.Controls.getPalette(this.map));this.map.changeColour=this.Controls.changeColour;}
if(vectorControls[i]=='print'){this.map.print=function(){var perma=this.map.getControl('thisPerma');var params=perma.createParams();var base=perma.base.split('?')[0];base+=ServerVars.bbox?'?bbox='+ServerVars.bbox+'&':'?';var url=base+'zoom='+params.zoom+'&lat='+params.lat+'&lon='+params.lon+'&layers='+params.layers+'&print=y';var w=window.open(url,"MapPrint");w.focus();};var func=this.Controls.getPrintButton();func.trigger=this.map.print;controls.push(func);}
if(vectorControls[i]=='editToolbar'){this.addTooltipDiv();var layerName='Vectors';var noAdd;if(this.specifics.editToolbar){options=this.specifics.editToolbar;if(options.layerName){layerName=options.layerName;}
if(options.noAdd){noAdd=options.noAdd;}}
var layer=this.map.getLayersByName(layerName)[0];layer.newAttribute=this.Controls.newAttribute;layer.enterAttributes=this.Controls.enterAttributes;layer.editAttributes=this.Controls.editAttributes;layer.freshAttributes=this.Controls.freshAttributes;this.map.addControl(this.Controls.getEditToolbar(layer,this.Styles.styles.edit,noAdd));}}
return controls;};Map.OberVector=OpenLayers.Class(OpenLayers.Layer.Vector,{calcKm:false,initialize:function(name,options,otherOptions){OpenLayers.Layer.Vector.prototype.initialize.apply(this,[name,options]);otherOptions=otherOptions||{};if(otherOptions.includeInInitialZoom){this.events.register('loadstart',this,function(){StatusLog.logMsg('fetch',name);});this.events.register('loadend',this,this.loaded);}
if(otherOptions.featureAdded){this.events.register('featureadded',this,otherOptions.featureAdded);}},loaded:function(event){StatusLog.logMsg('loaded',event.object.name);this.map.featureExtent.extend(this.getDataExtent());this.map.feedsRead++;this.map.inputDone();},getTemplate:function(feature){var atts=feature.attributes;var featureId=this.protocol.entries?this.protocol.entries[feature.fid].link[0].href.substr(this.protocol.entries[feature.fid].link[0].href.lastIndexOf('/')+1):feature.fid;var template='<i>featureId</i>: '+featureId;for(var att in atts){if(atts[att]!=''){if(atts[att].substring(0,7)=='http://'){template+='<br /><i>'+att+'</i>: <a target="linktab" href="'+atts[att]+'">'+atts[att]+'</a>';}
else{template+='<br /><i>'+att+'</i>: '+atts[att];}}}
if(feature.geometry.CLASS_NAME=="OpenLayers.Geometry.LineString"){template+='<br />'+this.map.getLength(feature)+' (calculated from map)';if(ServerVars.routeProfile){feature.coords=Array();var clone=feature.geometry.clone();if(this.map.projection!="EPSG:4326"){clone.transform(feature.layer.projection,this.map.displayProjection);}
var vertices=clone.getVertices();for(var i=0;i<vertices.length;i++){feature.coords[i]=[vertices[i].y,vertices[i].x];}
template+='<br /><a id="profile" href="#">Show height profile</a>';template+='<div id="profile"></div>';}}
return template;}});Map.Styles={styles:{select:{strokeColor:"red",fillColor:"red"}},filters:{type_ne_null:{type:OpenLayers.Filter.Comparison.NOT_EQUAL_TO,property:"type",value:null}},rules:{elseFilter:{elseFilter:true}},createStyleMap:function(defaultStyle,rulesArray,poiStyleWanted){if(typeof defaultStyle=="string"){defaultStyle=this.styles[defaultStyle];}
if(poiStyleWanted){OpenLayers.Util.extend(defaultStyle,this.styles.poi);}
var sty=OpenLayers.Util.applyDefaults(defaultStyle,OpenLayers.Feature.Vector.style["default"]);var sm=new OpenLayers.StyleMap({'default':sty,'select':this.styles.select});if(rulesArray){var rules=Array();var mvr=this.rules;for(i=0;i<rulesArray.length;i++){var ruleParams={};if(mvr[rulesArray[i]].filter){ruleParams.filter=new OpenLayers.Filter.Comparison(this.filters[mvr[rulesArray[i]].filter]);}
if(mvr[rulesArray[i]].elseFilter){ruleParams.elseFilter=true;}
if(mvr[rulesArray[i]].minScaleDenominator){ruleParams.minScaleDenominator=mvr[rulesArray[i]].minScaleDenominator;}
if(mvr[rulesArray[i]].symbolizer){ruleParams.symbolizer=this.styles[mvr[rulesArray[i]].symbolizer];}
var rule=new OpenLayers.Rule(ruleParams);rules.push(rule);}
sm.styles['default'].addRules(rules);}
return sm;}};Dialogs.setups.feature=function(){Dialogs.divs.feature='<div id="feature" title="Feature details" style="font-size: 10px"></div>';Dialogs.params.feature={position:'top',autoOpen:false};Dialogs.setup('feature');};Dialogs.setups.wiki=function(){Dialogs.divs.wiki='<div id="wiki" title="Wiki Entry"></div>';Dialogs.params.wiki={position:'top',width:600,maxHeight:300,autoOpen:false};Dialogs.functions.wiki=function(){appendCSS('#p-logo, .generated-sidebar, #p-lang, #p-tb, #p-search, #p-cactions, #p-personal, #footer {display:none;} #mw_content {margin: 0 0 .6em 0;}');};Dialogs.setup('wiki');};Map.Controls.selects={feature:function(feature){if(feature.attributes.clickable=='off'){return;}
if(feature.attributes.wiki){Dialogs.urls.wiki=ServerVars.wiki+feature.attributes.wiki+'?printable=yes';Dialogs.open('wiki',true);}else{var html=feature.layer.getTemplate(feature);jQuery('#feature').html(html);jQuery('#feature').dialog('open');jQuery('#profile').click(jQuery.proxy(function(){topoDrawGraph($('profile'),this.coords,600,250);return false;},feature));}}};;Map.Styles.styles.places={strokeColor:"white",strokeOpacity:"1",strokeWidth:3,fillColor:"white",pointRadius:1};Map.getPlacesLayerOptions=function(corrs){return{strategyTypes:['Fixed'],type:'FS',fsFile:corrs=='nocorrs'?"places?corronly__ne=y":"places",featureAdded:function(e){e.feature.attributes.clickable='off';},defaultStyle:'places',passThrough:{maxResolution:this.map.resolutions[1]}};};Dialogs.setups.route=function(){Dialogs.divs.route='<div id="route" title="Route details"></div>';Dialogs.params.route={maxHeight:300,width:500,position:'top',autoOpen:false};Dialogs.setup('route');}
Map.Controls.selects.route=function(feature){if(feature.attributes.clickable=='off')
return;Dialogs.urls.route=ServerVars['detailsUrl'].replace('ID',feature.attributes.route)+' #content';Dialogs.open('route',true);};OpenLayers.Layer.TileCache=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:true,format:'image/png',serverResolutions:null,initialize:function(name,url,layername,options){this.layername=layername;OpenLayers.Layer.Grid.prototype.initialize.apply(this,[name,url,{},options]);this.extension=this.format.split('/')[1].toLowerCase();this.extension=(this.extension=='jpg')?'jpeg':this.extension;},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.TileCache(this.name,this.url,this.layername,this.getOptions());}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);return obj;},getURL:function(bounds){var res=this.getServerResolution();var bbox=this.maxExtent;var size=this.tileSize;var tileX=Math.round((bounds.left-bbox.left)/(res*size.w));var tileY=Math.round((bounds.bottom-bbox.bottom)/(res*size.h));var tileZ=this.serverResolutions!=null?OpenLayers.Util.indexOf(this.serverResolutions,res):this.map.getZoom();function zeroPad(number,length){number=String(number);var zeros=[];for(var i=0;i<length;++i){zeros.push('0');}
return zeros.join('').substring(0,length-number.length)+number;}
var components=[this.layername,zeroPad(tileZ,2),zeroPad(parseInt(tileX/1000000),3),zeroPad((parseInt(tileX/1000)%1000),3),zeroPad((parseInt(tileX)%1000),3),zeroPad(parseInt(tileY/1000000),3),zeroPad((parseInt(tileY/1000)%1000),3),zeroPad((parseInt(tileY)%1000),3)+'.'+this.extension];var path=components.join('/');var url=this.url;if(OpenLayers.Util.isArray(url)){url=this.selectUrl(path,url);}
url=(url.charAt(url.length-1)=='/')?url:url+'/';return url+path;},CLASS_NAME:"OpenLayers.Layer.TileCache"});;Map.addTc=function(tcLayer){var tc=new OpenLayers.Layer.TileCache("Route lines",(window.location.hostname=="localhost"?"/test":"")+"/tilecache/",tcLayer,{buffer:0,isBaseLayer:false,tileSize:new OpenLayers.Size(200,200)});if(tcLayer=='europeOverview')
tc.maxExtent=new OpenLayers.Bounds(-11,35,30,70);tc.attribution='Lines: see <a href="http://pilgrim.peterrobins.co.uk/routes/mapping.html">separate page</a>';this.map.addLayer(tc);OpenLayers.Util.onImageLoadError=function(){};};Map.specifics={controls:['bbox'],vectorControls:['selectFeature'],mapOptions:{feedCount:1,zoomToFeatures:true},layerOptions:{'Clickable routes':{type:'FS',includeInInitialZoom:true,strategyTypes:['Fixed'],displayInLayerSwitcher:false,fsFile:"overviewlines",defaultStyle:{strokeOpacity:"0",strokeWidth:3,cursor:"pointer"}}},selectFeature:{selectFunction:'route',dialog:'route'},addTc:ServerVars['layer'],setupVectorOptions:function(){this.layerOptions['Clickable routes'].fsFile+=ServerVars['bbox']?'?bbox='+ServerVars['bbox']:'';if(this.addTc=='europeOverview'||this.addTc=='europe3035Overview'||this.addTc=='climaOverview')
this.placesLayer='nocorrs';if(this.addTc!='climaOverview')
this.switcher=true;Dialogs.divs.boundsConfirm='<div id="boundsConfirm" title="Confirm zoom to bounds" style="font-size: 10px">';Dialogs.onOk=function(){var slected=jQuery('[name=mapbase]:checked').val();window.location=ServerVars['serverPath']+'/'+slected+'/bbox.html?bbox='+$('bounds').innerHTML;};Dialogs.params.boundsConfirm={buttons:{"Ok":Dialogs.onOk},width:400,maxHeight:300,autoOpen:false};Dialogs.setup('boundsConfirm');jQuery('#boundsConfirm').load(ServerVars.serverPath+'/boundsConfirm.html');},getBboxControl:function(){var control=new OpenLayers.Control();OpenLayers.Util.extend(control,{draw:function(){this.box=new OpenLayers.Handler.Box(control,{"done":this.notice},{keyMask:OpenLayers.Handler.MOD_SHIFT});this.box.activate();},notice:function(bounds){var ll=this.map.getLonLatFromPixel({x:bounds.left,y:bounds.bottom});var ur=this.map.getLonLatFromPixel({x:bounds.right,y:bounds.top});var boundString=ll.lon+','+ll.lat+','+ur.lon+','+ur.lat;$('bounds').innerHTML=boundString;jQuery('#boundsConfirm').dialog('open');}});return control}}
