jQuery.ui||(function(c){var i=c.fn.remove,d=c.browser.mozilla&&(parseFloat(c.browser.version)<1.9);c.ui={version:"1.7.1",plugin:{add:function(k,l,n){var m=c.ui[k].prototype;for(var j in n){m.plugins[j]=m.plugins[j]||[];m.plugins[j].push([l,n[j]])}},call:function(j,l,k){var n=j.plugins[l];if(!n||!j.element[0].parentNode){return}for(var m=0;m<n.length;m++){if(j.options[n[m][0]]){n[m][1].apply(j.element,k)}}}},contains:function(k,j){return document.compareDocumentPosition?k.compareDocumentPosition(j)&16:k!==j&&k.contains(j)},hasScroll:function(m,k){if(c(m).css("overflow")=="hidden"){return false}var j=(k&&k=="left")?"scrollLeft":"scrollTop",l=false;if(m[j]>0){return true}m[j]=1;l=(m[j]>0);m[j]=0;return l},isOverAxis:function(k,j,l){return(k>j)&&(k<(j+l))},isOver:function(o,k,n,m,j,l){return c.ui.isOverAxis(o,n,j)&&c.ui.isOverAxis(k,m,l)},keyCode:{BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38}};if(d){var f=c.attr,e=c.fn.removeAttr,h="http://www.w3.org/2005/07/aaa",a=/^aria-/,b=/^wairole:/;c.attr=function(k,j,l){var m=l!==undefined;return(j=="role"?(m?f.call(this,k,j,"wairole:"+l):(f.apply(this,arguments)||"").replace(b,"")):(a.test(j)?(m?k.setAttributeNS(h,j.replace(a,"aaa:"),l):f.call(this,k,j.replace(a,"aaa:"))):f.apply(this,arguments)))};c.fn.removeAttr=function(j){return(a.test(j)?this.each(function(){this.removeAttributeNS(h,j.replace(a,""))}):e.call(this,j))}}c.fn.extend({remove:function(){c("*",this).add(this).each(function(){c(this).triggerHandler("remove")});return i.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","").unbind("selectstart.ui")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return false})},scrollParent:function(){var j;if((c.browser.msie&&(/(static|relative)/).test(this.css("position")))||(/absolute/).test(this.css("position"))){j=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test(c.curCSS(this,"position",1))&&(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}else{j=this.parents().filter(function(){return(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}return(/fixed/).test(this.css("position"))||!j.length?c(document):j}});c.extend(c.expr[":"],{data:function(l,k,j){return!!c.data(l,j[3])},focusable:function(k){var l=k.nodeName.toLowerCase(),j=c.attr(k,"tabindex");return(/input|select|textarea|button|object/.test(l)?!k.disabled:"a"==l||"area"==l?k.href||!isNaN(j):!isNaN(j))&&!c(k)["area"==l?"parents":"closest"](":hidden").length},tabbable:function(k){var j=c.attr(k,"tabindex");return(isNaN(j)||j>=0)&&c(k).is(":focusable")}});function g(m,n,o,l){function k(q){var p=c[m][n][q]||[];return(typeof p=="string"?p.split(/,?\s+/):p)}var j=k("getter");if(l.length==1&&typeof l[0]=="string"){j=j.concat(k("getterSetter"))}return(c.inArray(o,j)!=-1)}c.widget=function(k,j){var l=k.split(".")[0];k=k.split(".")[1];c.fn[k]=function(p){var n=(typeof p=="string"),o=Array.prototype.slice.call(arguments,1);if(n&&p.substring(0,1)=="_"){return this}if(n&&g(l,k,p,o)){var m=c.data(this[0],k);return(m?m[p].apply(m,o):undefined)}return this.each(function(){var q=c.data(this,k);(!q&&!n&&c.data(this,k,new c[l][k](this,p))._init());(q&&n&&c.isFunction(q[p])&&q[p].apply(q,o))})};c[l]=c[l]||{};c[l][k]=function(o,n){var m=this;this.namespace=l;this.widgetName=k;this.widgetEventPrefix=c[l][k].eventPrefix||k;this.widgetBaseClass=l+"-"+k;this.options=c.extend({},c.widget.defaults,c[l][k].defaults,c.metadata&&c.metadata.get(o)[k],n);this.element=c(o).bind("setData."+k,function(q,p,r){if(q.target==o){return m._setData(p,r)}}).bind("getData."+k,function(q,p){if(q.target==o){return m._getData(p)}}).bind("remove",function(){return m.destroy()})};c[l][k].prototype=c.extend({},c.widget.prototype,j);c[l][k].getterSetter="option"};c.widget.prototype={_init:function(){},destroy:function(){this.element.removeData(this.widgetName).removeClass(this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").removeAttr("aria-disabled")},option:function(l,m){var k=l,j=this;if(typeof l=="string"){if(m===undefined){return this._getData(l)}k={};k[l]=m}c.each(k,function(n,o){j._setData(n,o)})},_getData:function(j){return this.options[j]},_setData:function(j,k){this.options[j]=k;if(j=="disabled"){this.element[k?"addClass":"removeClass"](this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").attr("aria-disabled",k)}},enable:function(){this._setData("disabled",false)},disable:function(){this._setData("disabled",true)},_trigger:function(l,m,n){var p=this.options[l],j=(l==this.widgetEventPrefix?l:this.widgetEventPrefix+l);m=c.Event(m);m.type=j;if(m.originalEvent){for(var k=c.event.props.length,o;k;){o=c.event.props[--k];m[o]=m.originalEvent[o]}}this.element.trigger(m,n);return!(c.isFunction(p)&&p.call(this.element[0],m,n)===false||m.isDefaultPrevented())}};c.widget.defaults={disabled:false};c.ui.mouse={_mouseInit:function(){var j=this;this.element.bind("mousedown."+this.widgetName,function(k){return j._mouseDown(k)}).bind("click."+this.widgetName,function(k){if(j._preventClickEvent){j._preventClickEvent=false;k.stopImmediatePropagation();return false}});if(c.browser.msie){this._mouseUnselectable=this.element.attr("unselectable");this.element.attr("unselectable","on")}this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);(c.browser.msie&&this.element.attr("unselectable",this._mouseUnselectable))},_mouseDown:function(l){l.originalEvent=l.originalEvent||{};if(l.originalEvent.mouseHandled){return}(this._mouseStarted&&this._mouseUp(l));this._mouseDownEvent=l;var k=this,m=(l.which==1),j=(typeof this.options.cancel=="string"?c(l.target).parents().add(l.target).filter(this.options.cancel).length:false);if(!m||j||!this._mouseCapture(l)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){k.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(l)&&this._mouseDelayMet(l)){this._mouseStarted=(this._mouseStart(l)!==false);if(!this._mouseStarted){l.preventDefault();return true}}this._mouseMoveDelegate=function(n){return k._mouseMove(n)};this._mouseUpDelegate=function(n){return k._mouseUp(n)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);(c.browser.safari||l.preventDefault());l.originalEvent.mouseHandled=true;return true},_mouseMove:function(j){if(c.browser.msie&&!j.button){return this._mouseUp(j)}if(this._mouseStarted){this._mouseDrag(j);return j.preventDefault()}if(this._mouseDistanceMet(j)&&this._mouseDelayMet(j)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,j)!==false);(this._mouseStarted?this._mouseDrag(j):this._mouseUp(j))}return!this._mouseStarted},_mouseUp:function(j){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=(j.target==this._mouseDownEvent.target);this._mouseStop(j)}return false},_mouseDistanceMet:function(j){return(Math.max(Math.abs(this._mouseDownEvent.pageX-j.pageX),Math.abs(this._mouseDownEvent.pageY-j.pageY))>=this.options.distance)},_mouseDelayMet:function(j){return this.mouseDelayMet},_mouseStart:function(j){},_mouseDrag:function(j){},_mouseStop:function(j){},_mouseCapture:function(j){return true}};c.ui.mouse.defaults={cancel:null,distance:1,delay:0}})(jQuery);;Ext.namespace('mapfish.widgets');mapfish.widgets.MapComponent=function(config){Ext.apply(this,config);this.contentEl=this.map.div;var content=Ext.get(this.contentEl);content.setStyle('width','100%');content.setStyle('height','100%');mapfish.widgets.MapComponent.superclass.constructor.call(this);};Ext.extend(mapfish.widgets.MapComponent,Ext.Panel,{map:null,initComponent:function(){mapfish.widgets.MapComponent.superclass.initComponent.apply(this,arguments);this.on("bodyresize",this.map.updateSize,this.map);}});Ext.reg('mapcomponent',mapfish.widgets.MapComponent);Ext.namespace('mapfish.widgets.toolbar');mapfish.widgets.toolbar.Toolbar=function(config){Ext.apply(this,config);mapfish.widgets.toolbar.Toolbar.superclass.constructor.call(this);};Ext.extend(mapfish.widgets.toolbar.Toolbar,Ext.Toolbar,{controls:null,state:null,configurable:false,_buttons:null,initComponent:function(){mapfish.widgets.toolbar.Toolbar.superclass.initComponent.call(this);this.controls=[];this._buttons=[];this.autoWidth=true;this.autoHeight=true;Ext.QuickTips.init();},addControl:function(control,options){control.visible=true;this.controls.push(control);this.map.addControl(control);var button=new Ext.Toolbar.Button(options);if(!button.tooltip){button.tooltip=control.title;}
button.enableToggle=(control.type!=OpenLayers.Control.TYPE_BUTTON);if(control.isDefault){button.pressed=true;}
if(control.type==OpenLayers.Control.TYPE_BUTTON){button.on("click",control.trigger,control);}else{button.on("toggle",function(button,pressed){this.toggleHandler(control,pressed);},this);var self=this;control.events.on({"activate":function(){button.toggle(true);},"deactivate":function(){button.toggle(false);self.checkDefaultControl(button,control);}});}
this.add(button);this._buttons.push(button);return button;},getControlByClassName:function(className){if(this.controls){for(var i=0;i<this.controls.length;i++){if(this.controls[i].CLASS_NAME==className){return this.controls[i];}}}
return null;},getButtonForControl:function(control){if(this.controls){for(var i=0;i<this.controls.length;i++){if(this.controls[i]==control){return this._buttons[i];}}}
return null;},activate:function(){if(this.configurable){this.applyState(this.state);var mb=new Ext.Toolbar.Button({'text':'+'});mb.menu=new Ext.menu.Menu();for(var i=0;i<this.controls.length;i++){mb.menu.add({'style':'height:25px','text':'<div style="position: relative; left: 25px; top: -15px;" class="'+this._buttons[i].iconCls+'"/>',checked:this.controls[i].visible,scope:{toolbar:this,button:this._buttons[i],control:this.controls[i]},checkHandler:function(item,checked){if(checked){this.control.visible=true;if(this.control.isDefault){this.control.activate();}
this.button.show();}else{this.control.visible=false;this.control.deactivate();this.button.hide();}
this.toolbar.saveState();}});}
this.add(mb);}else{for(var j=0,c;j<this.controls.length;j++){c=this.controls[j];if(c.isDefault){c.activate();}}}},deactivate:function(){for(var i=0;i<this.controls.length;i++){this.controls[i].deactivate();}},applyState:function(state){if(!state){return false;}
this.state=state;var cs=state.controls;if(cs){for(var i=0,len=cs.length;i<len;i++){var s=cs[i];var c=this.getControlByClassName(s.id);if(c){c.visible=s.visible;if(!c.visible){this._buttons[i].hide();}}}}},getState:function(){var o={controls:[]};for(var i=0,c;i<this.controls.length;i++){c=this.controls[i];o.controls[i]={id:c.CLASS_NAME,visible:c.visible};}
return o;},toggleHandler:function(control,pressed){if(pressed!=control.active){if(pressed){control.activate();}else{control.deactivate();}}},checkDefaultControl:function(button,control){var group=button.toggleGroup;if(group){var defaultControl=null;for(var j=0;j<this.controls.length;j++){var curButton=this._buttons[j];if(curButton.toggleGroup==group){var control=this.controls[j];if(control.active){return;}else if(control.isDefault){defaultControl=control;}}}
if(defaultControl){defaultControl.activate();}}}});Ext.reg('toolbar',mapfish.widgets.toolbar.Toolbar);Ext.namespace('MarineMap');MarineMap.config={adminEmail:'admin@marinemap.org',identifyBboxRadius:500,projection:new OpenLayers.Projection("EPSG:900913"),displayProjection:new OpenLayers.Projection("EPSG:4326"),equalAreaProjection:new OpenLayers.Projection("EPSG:3310")};Ext.Ajax.timeout=120000;Ext.grid.SmartCheckboxSelectionModel=Ext.extend(Ext.grid.RowSelectionModel,{header:'<div id="x-grid3-hd-checker" class="x-grid3-hd-checker"> </div>',width:20,sortable:false,email:false,excel:true,alwaysSelectOnCheck:false,menuDisabled:true,fixed:true,id:'checker',dataIndex:'',initEvents:function(){Ext.grid.SmartCheckboxSelectionModel.superclass.initEvents.call(this);this.grid.on('render',function(){var view=this.grid.getView();view.on('columnmove',this.onColumnMove,this);view.mainBody.on('mousedown',this.onMouseDown,this);Ext.fly(view.innerHd).on('mousedown',this.onHdMouseDown,this);},this);this.rowNav.disable();this.rowNav2=new Ext.KeyNav(this.grid.getGridEl(),{"up":function(e){if(!e.shiftKey){if(!this.email){this.selectPreviousChecked(e.shiftKey);}
if(this.email){this.selectPrevious(e.shiftKey);}}
else if(this.last!==false&&this.lastActive!==false){var last=this.last;if(!this.email){this.selectRangeChecked(this.last,this.lastActive-1);}
if(this.email){this.selectRange(this.last,this.lastActive-1);}
this.grid.getView().focusRow(this.lastActive);if(last!==false){this.last=last;}}
else{this.selectFirstRow();if(!this.email){this.toggleChecked(0,true);}}},"down":function(e){if(!e.shiftKey){if(!this.email){this.selectNextChecked(e.shiftKey);}
if(this.email){this.selectNext(e.shiftKey);}}
else if(this.last!==false&&this.lastActive!==false){var last=this.last;if(!this.email){this.selectRangeChecked(this.last,this.lastActive+1);}
if(this.email){this.selectRange(this.last,this.lastActive+1);}
this.grid.getView().focusRow(this.lastActive,true);if(last!==false){this.last=last;}}
else{this.selectFirstRow();if(!this.email){this.toggleChecked(0,true);}}},scope:this});this.grid.on('columnmove',function(p){var t=Ext.get('x-grid3-hd-checker');if(t!=null){if(t.dom.className!='x-grid3-hd-checker'){Ext.fly(t.dom.parentNode).removeClass('x-grid3-hd-checker');}}});if(this.grid.store){this.grid.store.on('load',function(p){var t=Ext.get('x-grid3-hd-checker');if(t!=null){if(t.dom.className=='x-grid3-hd-checker'&&Ext.state.Manager.loaded){var hd=Ext.fly(t.dom.parentNode);var isChecked=hd.hasClass('x-grid3-hd-checker-on');if(isChecked){hd.addClass('x-grid3-hd-checker-on');if(!this.email){this.selectAll();}
this.selectAllChecked(true);}}
else{Ext.fly(t.dom.parentNode).removeClass('x-grid3-hd-checker');}}
var dataIndex=this.grid.getSelectionModel().dataIndex;var count=this.grid.store.getCount();for(var i=0,len=count;i<len;i++){var dataIndexValue=p.data.items[i].data[dataIndex];var isSelected=this.isSelected(i);if((dataIndexValue==true||isSelected)&&!Ext.state.Manager.loaded){if(!this.email||this.alwaysSelectOnCheck){this.grid.getSelectionModel().selectRow(i,true);}}
else if(isSelected){if(!this.email){this.toggleChecked(i,true);}}
else{if(!this.email){this.toggleChecked(i,false);}}}},this);}},toggleChecked:function(rowIndex,c){if(this.locked)return;var record=this.grid.store.getAt(rowIndex);if(c===true){record.set(this.dataIndex,true);}
else if(c===false){record.set(this.dataIndex,false);}
else{record.set(this.dataIndex,!record.data[this.dataIndex]);}
if(this.onToggle){this.onToggle(this,rowIndex,c);}},selectAllChecked:function(c,e){if(this.locked)return;var count=this.grid.store.getCount();for(var i=0,len=count;i<len;i++){if(c){if(i!==e){this.toggleChecked(i,true);}}
else{if(i!==e){this.toggleChecked(i,false);}}}},clearChecked:function(fast){if(this.locked)return;if(fast!==true){var count=this.grid.store.getCount();for(var i=0,len=count;i<len;i++){var isSelected=this.isSelected(i);if(!isSelected){this.toggleChecked(i,false);}}}
else{this.selectAllChecked(false);}
this.last=false;},selectRangeChecked:function(startRow,endRow,keepExisting){if(this.locked)return;if(!keepExisting){if(!this.email||this.alwaysSelectOnCheck){this.clearSelections();}
this.clearChecked();}
if(startRow<=endRow){for(var i=startRow;i<=endRow;i++){if(this.grid.store.getAt(i)){this.toggleChecked(i,true);if(!this.email||this.alwaysSelectOnCheck){this.selectRow(i,true);}}}}
else{for(var i=startRow;i>=endRow;i--){if(this.grid.store.getAt(i)){this.toggleChecked(i,true);if(!this.email||this.alwaysSelectOnCheck){this.selectRow(i,true);}}}}},selectPreviousChecked:function(keepExisting){if(this.hasPrevious()){this.selectRow(this.last-1,keepExisting);this.grid.getView().focusRow(this.last);if(!this.email){this.toggleChecked(this.last,true);this.selectAllChecked(false,this.last);}
return true;}
return false;},selectNextChecked:function(keepExisting){if(this.hasNext()){if(!this.email){this.selectRow(this.last+1,keepExisting);}
this.grid.getView().focusRow(this.last);if(!this.email){this.toggleChecked(this.last,true);this.selectAllChecked(false,this.last);}
return true;}
return false;},handleMouseDown:function(g,rowIndex,e){var t=e.getTarget('.ux-row-action-item');if(!t){if(e.button!==0||this.isLocked()){return;};var view=this.grid.getView();var record=this.grid.store.getAt(rowIndex);if(e.shiftKey&&this.last!==false){var last=this.last;this.selectRange(last,rowIndex,e.ctrlKey);if(!this.email){this.selectRangeChecked(last,rowIndex,e.ctrlKey);}
this.last=last;view.focusRow(rowIndex);}else{var isChecked=record.data[this.dataIndex];var isSelected=this.isSelected(rowIndex);if(isSelected){this.deselectRow(rowIndex);if(!this.email){this.toggleChecked(rowIndex,false);}}else{if(!this.excel){this.selectRow(rowIndex,true);if(!this.email){this.toggleChecked(rowIndex,true);}}
else{this.selectRow(rowIndex,e.ctrlKey);if(!this.email){this.selectRangeChecked(rowIndex,rowIndex,e.ctrlKey);}}
view.focusRow(rowIndex);}}}},onMouseDown:function(e,t){if(t.className&&t.className.indexOf('x-grid3-cc-'+this.id)!=-1){e.stopEvent();var view=this.grid.getView();var rowIndex=view.findRowIndex(t);var record=this.grid.store.getAt(rowIndex);var isSelected=this.isSelected(rowIndex);var isChecked=record.data[this.dataIndex];if(!this.email||this.alwaysSelectOnCheck){if(isSelected){if(!isChecked&&this.alwaysSelectOnCheck){this.toggleChecked(rowIndex,true);}
else{this.deselectRow(rowIndex);this.toggleChecked(rowIndex,false);}}
else{this.selectRow(rowIndex,true);this.toggleChecked(rowIndex,true);view.focusRow(rowIndex);}}
else{if(isChecked){this.toggleChecked(rowIndex,false);}
else{this.toggleChecked(rowIndex,true);}}
view.focusRow(rowIndex);}
Ext.state.Manager.setProvider(new Ext.state.CookieProvider());Ext.state.Manager.loaded=true;},onHdMouseDown:function(e,t){if(t.className=='x-grid3-hd-checker'){e.stopEvent();var hd=Ext.fly(t.parentNode);var isChecked=hd.hasClass('x-grid3-hd-checker-on');if(isChecked){hd.removeClass('x-grid3-hd-checker-on');if(!this.email||this.alwaysSelectOnCheck){this.clearSelections();}
this.clearChecked(true);}else{hd.addClass('x-grid3-hd-checker-on');if(!this.email||this.alwaysSelectOnCheck){this.selectAll();}
this.selectAllChecked(true);}}
Ext.state.Manager.setProvider(new Ext.state.CookieProvider());Ext.state.Manager.loaded=true;},renderer:function(v,p,record){p.css+=' x-grid3-check-col-td';return'<div class="x-grid3-check-col'+(v?'-on':'')+' x-grid3-cc-'+this.id+'"> </div>';}});Ext.namespace('MarineMap','MarineMap.data');MarineMap.data.StudyRegion=Ext.data.Record.create([{name:'name'},{name:'bounds'}]);MarineMap.data.StudyRegion.prototype.extent=function(){return OpenLayers.Bounds.fromString(this.data.bounds);};Ext.namespace('MarineMap','MarineMap.data');var NAME=0;var GROUP=1;var LAYER=2;var LEGEND=3;var DESC=4;var META=5;var DEFAULT_ON=6;MarineMap.data.MIN_ZOOM_LEVEL=7;MarineMap.data.MAX_ZOOM_LEVEL=18;MarineMap.data.TERRAIN_MAX_ZOOM_LEVEL=15;var getLegendParams={service:"WMS",version:"1.1.1",request:"GetLegendGraphic",exceptions:"application/vnd.ogc.se_inimage",format:"image/png"};MarineMap.data.GoogleTerrain=new OpenLayers.Layer.Google("Google Terrain",{type:G_PHYSICAL_MAP,'sphericalMercator':true,MIN_ZOOM_LEVEL:MarineMap.data.MIN_ZOOM_LEVEL,MAX_ZOOM_LEVEL:MarineMap.data.MAX_ZOOM_LEVEL,projection:new OpenLayers.Projection("EPSG:900913")});MarineMap.data.GoogleSat=new OpenLayers.Layer.Google("Satellite/Aerial Imagery",{type:G_SATELLITE_MAP,'sphericalMercator':true,MIN_ZOOM_LEVEL:MarineMap.data.MIN_ZOOM_LEVEL,MAX_ZOOM_LEVEL:MarineMap.data.MAX_ZOOM_LEVEL,projection:new OpenLayers.Projection("EPSG:900913")});MarineMap.data.DataLayers=[['Satellite/Aerial Imagery','Base',MarineMap.data.GoogleSat,'/marinemap/media/js/openlayers/img/blank.gif','Google satellite/aerial imagery','Insert link here'],['Bathymetry','Base',new OpenLayers.Layer.TMS("Bathymetry",["http://d3k3467ak9pvw9.cloudfront.net/Bathymetry/"],{layer_id:1,layername:'Bathymetry',buffer:1,'isBaseLayer':false,'opacity':0.75,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://d3k3467ak9pvw9.cloudfront.net/Bathymetry/Legend.png','Bathymetric Shaded Relief','Resolution is 200 meters. The original grid file was made from 75 original tiled DEMs that were mosaicked into one grid and resampled to 200 meters.  These mosaicked DEMs were produced by Teale Data Center from a contract with the Department of Fish and Game, funded by the Resources Agency.'],['Nautical Charts','Base',new OpenLayers.Layer.TMS("Nautical Charts",["http://d3k3467ak9pvw9.cloudfront.net/Charts/"],{layer_id:2,layername:'Charts',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://d3k3467ak9pvw9.cloudfront.net/Charts/Legend.png','NOAA Nautical Charts','Scanned and georeferenced NOAA nautical charts at varying resolutions.'],['Study Region','Base',new OpenLayers.Layer.TMS("Study Region",["http://marinemap.org/tiles/StudyRegion/"],{layer_id:3,layername:'StudyRegion',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=7){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/StudyRegion/Legend.png','MLPA Initiative South Coast Study Region','Study region boundary for the Marine Life Protection Act (MLPA) South Coast Study Region. The South Coast Study Region is broken into 7 subregions which are intended to represent logical biogeographic subunits.',true],['Graticules','Base',new OpenLayers.Layer.TMS("Graticules",["http://marinemap.org/tiles/Graticules/"],{layer_id:4,layername:'Graticules',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=7){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/Graticules/Legend.png','Graticules at 10, 5 and 1 minute','No Metadata'],['Coastal Energy','Management',new OpenLayers.Layer.TMS("Coastal Energy",["http://marinemap.org/tiles/CoastalEnergy/"],{layer_id:5,layername:'CoastalEnergy',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/CoastalEnergy/Legend.png','Coastal Energy','Active desalination facilities on the California coast as of 2008. Locations were provided by  California Department of Fish and Game.The power plant data layer for the power plants located in the south coast study region. The information provided by the California Energy Commission under strict usage guidelines. For cartographic display only. The oil platforms data layer represents locations of oil platforms offshore of California. Developed for Department of Fish and Game, Office of Spill Prevention and Response. November 20, 2002.'],['Recreational Fishing','Consumptive',new OpenLayers.Layer.TMS("Recreational Fishing",["http://marinemap.org/tiles/RecreationalFishing/"],{layer_id:6,layername:'RecreationalFishing',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/RecreationalFishing/Legend.png','Recreational Fishing','The kayak launch sites data layer depicts point locations as identified by Kayak Fishing Association of California based on survey results.  The information was collected in 2008. The spearfishing competition sites data layer depicts specific dive sites along the California coast as used by the Central California Diving Council (CenCal) for freedive spearfishing competitions. These data are a subset of fishing locations compiled by David VenTresca, California Department of Fish and Game.The fishing piers and jetties data layer is all public piers and jetties used by California Recreational Fisheries Survey (CRFS), as identified by Pacific States Marine Fisheries Commission between 2007 to 2008. The kayak fishing areas data layer demarcates areas identified by Kayak Fishing Association of California based on survey results.  The information was collected in 2008.'],['Coastal Access and Recreation','Non-Consumptive Use',new OpenLayers.Layer.TMS("Coastal Access and Recreation",["http://marinemap.org/tiles/CoastalAccessRecreation/"],{layer_id:7,layername:'CoastalAccessRecreation',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/CoastalAccessRecreation/Legend.png','Coastal Access and Recreation','The boat launch sites dataset represents Table 5.9-9 in the MLPA South Coast Study Region Regional Profile.  Locations were researched on the Internet and placed accordingly by DFGs Marine Region GIS Lab.  The shore dive sites data layer depicts shore diving locations for Southern California from <a href="http://www.shorediving.com/Earth/USA_West/CalS/index.htm" target="_blank">here</a>. The kayak launch sites data layer depicts point locations as identified by Kayak Fishing Association of California based on survey results.  The information was collected in 2008.  The coastal access points data layer shows the locations and facilities of the beach access points and coastal features of interest documented by the California Coastal Access Guide, which was published in 2002. The harbors data layer  is a subset of place names from a California statewide extract features from the USGS Geographic Names Information System (GNIS), provided by USGS GNIS staff, dated January 2006 The ports data layer identifies 194 marine and inland port locations used by marine fisheries for the landing and sale of fish and invertebrates. The data layer was created by the California Department of Fish and Game in 2001.'],['Research and Monitoring','Management',new OpenLayers.Layer.TMS("Coastal Access and Recreation",["http://marinemap.org/tiles/ResearchMonitoring/"],{layer_id:8,layername:'ResearchMonitoring',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/ResearchMonitoring/Legend.png','Research Institutions and Monitoring Locations','The research institutions data layer provides location information (address and lat/long) for the marine research and education institutions in and around the MLPA study region from Point Conception to Pigeon Point. The data was developed by the University of California Santa Barbara in 2006. The marine monitoring sites data layer provides location information for marine monitoring sites in and around the MLPA study region. The data was developed by the University of California Santa Barbara in 2006.Monitoring sites for the Cooperative Research and Assessment of Nearshore Ecosystems (CRANE) survey.  Diver surveys are conducted using PISCO protocols to characterize fish, invertebrate and macroalgal assemblages.'],['Estuaries','Habitat',new OpenLayers.Layer.TMS("Estuaries",["http://marinemap.org/tiles/Estuaries/"],{layer_id:9,layername:'Estuaries',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/Estuaries/Legend.png','Estuaries','The estuaries data layer is from the U.S. Fish and Wildlife Service, National Wetlands Survey, NOAA ESI (2004).'],['Agricultural Impacts to Watersheds','Physical',new OpenLayers.Layer.TMS("Agricultural Impacts to Watersheds",["http://marinemap.org/tiles/CoastalWatershedsImpactAgriculture/"],{layer_id:10,layername:'CoastalWatershedsImpactAgriculture',buffer:1,'isBaseLayer':false,'opacity':0.9,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/CoastalWatershedsImpactAgriculture/Legend.png','Agricultural Impacts to Coastal Watersheds','Shows the presence of Agricultural Areas provided by National Oceanic and Atmospheric Administration (NOAA). The Agricultural Impact on Coastal Watersheds layer shows the percentage of urban areas within major watersheds. It has been created by performing a spatial intersection between major watershed (Watershed Map of 1999, Calwater 2.2.1)  and agricultural areas provided by NOAA.'],['Eelgrass','Habitat',new OpenLayers.Layer.TMS("Eelgrass",["http://marinemap.org/tiles/Eelgrass/"],{layer_id:11,layername:'Eelgrasse',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/Eelgrass/Legend.png','Eelgrass','Metadata forthcoming'],['Urban Impacts to Watersheds','Physical',new OpenLayers.Layer.TMS("Urban Impacts to Watersheds",["http://marinemap.org/tiles/CoastalWatershedsImpactUrban/"],{layer_id:12,layername:'CoastalWatershedsImpactUrban',buffer:1,'isBaseLayer':false,'opacity':0.9,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/CoastalWatershedsImpactUrban/Legend.png','Urban Impacts to Coastal Watersheds','The Urban Impact on Coastal Watersheds layer shows the percentage of urban areas within major watersheds. It has been created by performing a spatial intersection between major watershed (Watershed Map of 1999, Calwater 2.2.1) and urban areas provided by National Oceanic and Atmospheric Administration (NOAA). Shows the presence of Urban Areas provided by NOAA.'],['Cowcod Conservation Area','Management',new OpenLayers.Layer.TMS("Cowcod Conservation Area",["http://marinemap.org/tiles/CowcodConservationArea/"],{layer_id:13,layername:'CowcodConservationArea',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/CowcodConservationArea/Legend.png','Cowcod Conservation Area','The cowcod conservation area data layer depicts the Cowcod management boundaries based on California Code Title 14, section 150.06.  California Department of Fish and Game, Marine Region January 2003.'],['Managed Areas','Management',new OpenLayers.Layer.TMS("Managed Areas",["http://marinemap.org/tiles/ExistingMarineandCoastalManagedAreas/"],{layer_id:14,layername:'ExistingMarineandCoastalManagedAreas',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/ExistingMarineandCoastalManagedAreas/Legend.png','Existing Marine and Coastal Managed Areas','The aquaculture layer outlines aquaculture seabed lease locations in California.  The layer does not include any aquaculture activities that take place on land.   Data provided by Tom Moore, California Department of Fish and Game. The kelp bed leases data layer identifies areas of kelp management in the south coast study region. Digitized from existing kelp maps, these maps were produced by the California Department of Fish and Game in 1989. The terrestrial managed areas data layer was developed by the California Resources Agency Legacy Project in 2004 and updated by the Nature Conservancy in March 2005. The Channel Islands National Marine Sanctuary  layer shows the legal boundaries of  this National Marine Sanctuary as defined within the Code of Federal Regulations, at 15 C.F.R. Part 922 and the subparts for each national marine sanctuary.  This data was provided by NOAA / National Marine Sanctuaries Program and published in 2004. These data include all of Californias marine protected areas that do not have associated Department of Fish and Game fishing regulations of 2004. Data was provided b California Department of Fish and Game, Marine Region GIS Lab. Published in 2004.'],['MPAs: Existing State','Management',new OpenLayers.Layer.TMS("MPAs: Existing State",["http://marinemap.org/tiles/ExistingStateMarineProtectedAreas/"],{layer_id:15,layername:'ExistingStateMarineProtectedAreas',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/ExistingStateMarineProtectedAreas/Legend.png','Existing State Marine Protected Areas','Marine Protected Areas in California as of October 31, 2008. Data provided by the California Department of Fish and Game'],['Marine Mammals','Biological',new OpenLayers.Layer.TMS("Marine Mammals",["http://marinemap.org/tiles/MarineMammalHauloutsandRookeries/"],{layer_id:16,layername:'MarineMammalHauloutsandRookeries',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/MarineMammalHauloutsandRookeries/Legend.png','Marine Mammal Haulouts and Rookeries','The Pinniped Rookeries layer  describes the location of rookeries (areas in which the pinnipeds repeatedly haul out and breed), the species found there and the months that species breeds at that rookery. Data is provided by U.S. Department of Commerce NOAA/National Marine Fisheries Service - Southwest Region and published on March 30, 2007.The Pinniped Haulouts layer shows Seal and sea lion haul-out sites in California, including the offshore islands. Data is provided by U.S. Department of Commerce NOAA/National Marine Fisheries Service - Southwest Region and published on March 30, 2007.'],['RCA: Commercial, Non-Trawl','Management',new OpenLayers.Layer.TMS("RCA: Commercial, Non-Trawl",["http://marinemap.org/tiles/RCACommercialNonTrawl/"],{layer_id:17,layername:'RCACommercialNonTrawl',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/RCACommercialNonTrawl/Legend.png','Rockfish Conservation Area: Commercial, Non-Trawl','This layer depicts the non-trawl fishing closures off the California coast as described <a href="http://www.nwr.noaa.gov/Groundfish-Halibut/Groundfish-Fishery-Management/Groundfish-Closed-Areas/Index.cfm" target="_blank">here</a> '],['RCA: Commercial, Trawl','Management',new OpenLayers.Layer.TMS("RCA: Commercial, Trawl",["http://marinemap.org/tiles/RCACommercialTrawl/"],{layer_id:18,layername:'RCACommercialTrawl',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/RCACommercialTrawl/Legend.png','Rockfish Conservation Area: Commercial, Trawl','This layer dipicts year round trawl fishing closures off the California coast as described <a href="http://www.nwr.noaa.gov/Groundfish-Halibut/Groundfish-Fishery-Management/Groundfish-Closed-Areas/Index.cfm" target="_blank">here</a>'],['RCA: Recreational','Management',new OpenLayers.Layer.TMS("RCA: Recreational",["http://marinemap.org/tiles/RCARecreational/"],{layer_id:19,layername:'RCARecreational',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/RCARecreational/Legend.png','Rockfish Conservation Area: Recreational','This layer dipicts the year round recreational fishing closures off the California coast as described <a href="http://www.nwr.noaa.gov/Groundfish-Halibut/Groundfish-Fishery-Management/Groundfish-Closed-Areas/Index.cfm" target="_blank">here</a>'],['Nearshore Habitats','Habitat',new OpenLayers.Layer.TMS("Recreational Fishing",["http://marinemap.org/tiles/Nearshorehabitats/"],{layer_id:20,layername:'Nearshorehabitats',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles//Nearshorehabitats/Legend.png','Nearshore Habitats','The surfgrass data layer shows the distribution of surfgrass along the California coast.  It was derived from aerial surveys that were done by the Mineral Management Service during years 1980 to 1982. The eelgrass data layer shows the eelgrass distribution for the California coast and the data is provided by the Nature Conservancy, Humboldt Atlas, California Department of Fish and Game, and NOAA (2004).'],['Hard and Soft Substrata','Habitat',new OpenLayers.Layer.TMS("Hard and Soft Substrata",["http://marinemap.org/tiles/HardSoftSubstrata/"],{layer_id:21,layername:'HardSoftSubstrata',buffer:1,'isBaseLayer':false,'opacity':0.8,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/HardSoftSubstrata/Legend.png','Hard and Soft Substrata','The shipwrecks layer shows the locations of shipwrecks along the coast of California, including offshore islands.  The data are provided by National Oceanic and Atmospheric Administration (NOAA) as Electronic Navigational Chart (ENC) data.  <a href="http://www.nauticalcharts.noaa.gov/csdl/encdirect_met.html" target="_blank">The full metadata can be downloaded here</a>. The artificial reefs layer shows the locations of artificial reefs along the California coast.  The data were provided by the California Department of Fish and Game. The seafloor substrate data layer depicts benthic substrate types in the form of either hard or soft substrate. These data were developed in 2006 by the Moss Landing Marine Laboratory, but have been revised to include additional areas of hard bottom added by researchers at the University of California-Santa Barbara. The submarine canyon data layer delineates geological seafloor characteristics of the contenental margin of the Unites States West Coast. It is a synthesis of various data sources including side-scan sonar, bottom samples, seismic data, and multibeam bathymetry.  The data was created in 2004 by TerraLogic GIS, Inc., Active Tectonics and Seafloor Mapping Lab, College of Oceanic and Atmospheric Sciences (Oregon State University), Center for Habitat Studies, Moss Landing Marine Laboratories.'],['Predicted Substrate','Habitat',new OpenLayers.Layer.TMS("Predicted Substrate",["http://marinemap.org/tiles/PredictedSubstrate/"],{layer_id:21,layername:'Predicted Substrate',buffer:1,'isBaseLayer':false,'opacity':0.8,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/PredictedSubstrate/Legend.png','Predicted Substrate','Fine-scale substrate data displayed on this map represent a union of data collected by, Seafloor Mapping Lab at California State University Monterey Bay, United States Geological Survey (USGS), Ocean Imaging, and the San Diego Association of Governments (SANDAG). Most datasets included in the fine scale substrate layer are derived from multibeam sonar. Gaps in the fine-scale data exist in the vicinity of all islands as well as along the mainland nearshore area, shallower than approximately 20 meters. Where fine scale data were unavailable at San Nicolas Island, coarse scale data are displayed. Coarse-scale data tends to overestimate abundance of rocky substrate. Where nearshore fine-scale data were unavailable, a linear proxy was created by drawing a line roughly parallel to shore, through nearshore areas where fine-scale data exist. Sections of the line were divided into either "hard" or "soft" categories in each area, depending on the dominant habitat type in that portion of the coast between 0 and 30 meters depth. Additional datasets were referenced where possible, including areas of kelp growth, shoreline habitat types, and Bight 08 reef characterizations. '],['Military Areas','Management',new OpenLayers.Layer.TMS("Military Areas",["http://marinemap.org/tiles/MilitaryAreas/"],{layer_id:22,layername:'Military Areas',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/MilitaryAreas/Legend.png','Military Areas','Data regarding military use areas displayed on this map have been developed in conjuction with representatives from the United States Department of Defense. This information is not comprehensive and does not include all activities occuring in the MLPA South Coast Study Region. This information represents current uses, which may change in the future. Pending military closures displayed on this map are under consideration by the MLPA Blue Ribbon Task Force. Additional information regarding military use areas and pending military closures at San Clemente Island and San Nicolas Island can be found <a href="http://www.dfg.ca.gov/mlpa/pdfs/agenda_040109c3.pdf" target="_blank">here</a>'],['Watersheds','Physical',new OpenLayers.Layer.TMS("Watersheds",["http://marinemap.org/tiles/Watersheds/"],{layer_id:23,layername:'Watersheds',buffer:1,'isBaseLayer':false,'opacity':0.7,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/Watersheds/Legend.png','Watersheds','This hydrography layer shows flowing streams and rivers of California as assembled from data originally published by the U.S. Geological Survey (USGS) in Digital Line Graph (DLG-3) format.  These data were last updated in 1998. The major watersheds data layer depicts the major hydrologic units in the south coast study region.  The information comes from the Calwater data layer and may vary slightly from the major hydrologic units described in the Regional Water Quality Control Boards Basin Plans. Differences exist because the GIS data layer, in some places, used smaller units to provide more detail than the major hydrologic units. This data is an extract from the California Interagency Watershed Map of 1999 (Calwater 2.2.1) for more information visit <a href="http://gis.ca.gov/casil/gis.ca.gov/calwater" target="_blank">here</a>. The impaired rivers data layer depicts coastal rivers of water quality concern in the study region.  The information was developed in 2003 by the State Water Resources Control Board (SWRCB) and Regional Water Quality Control Boards (RWQCB). The impaired water bodies data layer depicts water bodies of water quality concern in coastal watersheds and nearshore areas in the study region.  The information was developed in 2003 by the State Water Resources Control Board (SWRCB) and Regional Water Quality Control Boards (RWQCB).'],['Sea Bird Diversity','Biological',new OpenLayers.Layer.TMS("Sea Bird Diversity",["http://marinemap.org/tiles/AtSeaBirdDiversity/"],{layer_id:24,layername:'AtSeaBirdDiversity',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/AtSeaBirdDiversity/Legend.png','Sea Bird Diversity','This layer is derived from the NOAA/USF&WS seabird colony data base.  The layer shows  approximate location of seabird nesting colonies along the central and northern coast of California, including the SF Bay Area.  Original data is from Carter 1980 and Sowles 2000.  These data were then updated in 2004 with information mostly in Baja California from Wolfe SG 2002 using the same format.'],['Isobaths','Base',new OpenLayers.Layer.TMS("Isobaths",["http://d3k3467ak9pvw9.cloudfront.net/Isobaths/"],{layer_id:25,layername:'Isobaths',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://d3k3467ak9pvw9.cloudfront.net/Isobaths/Legend.png','Isobaths (contours)','No Metadata'],['Shore Types','SAT Analyses',new OpenLayers.Layer.TMS("Shore Types",["http://marinemap.org/tiles/ShoreTypes/"],{layer_id:26,layername:'ShoreTypes',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/ShoreTypes/Legend.png','Shore Types','The Shore Types layer is comprised of  the Environmental Sensitivity Index (ESI) maps for the shoreline of northern California. ESI data characterize coastal environments and wildlife by their sensitivity to spilled oil. The ESI data were collected, mapped, and digitized to provide environmental data for oil spill planning and response. The Clean Water Act with amendments by the Oil Pollution Act of 1990 requires response plans for immediate and effective protection of sensitive resources. The data has been provided by the  National Oceanic and Atmospheric Administration (NOAA), National Ocean Service, Office of Response and Restoration (2004).'],['Water Quality','Physical',new OpenLayers.Layer.TMS("Water Quality",["http://marinemap.org/tiles/WaterQuality/"],{layer_id:27,layername:'WaterQuality',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/WaterQuality/Legend.png','Water Quality',"The power plant entrainment layer was developed by using entrainment estimates and intake volume estimates as outlined in the Clean Water Act Section 316 (b) reports. This area does not define a zone of impact, but rather provides a visual sense of the scale over which larval mortality due to entrainment may be of concern, and the relative sizes of this area due to different pumping rates for different plants. The stormwater data layer provides a rough scale of the possible extent of stormwater impact for each of these major stormwater sites. The estimates of the relative extent of possible toxic impacts are based on a Ballona Creek stormwater toxicity zone study. Developed by the California State Water Resources Control Board in 2004, the municipal wastewater and industrial discharge layer depicts the discharge sites into California’s near-coastal marine waters, but does not include discharges into enclosed bays and estuaries. The SAT determined that the Major dischargers should receive a 0.5 mile buffer zone and the Intermediate discharges should receive a 0.25 mile buffer zone to act as a typical or average extent of impacted area from the discharger’s effluent. The minor dischargers do not have such a buffer and only represent the end point of that outfall. The outfall pipelines and diffusers layers were derived from a variety of sources including; Clean Water Act Section 316 (b) reports, monitoring reports from the sanitation districts, facility maps or construction plans from the sanitation districts, existing shapefiles from the Southern California Coastal Water Resources Project, and a few were created by using a best guess estimate by connecting the offshore outfall point to the land based facility.  All offshore outfall points came from National Pollutant Discharge Elimination System permits via the California State Water Resources Control Board in 2004."],['Bioregions','Base',new OpenLayers.Layer.TMS("Bioregions",["http://marinemap.org/tiles/Bioregions/"],{layer_id:29,layername:'Bioregions',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/Bioregions/Legend.png','Bioregions',"Metadata: "],['Place Names','Cultural',new OpenLayers.Layer.TMS("Place Names",["http://marinemap.org/tiles/Placenames/"],{layer_id:30,layername:'Placenames',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/Placenames/Legend.png','Placenames',"Metadata: "],['Surfing Locations','Cultural',new OpenLayers.Layer.TMS("Surfing Locations",["http://marinemap.org/tiles/SurfingLocations/"],{layer_id:31,layername:'Surfing Locations',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/SurfingLocations/Legend.png','Surfing Locations',"Metadata: "],['Halibut Trawl Grounds','Consumptive',new OpenLayers.Layer.TMS("Halibut Trawl Grounds",["http://marinemap.org/tiles/HalibutTrawlGrounds/"],{layer_id:32,layername:'Halibut Trawl Grounds',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/HalibutTrawlGrounds/Legend.png','Halibut Trawl Grounds',"Metadata: "],['Kelp Persistence','SAT Analyses',new OpenLayers.Layer.TMS("Kelp Persistence",["http://marinemap.org/tiles/PersistentKelp/"],{layer_id:33,layername:'Kelp Persistence',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/PersistentKelp/Legend.png','Kelp Persistence',"The linear kelp layer represents the alongshore length of persistent kelp beds. CDFG aerial kelp surveys from the years 1989, 1999, and 2003 through 2006 were used to assess kelp persistence--areas with kelp present at least 3 out of the 7 survey years were considered persistent. The alongshore length of these persistent kelp beds is measured using a line drawn along the outside edge of the kelp bed and roughly parallel to shore."],['Grunion Spawning Locations','Biological',new OpenLayers.Layer.TMS("Grunion Spawning Locations",["http://marinemap.org/tiles/GrunionSpawningLocations/"],{layer_id:34,layername:'Grunion Spawning Locations',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/GrunionSpawningLocations/Legend.png','Grunion Spawning Locations',"Metadata:"],['Beach Nourishment','Management',new OpenLayers.Layer.TMS("Beach Nourishment",["http://marinemap.org/tiles/BeachNourishment/"],{layer_id:35,layername:'Beach Nourhishment',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/BeachNourishment/Legend.png','Beach Nourishment',"Metadata:"],['Substrate Proxy (0-30m)','SAT Analyses',new OpenLayers.Layer.TMS("Substrate Proxy (0-30m)",["http://marinemap.org/tiles/LinearSubstrate/"],{layer_id:36,layername:'Substrate Proxy (0-30m)',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/LinearSubstrate/Legend.png','Substrate Proxy (0-30m)',"The shallow substrate proxy line integrates multiple sources of information to estimate the alongshore length of nearshore habitat that is dominated by rocky and soft-bottom respectively.  Information sources used to create this proxy include: finescale substrate data collected by Fugro Pelagos, Kvitek, USGS and others; maximum extent of kelp from CDFG aerial kelp surveys in years 1989, 1999, and 2003 through 2006; reef classifications from the Southern California Coastal Water Research Project (SCCWRP) Southern California Bight 2008 Regional Marine Monitoring Survey (Bight ’08) project; and shoreline type classification from National Oceanic and Atmospheric Administration (NOAA) Environmental Sensitivity Index (ESI) maps. It is important to recognize that this nearshore substrate proxy represents a generalized representation of the entire area from 0-30 meters depth, and not simply the habitat type present where the line is drawn."],['Maximum Extent of Kelp','SAT Analyses',new OpenLayers.Layer.TMS("Maximum Extent of Kelp",["http://marinemap.org/tiles/MaxKelp/"],{layer_id:37,layername:'Maximum Extent of Kelp',buffer:1,'isBaseLayer':false,'opacity':0.80,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/MaxKelp/Legend.png','Maximum Extent of Kelp',"The maximum kelp layer represents the alongshore length of all kelp beds captured by CDFG aerial kelp surveys from the years 1989, 1999, and 2002 through 2006. The alongshore length of these kelp beds is measured using a line drawn along the outside edge of the kelp and roughly parallel to shore. Areas with multiple small patches of kelp canopy are represented with a solid linear feature around the outer edge of the broader area where the small patches occur."],['Substrate SAT','SAT Analyses',new OpenLayers.Layer.TMS("Substrate SAT",["http://marinemap.org/tiles/SubstrateSAT/"],{layer_id:38,layername:'Substrate SAT',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/SubstrateSAT/Legend.png','Substrate SAT',"This layer is a combination predicted substrate and linear 0 - 30m substrate proxy layers and aims to illustrate the use of data by the Science Advisory Team (SAT) when evaluating habitats influenced by substrate."],['Vessel Obervations - Lighthawk Project','Draft',new OpenLayers.Layer.TMS("Vessel Obervations - Lighthawk Project",["http://marinemap.org/tiles/Lighthawk/"],{layer_id:39,layername:'Vessel Obervations - Lighthawk Project',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/Lighthawk/Legend.png','Vessel Obervations - Lighthawk Project',"Metadata forthcoming"],['Coastline Buffers','Base',new OpenLayers.Layer.TMS("CoastlineBuffers",["http://marinemap.org/tiles/CoastlineBuffers/"],{layer_id:40,layername:'Coastline Buffers',buffer:1,'isBaseLayer':false,'opacity':1.0,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var path=z+"/"+x+"/"+y+".png";}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/tiles/CoastlineBuffers/Legend.png','Coastline Buffers',"Metadata forthcoming"],['Human Uses Layers','Consumptive',new OpenLayers.Layer.WMS("HumanUsesLayers","/marinemap/mapserver/wms/esri/",{layer_id:29,layers:"HumanUses",esrilayer:"",transparent:"true",format:"image/png"},{'opacity':0.8}),'media/images/socioecon-legend.png','Human Uses Maps',"This dataset is a result of the Southern California Regional Workshop, conducted as a part of the California Ocean Uses Atlas Project: a collaboration between NOAA's National Marine Protected Areas Center and Marine Conservation Biology Institute. The workshop goal was to gather geospatial data on 26 human uses of California's ocean environment from the shoreline to the 200 nm EEZ boundary."],['Exposure Probability - Tijuana','Ocean Observing',new OpenLayers.Layer.TMS("Exposure Probability - Tijuana",["http://sandbar.ucsd.edu/tiles/mm/px/tj/"],{layer_id:38,layername:'Exposure Probability - Tijuana',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var zz=(z<10)?'0'+z:z;var t={x:x,y:y}
var path=zz+'/z'+z+'y'+t.y+'x'+t.x+'.png';}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/blank_tile/blank_legend.png','Exposure Probability',"The exposure map shows the area of influence from freshwater plumes. The color bar indicates the probability that the plume will reach a given area.  For example, red indicates locations that are always (100% of the time) impacted by plume waters when the plume is present. The exposure map was generated based on time periods the river is discharging (following rain events). Reference: Kim, S. Y., E. J. Terrill, and B. D. Cornuelle, 2009: Assessing coastal plumes in a region of multiple discharges: the U.S.--Mexico border, Environ. Sci. Tech., 43(19), 7450Ð-7457, doi:10.1021/es900775p"],['Exposure Probability - Punta Bandera','Ocean Observing',new OpenLayers.Layer.TMS("Exposure Probability - Pu–ta Bandera",["http://sandbar.ucsd.edu/tiles/mm/px/lb/"],{layer_id:38,layername:'Exposure Probability - Pu–ta Bandera',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var zz=(z<10)?'0'+z:z;var t={x:x,y:y}
var path=zz+'/z'+z+'y'+t.y+'x'+t.x+'.png';}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/blank_tile/blank_legend.png','Exposure Probability - Pu–ta Bandera',"The exposure map shows the area of influence from freshwater plumes. The color bar indicates the probability that the plume will reach a given area.  For example, red indicates locations that are always (100% of the time) impacted by plume waters when the plume is present. This is a beach outfall flowing constantly at San Antonio de Los Buenos. Reference: Kim, S. Y., E. J. Terrill, and B. D. Cornuelle, 2009: Assessing coastal plumes in a region of multiple discharges: the U.S.--Mexico border, Environ. Sci. Tech., 43(19), 7450Ð-7457, doi:10.1021/es900775p"],['Exposure Probability - South Bay Ocean Outfall','Ocean Observing',new OpenLayers.Layer.TMS("Exposure Probability - South Bay Ocean Outfall",["http://sandbar.ucsd.edu/tiles/mm/px/of/"],{layer_id:38,layername:'Exposure Probability - South Bay Ocean Outfall',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var zz=(z<10)?'0'+z:z;var t={x:x,y:y}
var path=zz+'/z'+z+'y'+t.y+'x'+t.x+'.png';}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/blank_tile/blank_legend.png','Exposure Probability - South Bay Ocean Outfall',"The exposure map shows the area of influence from freshwater plumes. The color bar indicates the probability that the plume will reach a given area.  For example, red indicates locations that are always (100% of the time) impacted by plume waters when the plume is present. The exposure map was generated based on time periods when the outfall is surfacing. Reference: Kim, S. Y., E. J. Terrill, and B. D. Cornuelle, 2009: Assessing coastal plumes in a region of multiple discharges: the U.S.--Mexico border, Environ. Sci. Tech., 43(19), 7450Ð-7457, doi:10.1021/es900775p"],['Larval Retention Areas - Ano Nuevo','Ocean Observing',new OpenLayers.Layer.TMS("Larval retention areas - Ano Nuevo",["http://sandbar.ucsd.edu/tiles/mm/age/AnoNuevo/"],{layer_id:38,layername:'Ocean Circulation Patterns - Ano Nuevo',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var zz=(z<10)?'0'+z:z;var t={x:x,y:y}
var path=zz+'/z'+z+'y'+t.y+'x'+t.x+'.png';}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/blank_tile/blank_legend.png','Larval retention areas',"Connectivity maps based on measured surface currents show what waters are influencing the MPAs and the potential extent of surface water larval transport. The A–o Nuevo example has extensive coastal extent in both directions along the coast. Color-code:  Location of waters 40 days ago (red), 30 days ago (yellow), 20 days ago (green), 10 days ago (cyan), and 5 days ago (blue) before reaching the labeled MPA (magenta). Reference: B. Zelenke, M. Moline, G. Crawford, N. Garfield, B. Jones, J. Largier, J. Paduan, S. Ramp, E. Terrill, and L. Washburn, \ÒEvaluating Connectivity between Marine Protected Areas Using CODAR High-Frequency Radar,\Ó in Proceedings of the OCEANS 2009 MTS/IEEE Biloxi Conference, Biloxi, MS (2009)."],['Larval Retention Areas - Point Sur','Ocean Observing',new OpenLayers.Layer.TMS("Larval retention areas - Point Sur",["http://sandbar.ucsd.edu/tiles/mm/age/PointSur/"],{layer_id:38,layername:'Ocean Circulation Patterns - Point Sur',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var zz=(z<10)?'0'+z:z;var t={x:x,y:y}
var path=zz+'/z'+z+'y'+t.y+'x'+t.x+'.png';}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/blank_tile/blank_legend.png','Larval retention areas',"Connectivity maps based on measured surface currents show what waters are influencing the MPAs and the potential extent of surface water larval transport. The Point Sur example shows broad offshore transport. Color-code:  Location of waters 40 days ago (red), 30 days ago (yellow), 20 days ago (green), 10 days ago (cyan), and 5 days ago (blue) before reaching the labeled MPA (magenta). Reference: B. Zelenke, M. Moline, G. Crawford, N. Garfield, B. Jones, J. Largier, J. Paduan, S. Ramp, E. Terrill, and L. Washburn, \ÒEvaluating Connectivity between Marine Protected Areas Using CODAR High-Frequency Radar,\Ó in Proceedings of the OCEANS 2009 MTS/IEEE Biloxi Conference, Biloxi, MS (2009)."],['Larval Retention Areas - Vandenberg','Ocean Observing',new OpenLayers.Layer.TMS("Larval Retention Areas - Vandenberg",["http://sandbar.ucsd.edu/tiles/mm/age/Vandenberg/"],{layer_id:38,layername:'Larval Retention Areas - Vandenberg',buffer:1,'isBaseLayer':false,'opacity':0.90,'sphericalMercator':true,getURL:function(bounds){var z=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;var url=this.url;var path='blank.png';if(z<=18&&z>=6){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var limit=Math.pow(2,z);var zz=(z<10)?'0'+z:z;var t={x:x,y:y}
var path=zz+'/z'+z+'y'+t.y+'x'+t.x+'.png';}
if(url instanceof Array){url=this.selectUrl(path,url);}
tilepath=url+path;return url+path;}}),'http://marinemap.org/blank_tile/blank_legend.png','Larval retention areas',"Connectivity maps based on measured surface currents show what waters are influencing the MPAs and the potential extent of surface water larval transport. The Vandenberg example shows smaller spatial extent with more transport from the Southern California Bight. Color-code:  Location of waters 40 days ago (red), 30 days ago (yellow), 20 days ago (green), 10 days ago (cyan), and 5 days ago (blue) before reaching the labeled MPA (magenta). Reference: B. Zelenke, M. Moline, G. Crawford, N. Garfield, B. Jones, J. Largier, J. Paduan, S. Ramp, E. Terrill, and L. Washburn, \ÒEvaluating Connectivity between Marine Protected Areas Using CODAR High-Frequency Radar,\Ó in Proceedings of the OCEANS 2009 MTS/IEEE Biloxi Conference, Biloxi, MS (2009)."]];for(var i=0;i<MarineMap.data.DataLayers.length;i++){var l=MarineMap.data.DataLayers[i];if(l[LAYER]instanceof OpenLayers.Layer.WMS){var params=OpenLayers.Util.extend({LAYER:l[LAYER].params.LAYERS},getLegendParams);var paramsString=OpenLayers.Util.getParameterString(params);l[LEGEND]=l[LAYER].url+'?'+paramsString;}}
MarineMap.data.EcotrustFishingImpactLayers=[['Ecotrust Fishing Ground Maps','Consumptive',new OpenLayers.Layer.WMS("Ecotrust Fishing Ground Maps","/marinemap/mapserver/wms/",{layer_id:28,layers:"SocioEconomicFishing",transparent:"true",format:"image/png"},{'opacity':0.9}),'media/images/socioecon-legend.png','Ecotrust Fishing Ground Maps','Ecotrust has generated these maps through a series of interviews with commercial and recreational fisherman throughout the South Coast region of California. <br/><br/>To view a map, first turn this layer on.  You will be presented with a menu allowing you to select a user group, species, and port/county.  <br/><br/>A number of other aggregations are also available for selection, which are simply combinations of the individual maps.  Please ask for assistance if you need help understanding what they represent.<br/><br/>Finally click the button to load the map, you will see it come into view on the map display.  If you don\'t see anything make sure you are zoomed into the right area for what you selected.  Be aware that some maps are hard to see zoomed all the way out as well.  Look for red and yellow colors.<br/><br/>To load a different map, simply turn this layer off (checkbox) and then back on again to reload the selection menu.']];MarineMap.data.SubDataLayers=[{node_name:'Satellite/Aerial Imagery',uiProvider:Ext.tree.ColumnNodeUI,children:[]},{node_name:'Bathymetry',uiProvider:Ext.tree.ColumnNodeUI,children:[]},{node_name:'Nautical Charts',uiProvider:Ext.tree.ColumnNodeUI,children:[]},{node_name:'Study Region',uiProvider:Ext.tree.ColumnNodeUI,children:[]},{node_name:'Graticules',uiProvider:Ext.tree.ColumnNodeUI,children:[]},{node_name:'Isobaths',uiProvider:Ext.tree.ColumnNodeUI,children:[]},{node_name:'Marine Mammals',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Pinniped Rookeries',sde:'BIO_MAMMAL_PINNIPED_ROOKERIES_2008',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'Sp_Com_Nam',node_name:'Name',value:''}]},{node_name:'Pinniped Haulouts',sde:'BIO_MAMMAL_PINNIPEDS_2008',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'Com_Name',node_name:'Name',value:''},{field:'Num_Pups',node_name:'Number of pups',value:''},{field:'Total_Pinn',node_name:'Total number',value:''},{field:'Month',node_name:'Month',value:''},{field:'Year',node_name:'Year',value:''}]}]},{node_name:'Sea Bird Diversity',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Colony size and # of species',sde:'BIO_SRSC_BIRD_COLONIES_SEABIRD',shape_field:'SHAPE',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'NumSpecies',node_name:'Total # of species',value:''},{field:'NumBirds',node_name:'Total # of birds',value:''}]}]},{node_name:'Recreational Fishing',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Fishing Piers and Jetties',sde:'CUL_SRSC_FISHINGPIERSANDJETTIES',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'MM_BDRY',node_name:'Name',value:''}]},{node_name:'Kayak Launch Sites',sde:'CUL_KFACA_KAYAKLAUNCHSITES',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'pmName',node_name:'Name',value:''}]},{node_name:'Kayak Fishing Areas',sde:'CON_KFACA_KAYAKFISHINGAREAS',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'pmName',node_name:'Name',value:''}]},{node_name:'Spearfish Competition Sites',sde:'CON_CENCALSPEARFISHSITES',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'DESCRIPT',node_name:'Name',value:''}]}]},{node_name:'Estuaries',uiProvider:Ext.tree.ColumnNodeUI,children:[]},{node_name:'Nearshore Habitats',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Oil Seeps',sde:'PHY_OILSEEPS',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'DESCRIPTIO',node_name:'Description',value:''}]}]},{node_name:'Hard and Soft Substrata',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Hard Substrate',sde:'HAB_SRSC_SUBSTRATE',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'DESCRIPT',node_name:'Description',value:''},{field:'Sub_Depth',node_name:'Depth',value:''}]},{node_name:'Artificial Reefs',sde:'HAB_ARTIFICIALREEFS_CENTROIDS',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'NAME',node_name:'Name',value:''}]},{node_name:'Shipwrecks',sde:'CUL_SHIPWRECKSNOAAENC',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'COASTAL__1',node_name:'Description',value:''}]},{node_name:'Submarine Canyons',sde:'PHY_CANYONS',shape_field:'SHAPE',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'HAB_TYPE',node_name:'Habitat Type',value:''}]}]},{node_name:'Coastal Energy',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Power Plants',sde:'CUL_POWERPLANTS',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Name',field:'PLANTNAME',value:''},{node_name:'Technology',field:'TECHNOLOGY',value:''}]},{node_name:'Oil Platforms',sde:'CUL_OILPLATFORMS',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Name',field:'NAME',value:''}]}]},{node_name:'Research and Monitoring',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Research Institutions',sde:'CUL_RESEARCH_INSTITUTIONS',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Name',field:'INSTITUTE',value:''}]},{node_name:'Marine Monitoring Sites',sde:'MAN_MONITORINGSITES',shape_field:'SHAPE',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Name',field:'NAME',value:''},{node_name:'Institution',field:'INSTITUTIO',value:''}]},{node_name:'Crane Monitoring Sites',sde:'MAN_MONITORING_CRANE',shape_field:'SHAPE',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Name',field:'SITE_NAME',value:''}]}]},{node_name:'Cowcod Conservation Area',uiProvider:Ext.tree.ColumnNodeUI,children:[]},{node_name:'Managed Areas',uiProvider:Ext.tree.ColumnNodeUI,iconCls:'',children:[{node_name:'Terrestrial Managed Areas',sde:'MAN_MANAGEDAREAS_TERRESTRIAL',shape_field:'SHAPE',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Managing Agency',field:'OWNERCODE',value:''}]},{node_name:'Marine Managed Areas',sde:'MAN_FEDMPA',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Name',field:'AREANAME1',value:''}]}]},{node_name:'MPAs: Existing State',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'State Marine Protected Areas',sde:'MPA_STATE',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'NAME',node_name:'Name',value:''},{field:'Type',node_name:'Type',value:''}]}]},{node_name:'RCA: Commercial, Non-Trawl',uiProvider:Ext.tree.ColumnNodeUI,children:[]},{node_name:'RCA: Commercial, Trawl',uiProvider:Ext.tree.ColumnNodeUI,children:[]},{node_name:'RCA: Recreational',uiProvider:Ext.tree.ColumnNodeUI,children:[]},{node_name:'Restricted Areas',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Restricted Areas',sde:'MAN_RESTRICTEDAREAS',shape_field:'SHAPE',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'TYPE',node_name:'Type',value:''}]}]},{node_name:'Coastal Access and Recreation',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Ports',sde:'CUL_PORTS',shape_field:'SHAPE',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'FEAT_NAME',node_name:'Name',value:''}]},{node_name:'Harbors',sde:'CUL_HARBORS',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'PROPERNAME',node_name:'Name',value:''}]},{node_name:'Coastal Access Points',sde:'CUL_COAST_ACCESSPOINT',shape_field:'SHAPE',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'NAME',node_name:'Name',value:''},{field:'FEATURETYP',node_name:'Type',value:''}]},{node_name:'Kayak Launch Sites',sde:'CUL_KFACA_KAYAKLAUNCHSITES',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'pmName',node_name:'Name',value:''}]},{node_name:'Shore Dive Sites',sde:'NON_SRSC_SHORE_DIVE_LOCATIONS',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'Site_Name',node_name:'Name',value:''}]}]},{node_name:'Agricultural Impacts to Watersheds',uiProvider:Ext.tree.ColumnNodeUI,children:[]},{node_name:'Urban Impacts to Watersheds',uiProvider:Ext.tree.ColumnNodeUI,children:[]},{node_name:'Watersheds',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Major Watersheds',sde:'PHY_HUNAMECALWAT221',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'HUNAME',node_name:'Hydrologic Unit Name',value:''}]},{node_name:'Coastal Rivers',sde:'PHY_COASTALRIVERS',shape_field:'SHAPE',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'PNAME',node_name:'Name',value:''}]}]},{node_name:'Water Quality',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Impaired Rivers',sde:'PHY_IMPAIRED_RIVERS_CART',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'WBNAME',node_name:'Name',value:''},{field:'WBTYPE_NAM',node_name:'Type',value:''}]},{node_name:'Impaired Water Bodies',sde:'PHY_IMPAIRED_WATERBODIES',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'WBNAME',node_name:'Name',value:''},{field:'WBTYPE_NAM',node_name:'Type',value:''}]},{node_name:'Ocean Outfalls',sde:'CUL_OCEANOUTFALLS',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'FACILITY',node_name:'Facility Name',value:''},{field:'PRIMARY_DI',node_name:'Company/Organization',value:''},{field:'PRIMARY_EF',node_name:'Type',value:''}]}]},{node_name:'Shore Types',uiProvider:Ext.tree.ColumnNodeUI,children:[{node_name:'Shore Types',sde:'HAB_SHORETYPES',shape_field:'Shape',uiProvider:Ext.tree.ColumnNodeUI,children:[{field:'MapClass',node_name:'Shore Type',value:''}]}]}];Ext.namespace('MarineMap','MarineMap.data');MarineMap.data.FisheryImpactMapUserGroups=[['cpfv','Comm. Passenger Fishing Vessel'],['com','Commercial'],['div','Recreational Dive'],['kyk','Recreational Kayak'],['pvt','Recreational Vessel'],['cnty','Recreational All Sectors']];MarineMap.data.FisheryImpactMapCpfvPorts=[['al','Entire Study Region'],['sb','Santa Barbara'],['ph','Port Hueneme/Channel Islands Harbor'],['sm','Santa Monica'],['sp','San Pedro/Long Beach'],['nb','Newport Beach'],['dp','Dana Point'],['oc','Oceanside'],['sd','San Diego']];MarineMap.data.FisheryImpactMapRecPorts=[['cmp','Entire Study Region'],['sbk','Santa Barbara County'],['vtk','Ventura County'],['lak','Los Angeles County'],['ock','Orange County'],['sdk','San Diego County']];MarineMap.data.FisheryImpactMapPvtPorts=[['cmp','Entire Study Region'],['sbk','Santa Barbara County'],['vtk','Ventura County'],['lak','Los Angeles County'],['ock','Orange County'],['osk','Oceanside'],['sdk','San Diego County']];MarineMap.data.FisheryImpactMapComPorts=[['allk','Entire study region'],['sbk','Santa Barbara'],['vtk','Ventura'],['phk','Port Hueneme/Channel Islands Harbor'],['spk','San Pedro'],['dpk','Dana Point'],['ock','Oceanside'],['sdk','San Diego']];MarineMap.data.FisheryImpactMapCntyPorts=[['sb','Santa Barbara County'],['vt','Ventura County'],['la','Los Angeles County'],['oc','Orange County'],['sd','San Diego County']];MarineMap.data.FisheryImpactMapAllCntySpecies=[['comp','Target Species Aggregated']];MarineMap.data.FisheryImpactMapAllCpfvSpecies=[['comp','All Species Aggregated'],['barc','Barracuda'],['clbas','Calico Bass'],['chal','California Halibut'],['sclp','California Scorpionfish (Sculpin)'],['shphd','California Sheephead'],['ling','Lingcod'],['rock','Rockfish'],['snbas','Sand Bass'],['wsbas','White Seabass'],['whtf','Whitefish']];MarineMap.data.FisheryImpactMapAllCpfvSpeciesSansComp=[['barc','Barracuda'],['clbas','Calico Bass'],['chal','California Halibut'],['sclp','California Scorpionfish (Sculpin)'],['shphd','California Sheephead'],['ling','Lingcod'],['rock','Rockfish'],['snbas','Sand Bass'],['wsbas','White Seabass'],['whtf','Whitefish']];MarineMap.data.FisheryImpactMapStudyRegionComSpecies=[['chalh','California Halibut - hook and line'],['cpss','Coastal Pelagics - seine'],['lbt','Live Bait'],['lobt','Lobster - trap'],['nsrkt','Nearshore Fishery - trap'],['nsrkh','Nearshore Fishery - hook and line'],['pbns','Pacific Bonito - seine'],['rcrbt','Rock Crab - trap'],['salt','Salmon - troll'],['sccd','Sea Cucumber - dive'],['spwnt','Spot Prawn - trap'],['sqdb','Squid - braile'],['sqds','Squid - seine'],['swdh','Swordfish - harpoon'],['urcd','Urchin - dive'],['wsbg','White Seabass - gilnet']];MarineMap.data.FisheryImpactMapSbkComSpecies=[['chalh','California Halibut - hook and line'],['chalt','California Halibut - trawl'],['dnsrh','Deep Nearshore Rockfish - hook and line'],['lobt','Lobster - trap'],['nsrkt','Nearshore Fishery - trap'],['nsrkh','Nearshore Fishery - hook and line'],['rcrbt','Rock Crab - trap'],['salt','Salmon - troll'],['sccd','Sea Cucumber - dive'],['scuct','Sea Cucumber - trawl'],['spwnt','Spot Prawn - trap'],['urcd','Urchin - dive'],['wsbg','White Seabass - gilnet']];MarineMap.data.FisheryImpactMapVtkComSpecies=[['lobt','Lobster - trap'],['nsrkt','Nearshore Fishery - trap'],['rcrbt','Rock Crab - trap'],['sccd','Sea Cucumber - dive'],['spwnt','Spot Prawn - trap'],['sqds','Squid - seine']];MarineMap.data.FisheryImpactMapPhkComSpecies=[['chalh','California Halibut - hook and line'],['cpss','Coastal Pelagics - seine'],['lobt','Lobster - trap'],['nsrkt','Nearshore Fishery - trap'],['nsrkh','Nearshore Fishery - hook and line'],['rcrbt','Rock Crab - trap'],['sccd','Sea Cucumber - dive'],['spwnt','Spot Prawn - trap'],['sqds','Squid - seine'],['urcd','Urchin - dive']];MarineMap.data.FisheryImpactMapSpkComSpecies=[['cpss','Coastal Pelagics - seine'],['lbt','Live Bait'],['lobt','Lobster - trap'],['nsrkt','Nearshore Fishery - trap'],['nsrkh','Nearshore Fishery - hook and line'],['pbns','Pacific Bonito - seine'],['rcrbt','Rock Crab - trap'],['sccd','Sea Cucumber - dive'],['spwnt','Spot Prawn - trap'],['sqdb','Squid - braile'],['sqds','Squid - seine'],['swdh','Swordfish - harpoon'],['urcd','Urchin - dive'],['wsbg','White Seabass - gilnet']];MarineMap.data.FisheryImpactMapDpkComSpecies=[['lbt','Live Bait'],['lobt','Lobster - trap'],['nsrkt','Nearshore Fishery - trap'],['rcrbt','Rock Crab - trap'],['spwnt','Spot Prawn - trap'],['urcd','Urchin - dive']];MarineMap.data.FisheryImpactMapOckComSpecies=[['lbt','Live Bait'],['lobt','Lobster - trap'],['nsrkt','Nearshore Fishery - trap'],['rcrbt','Rock Crab - trap'],['spwnt','Spot Prawn - trap'],['urcd','Urchin - dive']];MarineMap.data.FisheryImpactMapSdkComSpecies=[['lbt','Live Bait'],['lobt','Lobster - trap'],['nsrkt','Nearshore Fishery - trap'],['nsrkh','Nearshore Fishery - hook and line'],['rcrbt','Rock Crab - trap'],['sccd','Sea Cucumber - dive'],['spwnt','Spot Prawn - trap'],['urcd','Urchin - dive']];MarineMap.data.FisheryImpactMapAllDivSpecies=[['comp','Target Species Aggregated'],['barc','Barracuda'],['bon','Bonita'],['clbas','Calico Bass'],['chal','California Halibut'],['shphd','California Sheephead'],['crkr','Croaker'],['lobs','Lobster'],['rckf','Rockfish / Lingcod'],['snbas','Sand Bass'],['scalp','Scallops'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapCmpDivSpecies=[['comp','Target Species Aggregated'],['chal','California Halibut'],['lobs','Lobster'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapSbkDivSpecies=[['comp','Target Species Aggregated'],['clbas','Calico Bass'],['chal','California Halibut'],['lobs','Lobster'],['rckf','Rockfish / Lingcod'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapVtkDivSpecies=[['comp','Target Species Aggregated'],['clbas','Calico Bass'],['chal','California Halibut'],['lobs','Lobster'],['rckf','Rockfish / Lingcod'],['scalp','Scallops'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapLakDivSpecies=[['comp','Target Species Aggregated'],['clbas','Calico Bass'],['chal','California Halibut'],['shphd','California Sheephead'],['lobs','Lobster'],['snbas','Sand Bass'],['scalp','Scallops'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapOckDivSpecies=[['comp','Target Species Aggregated'],['clbas','Calico Bass'],['chal','California Halibut'],['shphd','California Sheephead'],['crkr','Croaker'],['lobs','Lobster'],['rckf','Rockfish / Lingcod'],['snbas','Sand Bass'],['scalp','Scallops'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapAllKykSpecies=[['comp','Target Species Aggregated'],['barc','Barracuda'],['bon','Bonita'],['clbas','Calico Bass'],['chal','California Halibut'],['shphd','California Sheephead'],['lobs','Lobster'],['mckl','Mackerels'],['rcrb','Rock Crab'],['rckf','Rockfish / Lingcod'],['snbas','Sand Bass'],['sqd','Squid'],['tshk','Thresher Shark'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapCmpKykSpecies=[['comp','Target Species Aggregated'],['clbas','Calico Bass'],['chal','California Halibut'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapLakKykSpecies=[['comp','Target Species Aggregated'],['barc','Barracuda'],['bon','Bonita'],['clbas','Calico Bass'],['chal','California Halibut'],['lobs','Lobster'],['rckf','Rockfish / Lingcod'],['snbas','Sand Bass'],['tshk','Thresher Shark'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapOckKykSpecies=[['comp','Target Species Aggregated'],['barc','Barracuda'],['bon','Bonita'],['clbas','Calico Bass'],['chal','California Halibut'],['shphd','California Sheephead'],['lobs','Lobster'],['mckl','Mackerels'],['rckf','Rockfish / Lingcod'],['snbas','Sand Bass'],['tshk','Thresher Shark'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapSbkKykSpecies=[['comp','Target Species Aggregated'],['clbas','Calico Bass'],['chal','California Halibut']];MarineMap.data.FisheryImpactMapVtkKykSpecies=[['comp','Target Species Aggregated'],['clbas','Calico Bass'],['chal','California Halibut'],['shphd','California Sheephead'],['lobs','Lobster'],['mckl','Mackerels'],['rckf','Rockfish / Lingcod'],['snbas','Sand Bass'],['wsbas','White Seabass']];MarineMap.data.FisheryImpactMapAllPvtSpecies=[['comp','Target Species Aggregated'],['barc','Barracuda'],['bon','Bonita'],['clbas','Calico Bass'],['chal','California Halibut'],['shphd','California Sheephead'],['crkr','Croaker'],['lobs','Lobster'],['mckl','Mackerels'],['rckf','Rockfish / Lingcod'],['snbas','Sand Bass'],['srfp','Surfperch'],['tshk','Thresher Shark'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapCmpPvtSpecies=[['comp','Target Species Aggregated'],['clbas','Calico Bass'],['chal','California Halibut'],['snbas','Sand Bass'],['wsbas','White Seabass']];MarineMap.data.FisheryImpactMapLakPvtSpecies=[['comp','Target Species Aggregated'],['barc','Barracuda'],['bon','Bonita'],['clbas','Calico Bass'],['chal','California Halibut'],['shphd','California Sheephead'],['lobs','Lobster'],['mckl','Mackerels'],['rckf','Rockfish / Lingcod'],['snbas','Sand Bass'],['tshk','Thresher Shark'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapOckPvtSpecies=[['comp','Target Species Aggregated'],['barc','Barracuda'],['bon','Bonita'],['clbas','Calico Bass'],['chal','California Halibut'],['crkr','Croaker'],['lobs','Lobster'],['mckl','Mackerels'],['rckf','Rockfish / Lingcod'],['snbas','Sand Bass'],['tshk','Thresher Shark'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapOskPvtSpecies=[['comp','Target Species Aggregated'],['barc','Barracuda'],['clbas','Calico Bass'],['chal','California Halibut'],['lobs','Lobster'],['rckf','Rockfish / Lingcod'],['snbas','Sand Bass'],['tshk','Thresher Shark'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapSbkPvtSpecies=[['comp','Target Species Aggregated'],['clbas','Calico Bass'],['chal','California Halibut'],['rckf','Rockfish / Lingcod'],['wsbas','White Seabass']];MarineMap.data.FisheryImpactMapVtkPvtSpecies=[['comp','Target Species Aggregated'],['barc','Barracuda'],['clbas','Calico Bass'],['chal','California Halibut'],['rckf','Rockfish / Lingcod'],['wsbas','White Seabass'],['ytail','Yellowtail']];MarineMap.data.FisheryImpactMapSpeciesByGroup=[['cpfv',[['al',MarineMap.data.FisheryImpactMapAllCpfvSpeciesSansComp],['sb',MarineMap.data.FisheryImpactMapAllCpfvSpecies],['ph',MarineMap.data.FisheryImpactMapAllCpfvSpecies],['sm',MarineMap.data.FisheryImpactMapAllCpfvSpecies],['sp',MarineMap.data.FisheryImpactMapAllCpfvSpecies],['nb',MarineMap.data.FisheryImpactMapAllCpfvSpecies],['dp',MarineMap.data.FisheryImpactMapAllCpfvSpecies],['oc',MarineMap.data.FisheryImpactMapAllCpfvSpecies],['sd',MarineMap.data.FisheryImpactMapAllCpfvSpecies]]],['com',[['allk',MarineMap.data.FisheryImpactMapStudyRegionComSpecies],['sbk',MarineMap.data.FisheryImpactMapSbkComSpecies],['vtk',MarineMap.data.FisheryImpactMapVtkComSpecies],['phk',MarineMap.data.FisheryImpactMapPhkComSpecies],['spk',MarineMap.data.FisheryImpactMapSpkComSpecies],['dpk',MarineMap.data.FisheryImpactMapDpkComSpecies],['ock',MarineMap.data.FisheryImpactMapOckComSpecies],['sdk',MarineMap.data.FisheryImpactMapSdkComSpecies]]],['div',[['cmp',MarineMap.data.FisheryImpactMapCmpDivSpecies],['sbk',MarineMap.data.FisheryImpactMapSbkDivSpecies],['vtk',MarineMap.data.FisheryImpactMapVtkDivSpecies],['lak',MarineMap.data.FisheryImpactMapLakDivSpecies],['ock',MarineMap.data.FisheryImpactMapOckDivSpecies],['sdk',MarineMap.data.FisheryImpactMapAllDivSpecies]]],['kyk',[['cmp',MarineMap.data.FisheryImpactMapCmpKykSpecies],['sbk',MarineMap.data.FisheryImpactMapSbkKykSpecies],['vtk',MarineMap.data.FisheryImpactMapVtkKykSpecies],['lak',MarineMap.data.FisheryImpactMapLakKykSpecies],['ock',MarineMap.data.FisheryImpactMapOckKykSpecies],['sdk',MarineMap.data.FisheryImpactMapAllKykSpecies]]],['pvt',[['cmp',MarineMap.data.FisheryImpactMapCmpPvtSpecies],['sbk',MarineMap.data.FisheryImpactMapSbkPvtSpecies],['vtk',MarineMap.data.FisheryImpactMapVtkPvtSpecies],['lak',MarineMap.data.FisheryImpactMapLakPvtSpecies],['ock',MarineMap.data.FisheryImpactMapOckPvtSpecies],['osk',MarineMap.data.FisheryImpactMapOskPvtSpecies],['sdk',MarineMap.data.FisheryImpactMapAllPvtSpecies]]],['cnty',[['all',MarineMap.data.FisheryImpactMapAllCntySpecies]]]];MarineMap.data.FisheryImpactMapPortsByGroup=[['cpfv',MarineMap.data.FisheryImpactMapCpfvPorts],['com',MarineMap.data.FisheryImpactMapComPorts],['div',MarineMap.data.FisheryImpactMapRecPorts],['kyk',MarineMap.data.FisheryImpactMapRecPorts],['pvt',MarineMap.data.FisheryImpactMapPvtPorts],['cnty',MarineMap.data.FisheryImpactMapCntyPorts]];Ext.namespace('MarineMap','MarineMap.data');MarineMap.data.HumanUsesMapGroups=[['fish','Fishing'],['ind','Industrial and Military'],['nonc','Nonconsumptive']];MarineMap.data.HumanUsesMapSubgroups=[['dom','Dominant Use Areas'],['fut','Future Trends'],['max','Maximum Footprint']];MarineMap.data.HumanUsesFishDomMapLayers=[['20','Com Benthic Fixed Gear - DUAC'],['19','Com Benthic Mobile Gear - DUAC'],['18','Com Dive Fishing - DUAC'],['17','Com Pelagic - DUAC'],['16','Rec Boat-Based Fishing - DUAC'],['15','Rec Dive Fishing - DUAC'],['14','Rec Kayak Fishing - DUAC'],['13','Rec Shore-Based Fishing - DUAC']];MarineMap.data.HumanUsesFishFutMapLayers=[['11','Com Dive Fishing - FTC'],['10','Rec Boat-Based Fishing - FTC']];MarineMap.data.HumanUsesFishMaxMapLayers=[['8','Com Benthic Fixed Gear - MFC'],['7','Com Benthic Mobile Gear - MFC'],['6','Com Dive Fishing - MFC'],['5','Com Pelagic - MFC'],['4','Rec Boat-Based Fishing - MFC'],['3','Rec Dive Fishing - MFC'],['2','Rec Kayak Fishing - MFC'],['1','Rec Shore-Based Fishing - MFC']];MarineMap.data.HumanUsesIndDomMapLayers=[['15','Cruise Ships - DUAC'],['14','Military Operations - DUAC'],['13','Oil and Natural Gas - DUAC'],['12','Shipping - DUAC']];MarineMap.data.HumanUsesIndFutMapLayers=[['10','Alternative Energy - FTC'],['9','Aquaculture - FTC']];MarineMap.data.HumanUsesIndMaxMapLayers=[['7','Aquaculture - MFC'],['6','Cables - MFC'],['5','Cruise Ships - MFC'],['4','Military Operations - MFC'],['3','Mining - MFC'],['2','Oil and Natural Gas - MFC'],['1','Shipping - MFC']];MarineMap.data.HumanUsesNoncDomMapLayers=[['24','Beach Use - DUAC'],['23','Boating - DUAC'],['22','Paddling - DUAC'],['21','Sailing - DUAC'],['20','Scuba/Snorkeling - DUAC'],['19','Surface Water Sports - DUAC'],['18','Swimming - DUAC'],['17','Tidepooling - DUAC'],['16','Wildlife Viewing - DUAC']];MarineMap.data.HumanUsesNoncFutMapLayers=[['14','Boating - FTC'],['13','Sailing - FTC'],['12','Scuba/Snorkeling - FTC'],['11','Wildlife Viewing - FTC']];MarineMap.data.HumanUsesNoncMaxMapLayers=[['9','Beach Use - MFC'],['8','Boating - MFC'],['7','Paddling - MFC'],['6','Sailing - MFC'],['5','Scuba/Snorkeling - MFC'],['4','Surface Water Sports - MFC'],['3','Swimming - MFC'],['2','Tidepooling - MFC'],['1','Wildlife Viewing - MFC']];MarineMap.data.HumanUsesMapLayersByGroup=[['fish',[['dom',MarineMap.data.HumanUsesFishDomMapLayers],['fut',MarineMap.data.HumanUsesFishFutMapLayers],['max',MarineMap.data.HumanUsesFishMaxMapLayers]]],['ind',[['dom',MarineMap.data.HumanUsesIndDomMapLayers],['fut',MarineMap.data.HumanUsesIndFutMapLayers],['max',MarineMap.data.HumanUsesIndMaxMapLayers]]],['nonc',[['dom',MarineMap.data.HumanUsesNoncDomMapLayers],['fut',MarineMap.data.HumanUsesNoncFutMapLayers],['max',MarineMap.data.HumanUsesNoncMaxMapLayers]]]];Ext.namespace('MarineMap','MarineMap.urls');MarineMap.urls={splash:'/marinemap/splash/',tutorials:'/marinemap/tutorials/',faq:'/marinemap/faq/',sendPassword:'/marinemap/user/sendpassword/',changePassword:'/marinemap/user/changepassword/',newMPAForm:'/marinemap/forms/create/mpa',submitNewMPA:'/marinemap/mpa/create/',validateGeometry:'/marinemap/mpa/validate/',mpas:'/marinemap/mpas/public/?srid=900913',editMPA:'/marinemap/mpa/edit/',deleteMPA:'/marinemap/mpa/delete/',MPAKml:'/marinemap/mpa/kml/',login:'/marinemap/login/',logout:'/marinemap/logout/',user:'/marinemap/user/',index:'/marinemap/',geoserver:'/marinemap/geoserver/wfs/',mpaAttributes:'/marinemap/mpa/',createArray:'/marinemap/array/create/',addtoarray:'/marinemap/mpa/addtoarray/',emptyarrays:'/marinemap/arrays/getempty/',deleteArray:'/marinemap/array/delete/',mpaImpactAnalysis:'/marinemap/econ_analysis/mpa/'};Ext.namespace('MarineMap');MarineMap.actions={};MarineMap.actions.utils={};jQuery.fn.bindButton=function(action,data){$(this).bind('click',data,function(e){action(e);return false});};MarineMap.actions.utils.showGeometryChangeInfo=function(html){MarineMap.app.statusPanel.body.update(html);MarineMap.app.statusPanel.show();};MarineMap.actions.utils.clearGeometryChangeInfo=function(){MarineMap.app.statusPanel.hide();};MarineMap.actions.utils.clearMenus=function(e){if(e){e.stopPropagation();}
Ext.getCmp('maptoolbar').collapseMenus();};MarineMap.actions.utils.restoreComponents=[];MarineMap.actions.utils.disableComponents=function(){if(MarineMap.app.mapToolbar.dataLayersMenu.window.isVisible()){MarineMap.actions.utils.restoreComponents.push(MarineMap.app.mapToolbar.dataLayersMenu);}
if(MarineMap.app.FeaturesMenu.extWindow.isVisible()){MarineMap.actions.utils.restoreComponents.push(MarineMap.app.FeaturesMenu.getExtButton());}
MarineMap.actions.utils.clearMenus();MarineMap.app.mapToolbar.dataLayersMenu.window.isVisible()
MarineMap.app.mapToolWindow.hide();MarineMap.app.reportsVisor.deactivate();MarineMap.ui.modal.hide();};MarineMap.actions.utils.enableComponents=function(){MarineMap.app.mapToolWindow.show();for(var i=0;i<MarineMap.actions.utils.restoreComponents.length;i++){MarineMap.actions.utils.restoreComponents[i].toggle();}
MarineMap.actions.utils.restoreComponents=[];MarineMap.app.reportsVisor.activate();};MarineMap.actions.utils.mapToolbarItems=[];MarineMap.actions.utils.changeMapToolbarMode=function(buttonConfig){var tbar=MarineMap.app.mapToolbar;tbar.addClass('editmodetoolbar');var removeList=[];for(var i=0;i<tbar.items.length;i++){var item=tbar.items.itemAt(i);if(item.restore){item.hide();}else{removeList.push(i);item.destroy();}}
for(var p=0;p<removeList.length;p++){tbar.items.removeAt(removeList[p]);}
for(var j=0;j<buttonConfig.length;j++){buttonConfig[j]['restore']=false;tbar.add(buttonConfig[j]);}};MarineMap.actions.utils.restoreMapToolbar=function(){var tbar=MarineMap.app.mapToolbar;tbar.removeClass('editmodetoolbar');var removeList=[];for(var i=0;i<tbar.items.length;i++){var item=tbar.items.item(i);if(item.restore){item.show();}else{removeList.push(i);item.destroy();}}
for(var p=0;p<removeList.length;p++){tbar.items.removeAt(removeList[p]);}};MarineMap.actions.utils.askUserToDefineGeometry=function(config){if(!config['finish']||!config['cancel']){}else{MarineMap.actions.utils.disableComponents();var clipSuccess=function(status_code,original,clipped){MarineMap.app.map.addClippedGeometryPreview(clipped);var title;var text;if(status_code==0){title=MarineMap.copy.confirmStudyRegionClippingTitle;text=MarineMap.copy.confirmStudyRegionClipping;}else{title=MarineMap.copy.overlapsEstuaryTitle;text=MarineMap.copy.confirmStudyRegionClipping+"<br />"+MarineMap.copy.overlapsEstuary[status_code];}
MarineMap.actions.utils.changeMapToolbarMode([{xtype:'tbtext',text:title},{xtype:'tbfill'},{text:'Go Back and Modify Geometry',geometry:original,config:config,handler:function(){MarineMap.actions.utils.restoreMapToolbar();MarineMap.actions.utils.clearGeometryChangeInfo();this.config['geometry']=this.geometry;MarineMap.app.map.clearClippedGeometryPreview();MarineMap.actions.utils.askUserToDefineGeometry(this.config);}},{text:'Cancel',iconCls:'remove-icon',handler:function(){MarineMap.app.map.clearClippedGeometryPreview();MarineMap.actions.utils.restoreMapToolbar();MarineMap.actions.utils.clearGeometryChangeInfo();config['cancel']();}},{text:'Continue',iconCls:'yes-icon',geometry:original,clipped:clipped,handler:function(){MarineMap.app.map.clearClippedGeometryPreview();MarineMap.actions.utils.restoreMapToolbar();MarineMap.actions.utils.clearGeometryChangeInfo();MarineMap.app.map.selectControl.deactivate();MarineMap.app.map.selectControl.activate();config['finish'](this.geometry,this.clipped);}}]);MarineMap.actions.utils.showGeometryChangeInfo(text);};var clipError=function(status_code,original){MarineMap.actions.utils.changeMapToolbarMode([{xtype:'tbtext',text:'The geometry you defined cannot be accepted'},{xtype:'tbfill'},{text:'Go Back and Modify Geometry',geometry:original,config:config,handler:function(){MarineMap.actions.utils.restoreMapToolbar();MarineMap.actions.utils.clearGeometryChangeInfo();this.config['geometry']=this.geometry;MarineMap.actions.utils.askUserToDefineGeometry(this.config);}},{text:'Cancel',iconCls:'remove-icon',handler:function(){MarineMap.actions.utils.restoreMapToolbar();MarineMap.actions.utils.clearGeometryChangeInfo();MarineMap.actions.utils.enableComponents();config['cancel']();}}]);MarineMap.actions.utils.showGeometryChangeInfo(MarineMap.copy.clippedGeometryStatus[status_code]);};var clipFail=function(response,opts){MarineMap.ui.error.show({errorText:'An unknown Server Error has Occurred while trying to clip your MPA. If you were editing a geometry, that geometry will remain intact as it was before editing. If you were creating a new MPA, you will have to start over. We have been notified of this problem.',logText:'Error clipping MPA'});MarineMap.actions.utils.enableComponents();};if(config['geometry']){MarineMap.app.map.addEditableGeometry(config['geometry']);MarineMap.actions.utils.changeMapToolbarMode([{xtype:'tbtext',text:MarineMap.copy.editGeometry},{xtype:'tbfill'},{text:'Finished',iconCls:'yes-icon',handler:function(){var new_geo=MarineMap.app.map.finishGeometryEditing();MarineMap.actions.utils.restoreMapToolbar();MarineMap.actions.async.clipGeometry({geometry:new_geo,success:clipSuccess,error:clipError,fail:clipFail});}},{text:'cancel',iconCls:'remove-icon',handler:function(){MarineMap.app.map.finishGeometryEditing();MarineMap.actions.utils.restoreMapToolbar();MarineMap.actions.utils.enableComponents();config['cancel']();}}]);}else{MarineMap.app.map.startDrawMPA();MarineMap.actions.utils.changeMapToolbarMode([{xtype:'tbtext',text:MarineMap.copy.createNewGeometry},{xtype:'tbfill'},{text:'cancel',iconCls:'remove-icon',handler:function(){MarineMap.app.map.cancelDrawMPA();MarineMap.actions.utils.enableComponents();config['cancel']();MarineMap.actions.utils.restoreMapToolbar();}}]);MarineMap.app.map.map.events.clearMouseCache();MarineMap.app.map.addListener('GeometryCreated',MarineMap.actions.utils.geometryCreatedCallback,{remove:MarineMap.actions.utils.geometryCreatedCallback,clipSuccess:clipSuccess,clipError:clipError,clipFail:clipFail});}}};MarineMap.actions.utils.geometryCreatedCallback=function(geometry){MarineMap.actions.utils.restoreMapToolbar();MarineMap.app.map.removeListener('GeometryCreated',this.remove,this);MarineMap.actions.async.clipGeometry({geometry:geometry,success:this.clipSuccess,error:this.clipError,fail:this.clipFail});};MarineMap.actions.createArray=new Ext.Action({text:'Create Array',iconCls:'add-icon',handler:function(target,e){MarineMap.actions.nonExt.createOrModifyArray();},tooltip:'Create a new Array of Marine Protected Areas.'});MarineMap.actions.utils.setUser=function(json){MarineMap.app.userManager.setUser(new MarineMap.data.mlpaFeatures.User(json));}
MarineMap.actions.help=new Ext.Action({text:'Help',handler:function(target,e){if(!MarineMap.app.helpWindow){MarineMap.app.helpWindow=new Ext.Window({id:'windowSplash',closeAction:'hide',width:650,items:[new Ext.TabPanel({deferredRender:false,labelWidth:75,height:465,activeTab:0,border:false,items:[MarineMap.app.splashScreen=new MarineMap.widgets.URLViewer({url:MarineMap.urls.splash,title:'Introduction',autoScroll:true}),MarineMap.app.tutorialScreen=new MarineMap.widgets.URLViewer({url:MarineMap.urls.tutorials,title:'Screencasts'}),MarineMap.app.faq=new MarineMap.widgets.URLViewer({url:MarineMap.urls.faq,title:'FAQ',autoScroll:true})]})]});}
MarineMap.app.helpWindow.show();},iconCls:'blist',tooltip:'Show Help Window'});MarineMap.actions.login=new Ext.Action({text:'Login',handler:function(target,e){var w=new Ext.Window({closable:false,modal:true,width:380,items:[new MarineMap.widgets.LoginForm()]});MarineMap.actions.currentLoginWindow=w;w.show();},tooltip:'Log in to MarineMap'});MarineMap.actions.logout=new Ext.Action({text:'Logout',handler:function(target,e){Ext.Ajax.request({url:MarineMap.urls.logout,success:function(){MarineMap.app.userManager.setUser(null);},failure:function(){}});},tooltip:'Log out of MarineMap'});MarineMap.actions.resetPassword=new Ext.Action({text:'Reset Password',handler:function(target,e){var w=new Ext.Window({closable:false,modal:true,width:380,items:[new MarineMap.widgets.PasswordResetForm()]});w.show();},tooltip:'Email me my password'});MarineMap.actions.changePassword=new Ext.Action({text:'Change Password',handler:function(target,e){var w=new Ext.Window({closable:false,modal:true,width:380,items:[new MarineMap.widgets.PasswordChangeForm()]});w.show();},tooltip:'Change my password'});MarineMap.actions.userPrefsDropdown=new Ext.Action({text:'UserPrefs',tooltip:'Modify user preferences',user:null});MarineMap.actions.drawMPA=new Ext.Action({text:'Create MPA',iconCls:'add-icon',handler:function(target,e){MarineMap.actions.utils.askUserToDefineGeometry({finish:function(geometry,clipped){mlpa.mpaForm.show({geometries:[geometry,clipped],success:function(mpa){MarineMap.app.reportsVisor.update();MarineMap.actions.utils.enableComponents();MarineMap.app.clientStore.add(mpa);MarineMap.app.selectionManager.setSelectedFeature(mpa);MarineMap.ui.modal.hide(false,true);MarineMap.actions.openMpaAttributes.execute({mpa:mpa});},cancel:function(){MarineMap.actions.utils.enableComponents();},error:function(response){MarineMap.ui.error.show({errorText:'There was a problem saving your new MPA. This error will show up in our logs, but if the problem persists please follow up with an administrator.',logText:'Error saving new MPA'});MarineMap.actions.utils.enableComponents();}});},cancel:function(){MarineMap.actions.utils.enableComponents();}});}});MarineMap.actions.handlers={};MarineMap.actions.enterMPAGeometryEditMode=new Ext.Action({text:'Edit Geometry',iconCls:'editGeo',handler:function(target,e){var mpa=target.mpa;if(mpa.editable!=true){alert('This is a read-only MPA that cannot be edited or deleted.');return;}
if(mpa.user!=MarineMap.app.userManager.user.pk){alert('You cannot edit the geometry of an MPA that does not belong to you.');return;}
MarineMap.app.map.removeMPAs([mpa]);MarineMap.actions.utils.askUserToDefineGeometry({geometry:mpa.feature.attributes.original_geometry,finish:function(geometry,clipped){MarineMap.ui.wait.show({msg:'While we save your geometry changes'});mpa.saveGeometryChanges(geometry,clipped,{success:function(mpa){MarineMap.ui.wait.hide();MarineMap.actions.utils.enableComponents();MarineMap.app.clientStore.add(mpa);MarineMap.app.selectionManager.setSelectedFeature(mpa);},error:function(request,textStatus,errorThrown){MarineMap.ui.error.show({errorText:'Problem saving your geometry',debugText:request.responseText,logText:'Problem saving geometry changes.'});MarineMap.actions.utils.enableComponents();}});},cancel:function(){MarineMap.actions.utils.enableComponents();MarineMap.app.map.addMPAs([mpa]);}});}});MarineMap.actions.englishMeasurements=new Ext.Action({text:'miles',enableToggle:true,pressed:true,toggleGroup:'measurements',tooltip:'Measure in feet / miles (English/imperial units)',toggleHandler:function(target,enabled){if(enabled){var controlToolbar=Ext.getCmp('mt1');for(i=0;i<controlToolbar.controls.length;i++){if(controlToolbar.controls[i].CLASS_NAME="OpenLayers.Control.Measure"){controlToolbar.controls[i].displaySystem="english";}}}}});MarineMap.actions.metricMeasurements=new Ext.Action({text:'kilometers',enableToggle:true,toggleGroup:'measurements',tooltip:'Measure in meters / kilometers (metric units)',toggleHandler:function(target,enabled){if(enabled){var controlToolbar=Ext.getCmp('mt1');for(i=0;i<controlToolbar.controls.length;i++){if(controlToolbar.controls[i].CLASS_NAME="OpenLayers.Control.Measure"){controlToolbar.controls[i].displaySystem="metric";}}}}});MarineMap.actions.openMpaAttributes=new Ext.Action({text:'Full Info',iconCls:'attributes',handler:function(target,e){var pk=target.mpa.pk;var url=MarineMap.urls.mpaAttributes+pk;if(target['saved']){url=url+"?saved=True";}
MarineMap.ui.modal.show({width:500,url:url,waitMsg:'while we retrieve information for this MPA.',afterRender:function(){$('li.editmpa a').bindButton(function(e){MarineMap.actions.nonExt.editMpaAttributes(e);},{mpa:target.mpa});$('li.deletempa a').bindButton(MarineMap.actions.nonExt.deleteMPA,{mpa:target.mpa});}});}});MarineMap.actions.nauticalMeasurements=new Ext.Action({text:'nautical miles',enableToggle:true,toggleGroup:'measurements',tooltip:'Measure in nautical miles',toggleHandler:function(target,enabled){if(enabled){var controlToolbar=Ext.getCmp('mt1');for(i=0;i<controlToolbar.controls.length;i++){if(controlToolbar.controls[i].CLASS_NAME="OpenLayers.Control.Measure"){controlToolbar.controls[i].displaySystem="nautical";}}}}});MarineMap.actions.nonExt={};MarineMap.actions.nonExt.editMpaAttributes=function(e){$(this).unbind('click');var mpa=e.data.mpa;if(mpa.editable!=true){alert('This is a read-only MPA that cannot be edited or deleted.');return;}
mlpa.mpaForm.show({editUrl:mpa.editUrl(),success:function(new_mpa){MarineMap.ui.modal.hide(false,true);MarineMap.app.clientStore.add(new_mpa);MarineMap.app.selectionManager.setSelectedFeature(new_mpa);},error:function(response){MarineMap.ui.error.show({errorText:'There was a problem saving your MPA attributes. Please try again.',logText:'Problem saving mpa attributes.'});},cancel:function(){}});}
MarineMap.actions.nonExt.deleteMPA=function(e){var mpa=e.data.mpa;if(mpa.editable!=true){alert('This is a read-only MPA that cannot be edited or deleted.');return;}
var answer=confirm('Are you sure you want to delete this MPA?');if(answer){MarineMap.ui.modal.hide(false,true);$(this).unbind('click');$.ajax({url:MarineMap.urls.deleteMPA+mpa.pk,type:'POST',success:function(){MarineMap.app.clientStore.remove(mpa);},error:MarineMap.actions.defaultErrorHandler});}else{}}
MarineMap.actions.nonExt.deleteArray=function(array){var answer=confirm('Are you sure you want to delete this Array? MPAs that you have created will be retained and put back into your MPA list.');if(answer){$(this).unbind('click');$.ajax({data:{pk:array.pk},url:MarineMap.urls.deleteArray,type:'POST',dataType:'json',success:function(data){MarineMap.ui.modal.hide(false,true);MarineMap.app.selectionManager.clearSelection();var remove=array.get_mpas();remove.push(array);MarineMap.app.clientStore.remove(remove);if(data&&data.length){var mpas=[];for(var i=0;i<data.length;i++){var mpa=MarineMap.data.mlpaFeatures.mpa_from_geojson(data[i]);mpas.push(mpa);}
MarineMap.app.clientStore.add(mpas);}else{}},error:MarineMap.actions.defaultErrorHandler});}else{}};MarineMap.actions.nonExt.deleteArrayAndMpas=function(array){var answer=confirm('Are you sure you want to delete this Array? THIS ACTION WILL DELETE ALL MPAs IN THIS ARRAY!');if(answer){var answer=confirm('Are you still sure? (Sorry for the redundancy, we just want to prevent any mistakes.)');if(answer){$(this).unbind('click');MarineMap.ui.modal.hide(false,true);$.ajax({data:{pk:array.pk},url:'/marinemap/array/delete-all/',type:'POST',dataType:'json',success:function(data){MarineMap.app.selectionManager.clearSelection();var mpas=array.get_mpas();mpas.push(array);MarineMap.app.clientStore.remove(mpas);},error:MarineMap.actions.defaultErrorHandler});}}};MarineMap.actions.nonExt.addMpasToInterface=function(mpas){MarineMap.app.reportsVisor.update();var store=Ext.getCmp('maptoolbar').mlpaFeaturesMenu.MPAStore;for(var i=0;i<mpas.length;i++){store.add(mpas[i]);}
store.sort('name');}
MarineMap.actions.nonExt.addArrayMpasToMap=function(array){return MarineMap.app.mapToolbar.mlpaFeaturesMenu.addArrayMpas(array);}
MarineMap.actions.async={};MarineMap.actions.async.clipGeometry=function(config){MarineMap.ui.wait.show({msg:'while we validate your geometry'});if(config['geometry']&&config['error']&&config['fail']&&config['success']){Ext.Ajax.request({url:MarineMap.urls.validateGeometry,method:'POST',disableCachingParam:true,params:'geometry='+config['geometry'].toString(),success:function(response,opts){MarineMap.ui.wait.hide();var text=response.responseText;var json=eval('('+text+')');var status_code=parseFloat(json['status_code']);if(status_code==1||status_code==0||status_code==5){var geometry=json['original_geom'];var clipped_geometry=json['clipped_mpa_geom'];config['success'](status_code,geometry,clipped_geometry);}else if(status_code!=4){config['error'](status_code,config['geometry']);}else{config['fail'](response,opts);}},failure:function(response,opts){MarineMap.ui.wait.hide();config['fail'](response,opts);}});}else{MarineMap.ui.error.show({errorText:'MarineMap client is improperly configured to handle this action. Please contact an administrator.',logText:'MarineMap.actions.async.clipGeometry was called with improper attributes'});}};MarineMap.actions.nonExt.createOrModifyArray=function(pk){MarineMap.app.selectionManager.clearSelection();var url='/marinemap/arrays/';if(pk){url=url+pk+'/edit/';}else{url=url+'create/';}
MarineMap.ui.form.show(url,function(json){var data=MarineMap.data.mlpaFeatures.array_and_mpas_from_geojson(json);var array=data[0];var mpas=data[1];mpas.push(array);MarineMap.app.clientStore.add(mpas);MarineMap.ui.wait.hide();MarineMap.app.selectionManager.setSelectedFeature(array);});};MarineMap.actions.nonExt.openUserInfo=function(user){MarineMap.ui.modal.show({width:300,url:'/marinemap/user/'+user.pk,waitMsg:'while we retrieve information for this user.'});};MarineMap.actions.nonExt.openArrayBasicInfo=function(pk){MarineMap.ui.modal.show({width:500,url:'/marinemap/array/'+pk,waitMsg:'while we retrieve information for this Array.'});};MarineMap.actions.nonExt.openTreeTutorial=function(pk){MarineMap.ui.modal.show({width:500,url:'/marinemap/tree_tutorial'});};MarineMap.actions.nonExt.copyMpa=function(pk){MarineMap.ui.wait.show({waitMsg:'While we copy this Marine Protected Area'});$.ajax({url:'/marinemap/mpa/copy/',type:'POST',data:{pk:pk},success:function(data){var mpa=MarineMap.data.mlpaFeatures.mpa_from_geojson(data);MarineMap.ui.wait.hide();MarineMap.app.clientStore.add(mpa);MarineMap.app.selectionManager.setSelectedFeature(mpa);},error:function(XMLHttpRequest,textStatus,errorThrown){if(XMLHttpRequest.status==401){MarineMap.ui.error.show({errorText:'You must be logged in to perform this operation.'});}else if(XMLHttpRequest.status==403){MarineMap.ui.error.show({errorText:'You do not have permission to copy this object.'});}else if(XMLHttpRequest.status==404){MarineMap.ui.error.show({errorText:'The object you are trying to copy does not exist.'});}else{MarineMap.ui.error.show({errorText:'An unknown server error occured. Please try again later.'});}},dataType:'json'});};MarineMap.actions.nonExt.copyArray=function(pk){var answer=confirm('By copying an Array, all member MPAs will also be copied and assigned to you so that you can edit them. The Array will recieve the same name + "_copy" added to the end, and will be added to your Marine Protected Areas listing. This may take a moment, please be patient and give your computer a minute to load the new MPAs.');if(answer){MarineMap.ui.wait.show({waitMsg:'While we copy this Marine Protected Area'});$.ajax({url:'/marinemap/array/copy/',type:'POST',data:{pk:pk},success:function(json){var data=MarineMap.data.mlpaFeatures.array_and_mpas_from_geojson(json);var array=data[0];var mpas=data[1];mpas.push(array);MarineMap.app.clientStore.add(mpas);MarineMap.ui.wait.hide();MarineMap.app.selectionManager.setSelectedFeature(array);},error:function(XMLHttpRequest,textStatus,errorThrown){if(XMLHttpRequest.status==401){MarineMap.ui.error.show({errorText:'You must be logged in to perform this operation.'});}else if(XMLHttpRequest.status==403){MarineMap.ui.error.show({errorText:'You do not have permission to copy this object.'});}else if(XMLHttpRequest.status==404){MarineMap.ui.error.show({errorText:'The object you are trying to copy does not exist.'});}else{MarineMap.ui.error.show({errorText:'An unknown server error occured. Please try again later.'});}},dataType:'json'});}};MarineMap.actions.setupEconomicAnalysis=function(){$.ajax({url:'/marinemap/econ_analysis/available/',type:'GET',success:function(user_groups){MarineMap.data.FisheryImpactAnalysisUserGroups=user_groups;MarineMap.app.FisheryImpactAnalysisSelector=new MarineMap.widgets.FisheryImpactAnalysisSelectorWindow();},error:function(XMLHttpRequest,textStatus,errorThrown){if(XMLHttpRequest.status==400){MarineMap.ui.error.show({errorText:'You must use a GET request.'});}else if(XMLHttpRequest.status==401){MarineMap.ui.error.show({errorText:'You must be logged in to perform this operation.'});}else if(XMLHttpRequest.status==403){MarineMap.ui.error.show({errorText:'You do not have permission to analyze this mpa'});}else if(XMLHttpRequest.status==404){MarineMap.ui.error.show({errorText:'That mpa does not exist'});}else{MarineMap.ui.error.show({errorText:'An unknown server error occured. Please try again later.'});}},dataType:'json'});};MarineMap.actions.openEconomicAnalysis=function(selectedFeature){MarineMap.app.FisheryImpactAnalysisSelector.setMPA(selectedFeature.pk);MarineMap.app.FisheryImpactAnalysisSelector.show();};MarineMap.actions.openStaffSummary=function(arrayId){MarineMap.actions.openUrl('/marinemap/array/staffsummary/'+arrayId);}
MarineMap.actions.openSpacingMatrixCSV=function(arrayId){MarineMap.actions.openUrl('/marinemap/array/spacingmatrix/'+arrayId);}
MarineMap.actions.openArrayReplication=function(arrayId){MarineMap.actions.openUrl('/marinemap/report/array/replication/'+arrayId);}
MarineMap.actions.openHabitatPauloFormat=function(arrayId){MarineMap.actions.openUrl('/marinemap/report/array/habitat/antiquated/'+arrayId);}
MarineMap.actions.openUrl=function(url){window.onbeforeunload=null;window.open(url);window.onbeforeunload=MarineMap.backWarn;return false;}
MarineMap.actions.defaultErrorHandler=function(XMLHttpRequest,textStatus,errorThrown){if(XMLHttpRequest.status==401){MarineMap.ui.error.show({errorText:'You must be logged in to perform this operation.'});}else if(XMLHttpRequest.status==403){MarineMap.ui.error.show({errorText:'You do not have permission to modify this object.'});}else if(XMLHttpRequest.status==404){MarineMap.ui.error.show({errorText:'This object cannot be found in the database.'});}else{MarineMap.ui.error.show({errorText:'An unknown server error occured. Please try again later.'});}}
MarineMap.actions.openAttributesCSV=function(arrayId){window.onbeforeunload=null;window.open('/marinemap/array/csv/'+arrayId);window.onbeforeunload=MarineMap.backWarn;}
OpenLayers.Control.Identify=OpenLayers.Class(OpenLayers.Control,{EVENT_TYPES:['identify'],handleRightClicks:false,initialize:function(options){this.EVENT_TYPES=OpenLayers.Control.Identify.prototype.EVENT_TYPES.concat(OpenLayers.Control.prototype.EVENT_TYPES);this.handlers={};var clickCallbacks={'click':this.defaultSingleClick,'dblclick':this.defaultSingleClick};var clickOptions={'single':true,'double':true,'stopSingle':true,'stopDouble':true};this.handlers.click=new OpenLayers.Handler.Click(this,clickCallbacks,clickOptions);this.handlers.click.setMap(Ext.getCmp('map').map);OpenLayers.Control.prototype.initialize.apply(this,arguments);},destroy:function(){this.deactivate();},activate:function(){this.handlers.click.activate();return OpenLayers.Control.prototype.activate.apply(this,arguments);},deactivate:function(){this.handlers.click.deactivate();return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},defaultSingleClick:function(evt){this.events.triggerEvent('identify',{xy:this.map.getLonLatFromViewPortPx(evt.xy)});},CLASS_NAME:"OpenLayers.Control.Identify"});OpenLayers.Geometry.Point.prototype.distanceTo=function(point){var distance=0.0;var transformedThis=this.clone();var transformedPoint=point.clone();var sourceProj=MarineMap.config.projection;var destProj=MarineMap.config.equalAreaProjection;transformedThis.transform(sourceProj,destProj);transformedPoint.transform(sourceProj,destProj);if((transformedThis.x!=null)&&(transformedThis.y!=null)&&(transformedPoint!=null)&&(transformedPoint.x!=null)&&(transformedPoint.y!=null)){var dx2=Math.pow(transformedThis.x-transformedPoint.x,2);var dy2=Math.pow(transformedThis.y-transformedPoint.y,2);distance=Math.sqrt(dx2+dy2);}
return distance;};OpenLayers.Geometry.LinearRing.prototype.getArea=function(){var area=0.0;if(this.components&&(this.components.length>2)){var sourceProj=MarineMap.config.projection;var destProj=MarineMap.config.equalAreaProjection;var sum=0.0;for(var i=0,len=this.components.length;i<len-1;i++){var b=this.components[i].clone();b.transform(sourceProj,destProj);var c=this.components[i+1].clone();c.transform(sourceProj,destProj);sum+=(b.x+c.x)*(c.y-b.y);}
area=-sum/2.0;}
return area;};OpenLayers.Control.Measure.prototype.displaySystemUnits={geographic:['dd'],english:['mi','ft','in'],metric:['km','m'],nautical:['nmi']};OpenLayers.Control.MousePosition.prototype.formatCoords=function(base){var sign='';if(base<0)
sign='-';var abs_base=Math.abs(base);var t,t2;var minute_pad='';var degrees=Math.floor(abs_base);t=(abs_base-degrees)*60;var minutes=t;if(minutes<10)
minute_pad='0';return(sign+degrees+"\u00B0 "+minute_pad+minutes.toFixed(3)+"\u0027 ");};OpenLayers.Control.MousePosition.prototype.formatOutput=function(lonLat){var newHtml=this.formatCoords(lonLat.lat)+this.separator+this.formatCoords(lonLat.lon);return newHtml;};Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.Map=Ext.extend(mapfish.widgets.MapComponent,{id:'map',layout:'fit',region:'center',border:false,buttonAlign:'right',baseToggled:false,initComponent:function(){OpenLayers.IMAGE_RELOAD_ATTEMPTS=3;OpenLayers.Tile.Image.useBlankTile=true;OpenLayers.Util.onImageLoadError=function(){};this.balloonTemplate=tmpl(['<div class="mpaPopup" style="width:225px;height:6em;">','<a class="closePopup" href="#" onclick="MarineMap.app.selectionManager.clearSelection();"><img src="/marinemap/media/images/silk/icons/cancel.png" /></a>','<h3><%= mpa.name.length > 23 ? mpa.name.substr(0, 23) + "..." : mpa.name %></h3>','<p class="creator">created by <%= mpa.get_user().name %> on <%= new Date(mpa.date_created).format("m/d/y") %></p>','<p class="designation"><img style="background-color:<%= mpa.feature.attributes.fillColor %>;" width="15" height="10" src="/marinemap/media/js/extjs/resources/images/default/s.gif" /> <%= mpa.get_designation() != null ? mpa.get_designation().name : "No designation" %></p>','<div id="popupToolbarSpace">&nbsp;</div>','</div>'].join(''));this.wktParser=new OpenLayers.Format.WKT();var self=this;$(this.userManager).bind('change',function(e,user,oldUser){self.clearFeatures();});$(this.store).bind('removed',function(e,items){if(items['mpa']&&items['mpa'].length){for(var i=0;i<items['mpa'].length;i++){var mpa=items['mpa'][i];if(mpa.feature&&self.vectorLayer.getFeatureById(mpa.feature.id)){self.destroyMPAs([mpa]);}}}});$(this.store).bind('updated',function(e,items){self.deselectAllMPAs();self.hideMPAPopup();if(items['mpa']&&items['mpa'].length){var add=[];for(var i=0;i<items['mpa'].length;i++){var mpa=items['mpa'][i][0];var old_mpa=items['mpa'][i][1];add.push(mpa);}
self.addMPAs(add);}});this.on("bodyresize",function(){var x=(Ext.Element(this.contentEl).getWidth()/2)-30;this.panzoom.position=new OpenLayers.Pixel(x,15);this.panzoom.redraw();},this);var styleMap=new OpenLayers.StyleMap({'default':new OpenLayers.Style({fillColor:'${fillColor}',fillOpacity:0.4,strokeColor:'${strokeColor}',strokeOpacity:1,strokeWidth:1,cursor:'pointer'}),'select':new OpenLayers.Style({strokeWidth:3,fillColor:'${fillColor}',strokeColor:'yellow',strokeOpacity:1,fillOpacity:0.4,cursor:'default'}),'temporary':new OpenLayers.Style({fillColor:'red'})});this.vectorLayer=new OpenLayers.Layer.Vector('mlpaFeatures',{styleMap:styleMap});this.map.addLayers([MarineMap.data.GoogleTerrain,MarineMap.data.GoogleSat,this.vectorLayer]);this.clippedGeometryPreview=null;this.panzoom=new OpenLayers.Control.PanZoomBar();var x=(Ext.Element(this.contentEl).getWidth()/2)-30;this.panzoom.position=new OpenLayers.Pixel(x,15);this.map.addControl(this.panzoom);this.map.events.register("zoomend",this,this.toggleBase);this.map.events.register("click",this,function(){this.selectionManager.clearSelection();});this.drawMPAControl=new OpenLayers.Control.DrawFeature(this.vectorLayer,OpenLayers.Handler.Polygon,{featureAdded:this.handleDrawMPA,handlerOptions:{options:{scope:this}}});this.map.addControl(this.drawMPAControl);this.map.addControl(new OpenLayers.Control.MousePosition());this.map.addControl(new OpenLayers.Control.MouseDefaults());this.map.addControl(new OpenLayers.Control.ZoomBox());this.map.zoomToExtent(this.studyRegion.extent());MarineMap.widgets.Map.superclass.initComponent.apply(this,arguments);var self=this;this.over=null;this.selectControl=new OpenLayers.Control.SelectFeature(this.vectorLayer,{multiple:true,clickout:true,callbacks:{'click':function(feature){self.selectionManager.setSelectedFeature(feature.attributes.mpa,self);feature.attributes.mpa.selectedOnMap=true;},'clickout':function(feature){if(self.over==null){self.selectionManager.clearSelection(self);}else{}
feature.attributes.mpa.selectedOnMap=false;},'over':function(feature){self.over=feature;},'out':function(feature){self.over=null;}}});$(this.selectionManager).bind('selectionChange',function(e,sm,selected,old,caller){self.selectItem(selected,caller);});this.map.addControl(this.selectControl);this.selectControl.activate();this.editVectorLayer=new OpenLayers.Layer.Vector('editFeature');this.editSelectControl=new OpenLayers.Control.SelectFeature(this.editVectorLayer,{clickout:false,multiple:false,toggle:false});this.modifyControl=new OpenLayers.Control.ModifyFeature(this.editVectorLayer,{selectControl:this.editSelectControl});this.map.addLayer(this.editVectorLayer);this.map.addControl(this.modifyControl);this.map.addControl(this.editSelectControl);this.map.extCmp=this;},selectItem:function(selected,caller){var self=this;if(selected!=null&&selected.model=='mpa'){selected.callWithFeature(function(){self.showMPAPopup(selected)});}else{this.hideMPAPopup();}
if(caller!=this){if(selected){if(selected.model=='mpa'){this.deselectAllMPAs();selected.callWithFeature(function(mpa,feature){self.selectMPA(mpa);});}else{this.deselectAllMPAs();selected.callWithFeature(function(array){array.each_mpa(function(mpa){if(self.vectorLayer.getFeatureById(mpa.feature.id)){self.selectMPA(mpa);}else{}});});}}else{this.deselectAllMPAs();}}},deselectAllMPAs:function(){var remove=[];for(var i=0;i<this.vectorLayer.selectedFeatures.length;i++){remove.push(this.vectorLayer.selectedFeatures[i].attributes.mpa);}
for(var i=0;i<remove.length;i++){this.deselectMPA(remove[i]);}},selectMPA:function(mpa){if(!mpa.selectedOnMap){this.selectControl.select(mpa.feature);mpa.selectedOnMap=true;}},deselectMPA:function(mpa){if(mpa.selectedOnMap){this.selectControl.unselect(mpa.feature);mpa.selectedOnMap=false;}},toggleBase:function(){var new_zoom_level=this.map.getZoom()+MarineMap.data.MIN_ZOOM_LEVEL;if(this.baseSatOn){return;}
if(new_zoom_level>MarineMap.data.TERRAIN_MAX_ZOOM_LEVEL){this.map.setBaseLayer(MarineMap.data.GoogleSat);}else{this.map.setBaseLayer(MarineMap.data.GoogleTerrain);}},showMPAPopup:function(mpa){if(mpa.model!='mpa'){throw('oh crap not an mpa',mpa);}
html=this.balloonTemplate({mpa:mpa});ll=mpa.feature.geometry.getBounds().getCenterLonLat();var callback=function(feature){this.map.extCmp.selectControl.unselectAll();};this.popup=new OpenLayers.Popup.Anchored("mpaPopup",ll,null,html,null,false);this.popup.panMapIfOutOfView=false;this.popup.autoSize=true;this.popup.padding=0;if(!mpa.feature.onScreen(true)){this.map.setCenter(mpa.feature.geometry.getBounds().getCenterLonLat());}
this.map.addPopup(this.popup,true);var full=new Ext.Button(MarineMap.actions.openMpaAttributes);full.mpa=mpa;var geoedit=new Ext.Button(MarineMap.actions.enterMPAGeometryEditMode);geoedit.mpa=mpa;items=[full];if(this.userManager.user&&mpa.user==this.userManager.user.pk){items.push(geoedit);}
items.push({xtype:'tbtext',text:'<a onmouseover="window.onbeforeunload = null;" onmouseout="window.onbeforeunload = MarineMap.backWarn;" class="marinemap-button kml" href="/marinemap/kml/mpa/'+mpa.pk+'">kml</a>'});var bbar=new Ext.Toolbar({id:'popupTbar',items:items,renderTo:'mpaPopup'});bbar.show();},hideMPAPopup:function(feature){if(this.popup){this.map.removePopup(this.popup);this.popup=null;}},zoomIn:function(){this.map.zoomIn();},zoomOut:function(){this.map.zoomOut();},handleDrawMPA:function(feature,opts){MarineMap.app.map.newFeature=feature;this.deactivate();feature.layer.removeFeatures([feature]);MarineMap.app.map.fireEvent('GeometryCreated',feature.geometry);},startDrawMPA:function(){this.deselectAllMPAs();this.drawMPAControl.activate();},cancelDrawMPA:function(){this.drawMPAControl.deactivate();},addDataLayer:function(layer){if(layer instanceof OpenLayers.Layer.Google){this.baseSatOn=true;this.map.setBaseLayer(MarineMap.data.GoogleSat);this.setWidth(this.getSize().width+1);this.setWidth(this.getSize().width-1);}else{this.map.addLayer(layer);}},removeDataLayer:function(layer){if(layer instanceof OpenLayers.Layer.Google){this.baseSatOn=false;this.map.setBaseLayer(MarineMap.data.GoogleTerrain);}else{this.map.removeLayer(layer);}},addMPAs:function(mpas){var self=this;for(var i=0;i<mpas.length;i++){mpas[i].callWithFeature(function(mpa,feature){self.vectorLayer.addFeatures([feature]);if(MarineMap.app.selectionManager.selectedFeature&&(mpa.pk==MarineMap.app.selectionManager.selectedFeature.pk||mpa.array==MarineMap.app.selectionManager.selectedFeature.pk)){self.selectMPA(mpa);if(MarineMap.app.selectionManager.selectedFeature.client_id==mpa.client_id){self.showMPAPopup(mpa);}}});}},removeMPAs:function(mpas){var self=this;this.hideMPAPopup();for(var i=0;i<mpas.length;i++){mpas[i].callWithFeature(function(mpa,feature){self.deselectMPA(mpa);self.vectorLayer.removeFeatures([feature]);});}},destroyMPAs:function(mpas){var self=this;this.hideMPAPopup();for(var i=0;i<mpas.length;i++){mpas[i].callWithFeature(function(mpa,feature){self.selectControl.unselect(mpa.feature);self.vectorLayer.destroyFeatures([feature]);});}},addClippedGeometryPreview:function(wkt){this.clearClippedGeometryPreview();this.clippedGeometryPreview=this.wktParser.read(wkt);this.clippedGeometryPreview.attributes={fillColor:'purple',strokeColor:'orange'};this.vectorLayer.addFeatures([this.clippedGeometryPreview]);this.selectControl.select(this.clippedGeometryPreview);bounds=this.clippedGeometryPreview.geometry.getBounds();this.map.panTo(bounds.getCenterLonLat());},clearClippedGeometryPreview:function(){if(this.clippedGeometryPreview){this.vectorLayer.removeFeatures(this.clippedGeometryPreview);this.clippedGeometryPreview=null;}else{}},addEditableGeometry:function(geometry){this.selectControl.deactivate();var feature;if(geometry instanceof OpenLayers.Feature.Vector){feature=geometry;}else{feature=this.wktParser.read(geometry);}
feature.id='featureforedit';this.editVectorLayer.addFeatures([feature]);this.editSelectControl.activate();this.modifyControl.activate();this.editSelectControl.select(feature);},finishGeometryEditing:function(){this.editSelectControl.unselectAll();this.modifyControl.deactivate();this.editSelectControl.deactivate();var feature=this.editVectorLayer.getFeatureById('featureforedit');var geo=feature.geometry;feature.layer.removeFeatures([feature]);this.selectControl.activate();return geo;},zoomToFeature:function(feature){if(feature['model']!='mpa'&&feature['model']!='array'){throw('zoomToFeature must be called with feature of type mpa or array');}
var self=this;feature.callWithFeature(function(){self._zoomToFeatureCallback(feature);});},_zoomToFeatureCallback:function(feature){var bounds=new OpenLayers.Bounds();if(feature['model']=='mpa'){bounds=feature.feature.geometry.getBounds();}else if(feature['model']=='array'){feature.each_mpa(function(mpa){if(!bounds){bounds=mpa.feature.geometry.getBounds();}else{bounds.extend(mpa.feature.geometry.getBounds());}});}
var center=bounds.getCenterLonLat();var zoom=this.map.getZoomForExtent(bounds);if(zoom>8){zoom=8;}
if(zoom>5){zoom=zoom-1;}
this.map.setCenter(center,zoom);},clearFeatures:function(feature){this.vectorLayer.removeFeatures(this.vectorLayer.features);}});Ext.reg('marinemap-widgets-map',MarineMap.widgets.Map);Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.ControlToolbar=Ext.extend(mapfish.widgets.toolbar.Toolbar,{onRender:function(){MarineMap.widgets.ControlToolbar.superclass.onRender.apply(this,arguments);this.addControl(new OpenLayers.Control.Navigation({isDefault:true}),{iconCls:'pan-icon',toggleGroup:'map1',tooltip:'Pan'});this.add(new Ext.Toolbar.Spacer());this.addControl(new OpenLayers.Control.ZoomBox({out:false}),{iconCls:'zoom-icon',toggleGroup:'map1',tooltip:'Zoom In'});this.add(new Ext.Toolbar.Spacer());var ident_control=new OpenLayers.Control.Identify({});ident_control.events.on({"activate":this.loadIdentify,"deactivate":this.unloadIdentify,"identify":this.startIdentify,scope:this});this.addControl(ident_control,{iconCls:'identify-icon',toggleGroup:'map1',tooltip:'Identify Features'});var options={handlerOptions:{persist:true},displaySystem:'english'};var measureDistControl=new OpenLayers.Control.Measure(OpenLayers.Handler.Path,options);measureDistControl.events.on({"measure":this.handleMeasurements,"measurepartial":this.handleMeasurements,"activate":this.activateMeasurements,"deactivate":this.deactivateMeasurements,scope:this});this.add(new Ext.Toolbar.Spacer());this.addControl(measureDistControl,{iconCls:'chart-line-icon',toggleGroup:'map1',tooltip:'Measure Distance'});var measureAreaControl=new OpenLayers.Control.Measure(OpenLayers.Handler.Polygon,options);measureAreaControl.events.on({"measure":this.handleMeasurements,"measurepartial":this.handleMeasurements,"activate":this.activateMeasurements,"deactivate":this.deactivateMeasurements,scope:this});this.add(new Ext.Toolbar.Spacer());this.addControl(measureAreaControl,{iconCls:'chart-bar-icon',toggleGroup:'map1',tooltip:'Measure Area'});},handleMeasurements:function(event){var geometry=event.geometry;var units=event.units;var order=event.order;var measure=event.measure;var out="";if(order==1){out+="Distance: "+measure.toFixed(3)+" "+units;}else{out+="Area: "+measure.toFixed(3)+" "+units+"<sup>2</"+"sup>";}
this.measure_win.body.update(out);},activateMeasurements:function(){if(!this.measure_win){var button_english=new Ext.Button(MarineMap.actions.englishMeasurements);var button_metric=new Ext.Button(MarineMap.actions.metricMeasurements);var button_nautical=new Ext.Button(MarineMap.actions.nauticalMeasurements);this.measure_win=new Ext.Window({title:'Measurement Tool',html:'Click the map to begin measuring.',height:80,width:200,resizable:false,closable:true,closeAction:'hide',x:139,y:30,bbar:[button_english,button_metric,button_nautical]});this.measure_win.addListener("hide",this.cleanupMeasureWin,this);this.activate_count=0;}
else
{this.measure_win.body.update('Click the map to begin measuring.');}
this.activate_count++;this.measure_win.show();},deactivateMeasurements:function(){if(this.measure_win){this.activate_count--;if(this.activate_count==0){this.measure_win.hide();}}else{this.activate_count=0;}},cleanupMeasureWin:function(){if(this.activate_count>0){this._buttons[0].toggle();}},loadIdentify:function(){if(this.tree){this.ident_win.remove(this.tree);this.tree.destroy();this.tree=null;}
if(!this.ident_win){this.ident_win=new MarineMap.widgets.IdentifyWindow();this.ident_win.addListener("hide",this.cleanupIdentWin,this);}
this.ident_win.show();},startIdentify:function(evt){this.xy=evt.xy;var size=new OpenLayers.Size(20,34);var offset=new OpenLayers.Pixel(-(size.w/2),-size.h);var icon=new OpenLayers.Icon('http://boston.openguides.org/markers/AQUA.png',size,offset);var marker=new OpenLayers.Marker(this.xy,icon);var map_widget=MarineMap.app.map;if(map_widget.markerLayer){MarineMap.app.map.markerLayer.destroy();}
map_widget.markerLayer=new OpenLayers.Layer.Markers('identifyMarker');map_widget.map.addLayer(map_widget.markerLayer);map_widget.markerLayer.addMarker(marker);this.xy.transform(MarineMap.config.projection,MarineMap.config.equalAreaProjection);var x_top=this.xy.lat+MarineMap.config.identifyBboxRadius;var y_left=this.xy.lon-MarineMap.config.identifyBboxRadius;var x_bottom=this.xy.lat-MarineMap.config.identifyBboxRadius;var y_right=this.xy.lon+MarineMap.config.identifyBboxRadius;if(this.tree){this.ident_win.remove(this.tree);this.tree.destroy();this.tree=null;}
this.tree=new Ext.tree.ColumnTree({rootVisible:false,autoScroll:true,columns:[{header:'',width:260,dataIndex:'node_name'},{header:'Value',width:200,dataIndex:'value'}]});var the_root=new Ext.tree.TreeNode({text:'',dataUrl:MarineMap.data.SubDataLayers});this.tree.setRootNode(the_root);var data=MarineMap.data.SubDataLayers;var group_data=null;var group_node=null;var layer_data=null;var layer_node=null;var dm_store=Ext.getCmp('dataLayersMenu').store;var curr_group_name=null;var name_query=function(rec){return(rec.layerOn&&rec.get('name')==curr_group_name);};for(var i=0;i<data.length;i++){group_data=data[i];curr_group_name=group_data.node_name;var layer_recs=dm_store.queryBy(name_query,this);if(layer_recs.items.length>0){if(group_data.children.length==0){group_data.value="No queryable layers";}else{group_data.value="";}
group_node=new Ext.tree.TreeNode({node_name:group_data.node_name,uiProvider:Ext.tree.ColumnNodeUI,leaf:false,expanded:true,value:group_data.value});the_root.appendChild(group_node);for(var k=0;k<group_data.children.length;k++){layer_data=group_data.children[k];layer_node=new Ext.tree.TreeNode({node_name:layer_data.node_name,sde:layer_data.sde,shape_field:layer_data.shape_field,fields:layer_data.children,uiProvider:Ext.tree.ColumnNodeUI,leaf:false,expandable:true,top:x_top,left:y_left,bottom:x_bottom,right:y_right});layer_node.on("expand",this.doIdentify,this);group_node.appendChild(layer_node);}}}
this.ident_win.add(this.tree);this.ident_win.doLayout();},doIdentify:function(node){this.ident_win.show_load();var fields='';for(i=0;i<node.attributes.fields.length;i++){if(i!=0){fields+=',';}
fields+=node.attributes.fields[i].field;}
var wfs_params='request=GetFeature&version=1.0.0&typeName=sde:'+node.attributes.sde+'&outputFormat=JSON&propertyName='+fields+'&FILTER=<Filter xmlns="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml"><Intersects><PropertyName>'+node.attributes.shape_field+'</PropertyName><gml:Box srsName="EPSG:3310"><gml:coordinates>'+node.attributes.left+','+node.attributes.bottom+' '+node.attributes.right+','+node.attributes.top+'</gml:coordinates></gml:Box></Intersects></Filter>';Ext.Ajax.request({url:MarineMap.urls.geoserver+'?'+wfs_params,success:this.finishIdentify,failure:this.failIdentify,params:{self:this},scope:node});},finishIdentify:function(response){var res=Ext.util.JSON.decode(response.responseText);if(!res.features||res.features.length==0){var empty_node=new Ext.tree.TreeNode({node_name:'No Features Found',uiProvider:Ext.tree.ColumnNodeUI,leaf:true});this.appendChild(empty_node);Ext.getCmp('identify_win').hide_load();return;}
for(var i=0;i<res.features.length;i++){var feature=res.features[i];var feature_node=new Ext.tree.TreeNode({node_name:'Feature '+(i+1),uiProvider:Ext.tree.ColumnNodeUI,leaf:false,expandable:true});this.appendChild(feature_node);for(var j=0;j<this.attributes.fields.length;j++){var field=this.attributes.fields[j];feature_node.appendChild(new Ext.tree.TreeNode({node_name:field.node_name,value:feature.properties[field.field],uiProvider:Ext.tree.ColumnNodeUI,leaf:true}));}}
Ext.getCmp('identify_win').hide_load();},failIdentify:function(){Ext.Msg.alert("Identify query failed, please try again or notify an administrator");},unloadIdentify:function(evt){if(this.ident_win){this.ident_win.hide();}
if(MarineMap.app.map.markerLayer){MarineMap.app.map.markerLayer.destroy();}},cleanupIdentWin:function(){this._buttons[0].toggle();}});Ext.reg('marinemap-widgets-controltoolbar',MarineMap.widgets.ControlToolbar);MarineMap.widgets.IdentifyWindow=Ext.extend(Ext.Window,{id:'identify_win',title:'Identify Map Features',height:240,width:600,closable:true,closeAction:'hide',resizable:true,collapsible:false,initComponent:function(){Ext.apply(this,{x:60,y:100,layout:'fit',tbar:new Ext.StatusBar({id:'win-statusbar',defaultText:'To use, turn on data layers you want to query, click a location on the map, expand available sublayers',busyText:'Querying features...',hidden:false})});MarineMap.widgets.IdentifyWindow.superclass.initComponent.apply(this,arguments);},show_load:function(){var statusBar=Ext.getCmp('win-statusbar');statusBar.showBusy();},hide_load:function(){var statusBar=Ext.getCmp('win-statusbar');statusBar.clearStatus({anim:true,useDefaults:true});}});Ext.reg('MarineMap.widgets.IdentifyWindow',MarineMap.widgets.IdentifyWindow);MarineMap.widgets.MapToolWindow=Ext.extend(Ext.Window,{id:'map_tool_win',title:'',height:40,width:136,closable:false,resizable:false,initComponent:function(){var toolbar=new MarineMap.widgets.ControlToolbar({map:Ext.getCmp('map').map,configurable:false,id:'mt1'});Ext.apply(this,{x:0,y:30,layout:'fit',html:'some stuff goes here',tbar:toolbar});MarineMap.widgets.MapToolWindow.superclass.initComponent.apply(this,arguments);},onRender:function(){MarineMap.widgets.MapToolWindow.superclass.onRender.apply(this,arguments);}});Ext.reg('MarineMap.widgets.MapToolWindow',MarineMap.widgets.MapToolWindow);Ext.tree.ColumnTree=Ext.extend(Ext.tree.TreePanel,{lines:false,borderWidth:Ext.isBorderBox?0:2,cls:'x-column-tree',onRender:function(){Ext.tree.ColumnTree.superclass.onRender.apply(this,arguments);this.headers=this.body.createChild({cls:'x-tree-headers'},this.innerCt.dom);var cols=this.columns,c;var totalWidth=0;for(var i=0,len=cols.length;i<len;i++){c=cols[i];totalWidth+=c.width;this.headers.createChild({cls:'x-tree-hd '+(c.cls?c.cls+'-hd':''),cn:{cls:'x-tree-hd-text',html:c.header},style:'width:'+(c.width-this.borderWidth)+'px;'});}
this.headers.createChild({cls:'x-clear'});this.headers.setWidth(totalWidth);this.innerCt.setWidth(totalWidth);}});Ext.tree.ColumnNodeUI=Ext.extend(Ext.tree.TreeNodeUI,{focus:Ext.emptyFn,renderElements:function(n,a,targetNode,bulkRender){this.indentMarkup=n.parentNode?n.parentNode.ui.getChildIndent():'';var t=n.getOwnerTree();var cols=t.columns;var bw=t.borderWidth;var c=cols[0];var buf=['<li class="x-tree-node"><div ext:tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf ',a.cls,'">','<div class="x-tree-col" style="width:',c.width-bw,'px;">','<span class="x-tree-node-indent">',this.indentMarkup,"</span>",'<img src="',this.emptyIcon,'" class="x-tree-ec-icon x-tree-elbow">','<img src="',a.icon||this.emptyIcon,'" class="x-tree-node-icon',(a.icon?" x-tree-node-inline-icon":""),(a.iconCls?" "+a.iconCls:""),'" unselectable="on">','<a hidefocus="on" class="x-tree-node-anchor" href="',a.href?a.href:"#",'" tabIndex="1" ',a.hrefTarget?' target="'+a.hrefTarget+'"':"",'>','<span unselectable="on">',n.text||(c.renderer?c.renderer(a[c.dataIndex],n,a):a[c.dataIndex]),"</span></a>","</div>"];for(var i=1,len=cols.length;i<len;i++){c=cols[i];buf.push('<div class="x-tree-col ',(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">','<div class="x-tree-col-text">',(c.renderer?c.renderer(a[c.dataIndex],n,a):a[c.dataIndex]),"</div>","</div>");}
buf.push('<div class="x-clear"></div></div>','<ul class="x-tree-node-ct" style="display:none;"></ul>',"</li>");if(bulkRender!==true&&n.nextSibling&&n.nextSibling.ui.getEl()){this.wrap=Ext.DomHelper.insertHtml("beforeBegin",n.nextSibling.ui.getEl(),buf.join(""));}else{this.wrap=Ext.DomHelper.insertHtml("beforeEnd",targetNode,buf.join(""));}
this.elNode=this.wrap.childNodes[0];this.ctNode=this.wrap.childNodes[1];var cs=this.elNode.firstChild.childNodes;this.indentNode=cs[0];this.ecNode=cs[1];this.iconNode=cs[2];this.anchor=cs[3];this.textNode=cs[3].firstChild;}});Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.MapToolbar=Ext.extend(Ext.Toolbar,{dropdowns:[],onRender:function(){MarineMap.widgets.MapToolbar.superclass.onRender.apply(this,arguments);var text=this.addText('<span class="mmlogo"><a target="_blank" href="http://marinemap.org" class="mmlogo"><img src="'+Ext.BLANK_IMAGE_URL+'" width="50" height="50" /></a></span><span class="mmlogotext"><a target="_blank" href="http://marinemap.org" class="mmlogo">Marine<span class="map">MAP</span> Decision Support Tool</a></span>');text.restore=true;var fill=this.addFill();fill.restore=true;var self=this;var b=this.featuresMenu.getExtButton();b.restore=true;this.addItem(this.featuresMenu.getExtButton());this.dataLayersMenu=new MarineMap.widgets.DataLayersMenu({onAddMapLayer:this.onAddMapLayer,onRemoveMapLayer:this.onRemoveMapLayer});this.dataLayersMenu.restore=true;this.dropdowns.push(this.addItem(this.dataLayersMenu));var sep=this.addSeparator();sep.restore=true;this.loginButton=new Ext.Button(MarineMap.actions.login);this.addItem(this.loginButton);var config=MarineMap.actions.userPrefsDropdown.initialConfig;config['menu']=[MarineMap.actions.logout,MarineMap.actions.changePassword];config['restore']=true;this.userPrefDropDown=new Ext.SplitButton(config);this.userPrefDropDown.hide();this.addItem(this.userPrefDropDown);var h=this.addButton(MarineMap.actions.help);h.restore=true;var sp=this.addSeparator();sp.restore=true;this.dataLayersMenu.toggle(true);var self=this;$(this.userManager).bind('change',function(e,user,olduser){if(user==null&&olduser!=null){self.logout()}else if(user!=null){self.login(user.name,user.permission_ecotrust_data);}});},collapseMenus:function(skip){for(var i=0;i<this.dropdowns.length;i++){if(this.dropdowns[i]!=skip){this.dropdowns[i].toggle(false);}}
this.featuresMenu.getExtButton().toggle(false);},setState:function(state,userName,permissionEcotrustData){if(state=='logged in'){this.login(userName,permissionEcotrustData);}else{this.logout();}},login:function(userName,permissionEcotrustData){this.loginButton.hide();this.userPrefDropDown.setText(userName);this.userPrefDropDown.show();if(permissionEcotrustData){this.dataLayersMenu.store.loadData(MarineMap.data.EcotrustFishingImpactLayers,true);this.dataLayersMenu.store.sort('group','ASC');}},logout:function(){this.loginButton.show();this.userPrefDropDown.hide();this.dataLayersMenu.reinitLayers();}});Ext.reg('marinemap-widgets-maptoolbar',MarineMap.widgets.MapToolbar);Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.DropdownMenu=Ext.extend(Ext.Button,{toggleHandler:function(target,enabled){if(enabled){this.window.show(this.getEl());}else{this.window.hide();}},initComponent:function(){Ext.apply(this,{enableToggle:true,scope:this});MarineMap.widgets.DropdownMenu.superclass.initComponent.apply(this,arguments);this.window=new MarineMap.widgets.DropdownWindow({minimizable:true,animateTarget:this.id,button:this});this.window.show();this.window.hide();},onRender:function(){MarineMap.widgets.DropdownMenu.superclass.onRender.apply(this,arguments);}});Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.DropdownWindow=Ext.extend(Ext.Window,{layout:'fit',closable:false,draggable:true,hideCollapseTool:true,layoutConfig:{titleCollapse:true,animate:true,hideCollapseTool:true},width:300,constrain:true,height:400,listeners:{'minimize':function(w){w.button.toggle(false);}}});Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.DataLayersMenu=Ext.extend(MarineMap.widgets.DropdownMenu,{id:'dataLayersMenu',initComponent:function(){Ext.apply(this,{text:'Data Layers'});MarineMap.widgets.DataLayersMenu.superclass.initComponent.apply(this,arguments);},redrawLayers:function(){var num_recs=this.store.getCount();var curr_rec;new_index=0;for(i=num_recs-1;i>=0;i--)
{curr_rec=this.store.getAt(i);if(curr_rec.layerOn)
{layer=curr_rec.get('layer');MarineMap.app.map.map.setLayerIndex(layer,new_index);new_index=new_index+1;}}},turnOnDefaultLayers:function(){var default_on_query=function(rec){var on_default=rec.get('on_default');return(on_default===true);};var layer_recs=this.store.queryBy(default_on_query,this);var map=Ext.getCmp('map');for(var i=0;i<layer_recs.items.length;i++){map.addDataLayer(layer_recs.items[i].get('layer'));layer_recs.items[i].layerOn=true;}},reinitLayers:function(){var map=Ext.getCmp('map');var num_recs=this.store.getCount();var curr_rec;for(i=num_recs-1;i>=0;i--)
{curr_rec=this.store.getAt(i);if(curr_rec.layerOn)
{layer=curr_rec.get('layer');map.removeDataLayer(layer);curr_rec.layerOn=false;}}
this.store.removeAll();this.store.loadData(MarineMap.data.DataLayers);this.turnOnDefaultLayers();this.store.sort('group','ASC');if(this.FisheryImpactMapSelector.rendered){this.FisheryImpactMapSelector.hide();}
if(this.HumanUsesMapSelector.rendered){this.HumanUsesMapSelector.hide();}},toggleLayerHandler:function(sm,rowIndex,rec){var layer=rec.get('layer');if(!rec.layerOn)
{rec.layerOn=true;this.onAddMapLayer(rec.get('layer'));if(rec.get('name')=='Ecotrust Fishing Ground Maps')
{this.FisheryImpactMapSelector.show();}
else if(rec.get('name')=='Human Uses Layers')
{this.HumanUsesMapSelector.show();}}else{rec.layerOn=false;this.onRemoveMapLayer(rec.get('layer'));if(rec.get('name')=='Ecotrust Fishing Ground Maps')
{this.FisheryImpactMapSelector.hide();}
else if(rec.get('name')=='Human Uses Layers')
{this.HumanUsesMapSelector.hide();}}
this.redrawLayers();},mergeFisheryImpactMapParams:function(newParams){var num_recs=this.store.getCount();var curr_rec;for(i=0;i<num_recs;i++)
{curr_rec=this.store.getAt(i);if(curr_rec.get('name')=='Ecotrust Fishing Ground Maps')
{curr_rec.get('layer').mergeNewParams(newParams);break;}}},mergeHumanUsesMapParams:function(newParams){var num_recs=this.store.getCount();var curr_rec;for(i=0;i<num_recs;i++)
{curr_rec=this.store.getAt(i);if(curr_rec.get('name')=='Human Uses Layers')
{curr_rec.get('layer').mergeNewParams(newParams);break;}}},onRender:function(){MarineMap.widgets.DataLayersMenu.superclass.onRender.apply(this,arguments);var expander=new Ext.grid.RowExpander({tpl:new Ext.Template('<p><i>Description: {desc}</i></p>','<p><img src=\'{legend_url}\'></p>','<p><i>Metadata: {metadata}</i></p>')});var reader=new Ext.data.ArrayReader({},[{name:'name'},{name:'group'},{name:'layer'},{name:'legend_url'},{name:'desc'},{name:'metadata'},{name:'on_default'}]);var sm=new Ext.grid.MmappSelectionModel({singleSelect:true,header:'<div id="fool-ext-into-hiding-header2" class="eh"></div>'});sm.addListener('toggleLayer',this.toggleLayerHandler,this);var toolbar=new MarineMap.widgets.ControlToolbar({map:Ext.getCmp('map').map,configurable:false,id:'mt1'});this.FisheryImpactMapSelector=new MarineMap.widgets.FisheryImpactMapSelectorWindow();this.HumanUsesMapSelector=new MarineMap.widgets.HumanUsesMapSelectorWindow();this.store=new Ext.data.Store({reader:reader,data:MarineMap.data.DataLayers});this.store.sort('group');this.grid=new Ext.grid.GridPanel({id:'the-grid',store:this.store,cm:new Ext.grid.ColumnModel([sm,expander,{id:'name',header:"Name",width:210,sortable:true,dataIndex:'name'},{header:"Category",width:140,sortable:true,dataIndex:'group'}]),sm:sm,width:500,height:300,viewConfig:{forceFit:true},plugins:expander,frame:false,enableDragDrop:true,ddGroup:'mmDDGroup',listeners:{sortchange:function(){Ext.getCmp('dataLayersMenu').redrawLayers();},render:function(g){var ddrow=new Ext.ux.dd.GridReorderDropTarget(g,{copy:false,listeners:{beforerowmove:function(objThis,oldIndex,newIndex,records){},afterrowmove:function(objThis,oldIndex,newIndex,records){Ext.getCmp('dataLayersMenu').redrawLayers();},beforerowcopy:function(objThis,oldIndex,newIndex,records){},afterrowcopy:function(objThis,oldIndex,newIndex,records){}}});Ext.dd.ScrollManager.register(g.getView().getEditorParent());},beforedestroy:function(g){Ext.dd.ScrollManager.unregister(g.getView().getEditorParent());}},iconCls:'icon-grid'});sm.addListener({'beforerowselect':function(sm,rowIndex,keepExisting,record){if(keepExisting===false){return false;}}});this.turnOnDefaultLayers();this.window.add(this.grid);this.window.x=0;this.window.y=76;this.window.setTitle('Data Layers');}});Ext.reg('marinemap-widgets-datalayersmenu',MarineMap.widgets.DataLayersMenu);Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.DataLayerTreePanel=Ext.extend(Ext.tree.TreePanel,{loader:new Ext.tree.TreeLoader(),bodyBorder:false,border:false,collapseFirst:false,rootVisible:false});MarineMap.widgets.DataLayerTreeRoot=new Ext.tree.AsyncTreeNode({draggable:false,id:'data_layer_root',children:MarineMap.data.DataLayers});Ext.grid.RowExpander=function(config){Ext.apply(this,config);this.addEvents({beforeexpand:true,expand:true,beforecollapse:true,collapse:true});Ext.grid.RowExpander.superclass.constructor.call(this);if(this.tpl){if(typeof this.tpl=='string'){this.tpl=new Ext.Template(this.tpl);}
this.tpl.compile();}
this.state={};this.bodyContent={};};Ext.extend(Ext.grid.RowExpander,Ext.util.Observable,{header:"",width:20,sortable:false,fixed:true,menuDisabled:true,dataIndex:'',id:'expander',lazyRender:true,enableCaching:true,getRowClass:function(record,rowIndex,p,ds){p.cols=p.cols-1;var content=this.bodyContent[record.id];if(!content&&!this.lazyRender){content=this.getBodyContent(record,rowIndex);}
if(content){p.body=content;}
return this.state[record.id]?'x-grid3-row-expanded':'x-grid3-row-collapsed';},init:function(grid){this.grid=grid;var view=grid.getView();view.getRowClass=this.getRowClass.createDelegate(this);view.enableRowBody=true;grid.on('render',function(){view.mainBody.on('mousedown',this.onMouseDown,this);},this);},getBodyContent:function(record,index){if(!this.enableCaching){return this.tpl.apply(record.data);}
var content=this.bodyContent[record.id];if(!content){content=this.tpl.apply(record.data);this.bodyContent[record.id]=content;}
return content;},onMouseDown:function(e,t){if(t.className=='x-grid3-row-expander'){e.stopEvent();var row=e.getTarget('.x-grid3-row');this.toggleRow(row);}},renderer:function(v,p,record){p.cellAttr='rowspan="2"';return'<div class="x-grid3-row-expander">&#160;</div>';},beforeExpand:function(record,body,rowIndex){if(this.fireEvent('beforeexpand',this,record,body,rowIndex)!==false){if(this.tpl&&this.lazyRender){body.innerHTML=this.getBodyContent(record,rowIndex);}
return true;}else{return false;}},toggleRow:function(row){if(typeof row=='number'){row=this.grid.view.getRow(row);}
this[Ext.fly(row).hasClass('x-grid3-row-collapsed')?'expandRow':'collapseRow'](row);},expandRow:function(row){if(typeof row=='number'){row=this.grid.view.getRow(row);}
var record=this.grid.store.getAt(row.rowIndex);var body=Ext.DomQuery.selectNode('tr:nth(2) div.x-grid3-row-body',row);if(this.beforeExpand(record,body,row.rowIndex)){this.state[record.id]=true;Ext.fly(row).replaceClass('x-grid3-row-collapsed','x-grid3-row-expanded');this.fireEvent('expand',this,record,body,row.rowIndex);}},collapseRow:function(row){if(typeof row=='number'){row=this.grid.view.getRow(row);}
var record=this.grid.store.getAt(row.rowIndex);var body=Ext.fly(row).child('tr:nth(1) div.x-grid3-row-body',true);if(this.fireEvent('beforecollapse',this,record,body,row.rowIndex)!==false){this.state[record.id]=false;Ext.fly(row).replaceClass('x-grid3-row-expanded','x-grid3-row-collapsed');this.fireEvent('collapse',this,record,body,row.rowIndex);}}});ï»¿Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.LoginForm=Ext.extend(Ext.form.FormPanel,{closeWindow:function(){this.ownerCt.hide();this.hide();},initComponent:function(){var submitAction={text:'Login',scope:this,handler:function(){var mask=new Ext.LoadMask(this.ownerCt.getEl(),{msg:'Logging you in...'});mask.show();this.buttons[0].disable();this.form.submit({url:MarineMap.urls.login,method:'POST',scope:this,success:function(theForm,responseObj){mask.hide();this.buttons[0].enable();this.closeWindow();MarineMap.actions.utils.setUser(responseObj.result.returnObj.user);},failure:function(theForm,responseObj){mask.hide();if(responseObj.failureType=='client'){alert('You must specify both a username and password.');}else{alert(responseObj.result.message);}
this.buttons[0].enable();},scope:this});}}
var cancelAction={text:'Cancel',scope:this,handler:this.closeWindow}
var keyAction={key:Ext.EventObject.ENTER,fn:submitAction.handler,scope:this}
Ext.apply(this,{frame:true,title:'Log in to MarineMap',bodyStyle:'padding:5px 5px 0',defaults:{msgTarget:'side'},defaultType:'textfield',buttons:[submitAction,cancelAction],keys:[keyAction],items:[{fieldLabel:'Login',name:'name',allowBlank:false},{fieldLabel:'Password',name:'password',allowBlank:false,inputType:'password'},{xtype:'container',autoEl:{html:'<a onclick="MarineMap.actions.currentLoginWindow.hide(); MarineMap.actions.resetPassword.execute(); return false;" href="#">Help I forgot my password!</a>'}}]});MarineMap.widgets.LoginForm.superclass.initComponent.apply(this,arguments);var form=this.getForm();setTimeout(function(){var field=form.findField('name');if(field){field.focus();}},200);}});ï»¿Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.PasswordResetForm=Ext.extend(Ext.form.FormPanel,{initComponent:function(){var submitAction={text:'Reset my password',scope:this,handler:function(){var mask=new Ext.LoadMask(this.getEl(),{msg:'Resetting your password...'});mask.show();this.buttons[0].disable();this.form.submit({url:MarineMap.urls.sendPassword,method:'POST',success:function(theForm,responseObj){mask.hide();this.buttons[0].enable();this.ownerCt.hide();this.hide();Ext.Msg.alert('Password Reset!','An email has been send with your new password.');},failure:function(theForm,responseObj){mask.hide();if(responseObj.result){Ext.Msg.alert('There was a problem resetting your password',responseObj.result.message);this.ownerCt.hide();this.hide();}else{Ext.Msg.alert('','Please correct any errors in the form.');this.buttons[0].enable();}},scope:this});}}
var cancelAction={text:'Cancel',scope:this,handler:function(){this.ownerCt.hide();this.hide();}}
var keyAction={key:Ext.EventObject.ENTER,fn:submitAction.handler,scope:this}
Ext.apply(this,{url:MarineMap.urls.sendPassword,method:'POST',frame:true,title:'Reset Password',bodyStyle:'padding:5px 5px 0',labelWidth:150,defaults:{msgTarget:'side'},defaultType:'textfield',buttons:[submitAction,cancelAction],keys:[keyAction],items:[{xtype:'container',autoEl:{html:'<h1>Did you forget your password?</h1><p style="margin-bottom:15px;">Enter your username below, and we\'ll email a NEW password to the email address we have on file.</p>'}},{fieldLabel:'Enter your username',name:'username',allowBlank:false}]});MarineMap.widgets.PasswordResetForm.superclass.initComponent.apply(this,arguments);var form=this.getForm();setTimeout(function(){var field=form.findField('username');if(field){field.focus();}},200);}});ï»¿Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.PasswordChangeForm=Ext.extend(Ext.form.FormPanel,{initComponent:function(){var submitAction={text:'Change my password',scope:this,handler:function(){var mask=new Ext.LoadMask(this.getEl(),{msg:'Changing your password...'});mask.show();this.buttons[0].disable();this.form.submit({url:MarineMap.urls.changePassword,method:'POST',success:function(theForm,responseObj){mask.hide();this.buttons[0].enable();this.ownerCt.hide();this.hide();Ext.Msg.alert('Password Changed!','An email has been sent with your new password.');},failure:function(theForm,responseObj){mask.hide();if(responseObj.result){Ext.Msg.alert('There was a problem changing your password',responseObj.result.message);this.ownerCt.hide();this.hide();}else{Ext.Msg.alert('','Please correct any errors in the form.');this.buttons[0].enable();}},scope:this});}}
var cancelAction={text:'Cancel',scope:this,handler:function(){this.ownerCt.hide();this.hide();}}
var keyAction={key:Ext.EventObject.ENTER,fn:submitAction.handler,scope:this}
Ext.apply(this,{url:MarineMap.urls.sendPassword,method:'POST',frame:true,title:'Change Your Password',bodyStyle:'padding:5px 5px 0',labelWidth:150,defaults:{msgTarget:'side'},defaultType:'textfield',buttons:[submitAction,cancelAction],keys:[keyAction],items:[{xtype:'container',autoEl:{html:'<h1>Want to change your password?</h1><p style="margin-bottom:15px;">Enter your old and new passwords below, and we\'ll email your new password to the email address we have on file.</p>'}},{fieldLabel:'Enter your old password',name:'password_old',allowBlank:false,inputType:'password'},{fieldLabel:'Enter your new password',name:'password_new',allowBlank:false,inputType:'password'},{fieldLabel:'Confirm your new password',name:'password_confirm',allowBlank:false,inputType:'password'}]});MarineMap.widgets.PasswordChangeForm.superclass.initComponent.apply(this,arguments);var form=this.getForm();setTimeout(function(){var field=form.findField('password_old');if(field){field.focus();}},200);}});ï»¿Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.SplashScreen=Ext.extend(Ext.Panel,{id:'panelSplashScreen',html:'',initComponent:function(){Ext.apply(this,{frame:true,title:'Welcome to MarineMAP',bodyStyle:'padding:10px'});MarineMap.widgets.SplashScreen.superclass.initComponent.apply(this,arguments);}});Ext.namespace('Ext.ux.dd');Ext.ux.dd.GridReorderDropTarget=function(grid,config)
{this.target=new Ext.dd.DropTarget(grid.getEl(),{ddGroup:grid.ddGroup||'GridDD',grid:grid,gridDropTarget:this,notifyDrop:function(dd,e,data)
{if(this.currentRowEl)
{this.currentRowEl.removeClass('grid-row-insert-below');this.currentRowEl.removeClass('grid-row-insert-above');}
var t=Ext.lib.Event.getTarget(e);var rindex=this.grid.getView().findRowIndex(t);data.selections=this.grid.getSelectionModel().getSelections();if(rindex===false||rindex==data.rowIndex)
{return false;}
if(this.gridDropTarget.fireEvent('beforerowmove',this.gridDropTarget,data.rowIndex,rindex,data.selections,123)===false)
{return false;}
var ds=this.grid.getStore();var selections=new Array();var keys=ds.data.keys;for(var key in keys)
{for(var i=0;i<data.selections.length;i++)
{if(keys[key]==data.selections[i].id)
{if(rindex==key)
{return false;}
selections.push(data.selections[i]);}}}
if(rindex>data.rowIndex&&this.rowPosition<0)
{rindex--;}
if(rindex<data.rowIndex&&this.rowPosition>0)
{rindex++;}
if(rindex>data.rowIndex&&data.selections.length>1)
{rindex=rindex-(data.selections.length-1);}
if(rindex==data.rowIndex)
{return false;}
for(var i=0;i<data.selections.length;i++)
{ds.remove(ds.getById(data.selections[i].id));}
for(var i=selections.length-1;i>=0;i--)
{var insertIndex=rindex;ds.insert(insertIndex,selections[i]);}
var sm=this.grid.getSelectionModel();if(sm)
{sm.selectRecords(data.selections);}
this.gridDropTarget.fireEvent('afterrowmove',this.gridDropTarget,data.rowIndex,rindex,data.selections);return true;},notifyOver:function(dd,e,data)
{var t=Ext.lib.Event.getTarget(e);var rindex=this.grid.getView().findRowIndex(t);var ds=this.grid.getStore();var keys=ds.data.keys;for(var key in keys)
{for(var i=0;i<data.selections.length;i++)
{if(keys[key]==data.selections[i].id)
{if(rindex==key)
{if(this.currentRowEl)
{this.currentRowEl.removeClass('grid-row-insert-below');this.currentRowEl.removeClass('grid-row-insert-above');}
return this.dropNotAllowed;}}}}
if(rindex<0||rindex===false)
{this.currentRowEl.removeClass('grid-row-insert-above');return this.dropNotAllowed;}
try
{var currentRow=this.grid.getView().getRow(rindex);var resolvedRow=new Ext.Element(currentRow).getY()-this.grid.getView().scroller.dom.scrollTop;var rowHeight=currentRow.offsetHeight;this.rowPosition=e.getPageY()-resolvedRow-(rowHeight/2);if(this.currentRowEl)
{this.currentRowEl.removeClass('grid-row-insert-below');this.currentRowEl.removeClass('grid-row-insert-above');}
if(this.rowPosition>0)
{this.currentRowEl=new Ext.Element(currentRow);this.currentRowEl.addClass('grid-row-insert-below');}
else
{if(rindex-1>=0)
{var previousRow=this.grid.getView().getRow(rindex-1);this.currentRowEl=new Ext.Element(previousRow);this.currentRowEl.addClass('grid-row-insert-below');}
else
{this.currentRowEl.addClass('grid-row-insert-above');}}}
catch(err)
{console.warn(err);rindex=false;}
return(rindex===false)?this.dropNotAllowed:this.dropAllowed;},notifyOut:function(dd,e,data)
{if(this.currentRowEl)
{this.currentRowEl.removeClass('grid-row-insert-above');this.currentRowEl.removeClass('grid-row-insert-below');}}});if(config)
{Ext.apply(this.target,config);if(config.listeners)
{Ext.apply(this,{listeners:config.listeners});}}
this.addEvents({'beforerowmove':true,'afterrowmove':true,'beforerowcopy':true,'afterrowcopy':true});Ext.ux.dd.GridReorderDropTarget.superclass.constructor.call(this);};Ext.extend(Ext.ux.dd.GridReorderDropTarget,Ext.util.Observable,{getTarget:function()
{return this.target;},getGrid:function()
{return this.target.grid;}});Ext.grid.MmappSelectionModel=Ext.extend(Ext.grid.RowSelectionModel,{header:'<div class="x-grid3-hd-checker">&#160;</div>',width:20,sortable:false,menuDisabled:true,fixed:true,dataIndex:'',id:'checker',initEvents:function(){Ext.grid.MmappSelectionModel.superclass.initEvents.call(this);this.grid.on('render',function(){var view=this.grid.getView();view.mainBody.on('mousedown',this.onMouseDown,this);},this);},onMouseDown:function(e,t){if(e.button===0)
{e.stopEvent();var row=e.getTarget('.x-grid3-row');if(row){var index=row.rowIndex;var rec=this.grid.store.getAt(index);var checkbox;if(t.className.match('x-grid3-row-checker')!='x-grid3-row-checker')
{if(t.className!='x-grid3-row-expander'){this.selectRow(index,true);checkbox=Ext.fly(t.parentNode.parentNode.firstChild.firstChild.firstChild);if(!rec.layerOn)
{checkbox.removeClass('x-grid3-row-checker');checkbox.removeClass('x-grid3-row-checker-on');checkbox.addClass('x-grid3-row-checker-off');}}}
else
{this.fireEvent("toggleLayer",this,index,rec);checkbox=Ext.fly(t);if(!rec.layerOn){checkbox.addClass('x-grid3-row-checker-off');checkbox.removeClass('x-grid3-row-checker-on');}else{checkbox.addClass('x-grid3-row-checker-on');checkbox.removeClass('x-grid3-row-checker');checkbox.removeClass('x-grid3-row-checker-off');}}}}},renderer:function(v,p,record){if(record.layerOn){return'<div class="x-grid3-row-checker-on">&#160;</div>';}else{return'<div class="x-grid3-row-checker-off">&#160;</div>';}}});Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.FisheryImpactMapSelectorForm=Ext.extend(Ext.form.FormPanel,{id:'FisheryImpactMapSelectorPanel',successPanel:'initialized below',statusPanel:'initialized below',initComponent:function(){this.group_sel=new Ext.form.ComboBox({store:new Ext.data.SimpleStore({fields:['abbr','group'],data:MarineMap.data.FisheryImpactMapUserGroups}),displayField:'group',valueField:'abbr',typeAhead:true,mode:'local',triggerAction:'all',emptyText:'Select a user group',selectOnFocus:true,fieldLabel:'User Group',hiddenName:'group',width:235,forceSelection:true});this.group_sel.on('select',this.selectGroup,this);this.speciesSelectStore=new Ext.data.SimpleStore({fields:['abbr','species'],data:[]});this.species_sel=new Ext.form.ComboBox({store:this.speciesSelectStore,displayField:'species',valueField:'abbr',typeAhead:true,mode:'local',triggerAction:'all',emptyText:'Select a species',selectOnFocus:true,fieldLabel:'Species',hiddenName:'species',width:235,forceSelection:true});this.portSelectStore=new Ext.data.SimpleStore({fields:['abbr','port'],data:[]});this.port_sel=new Ext.form.ComboBox({store:this.portSelectStore,displayField:'port',valueField:'abbr',typeAhead:true,mode:'local',triggerAction:'all',emptyText:'Select a port/county',selectOnFocus:true,fieldLabel:'Port/County',hiddenName:'port',width:235,forceSelection:true});this.port_sel.on('select',this.selectPort,this);Ext.apply(this,{frame:true,border:false,bodyStyle:'padding:5px 5px 0',formId:'frmfimap',defaults:{msgTarget:'side'},defaultType:'textfield',items:[this.group_sel,this.port_sel,this.species_sel]});MarineMap.widgets.FisheryImpactMapSelectorForm.superclass.initComponent.apply(this,arguments);},selectGroup:function(){var sel_group=this.group_sel.getValue();this.port_sel.reset();this.portSelectStore.removeAll();for(grp in MarineMap.data.FisheryImpactMapPortsByGroup){if(MarineMap.data.FisheryImpactMapPortsByGroup[grp][0]==sel_group){this.portSelectStore.loadData(MarineMap.data.FisheryImpactMapPortsByGroup[grp][1]);break;}}
this.species_sel.reset();this.speciesSelectStore.removeAll();},selectPort:function(){var prev_species=this.species_sel.getValue();var sel_group=this.group_sel.getValue();var sel_port=this.port_sel.getValue();this.species_sel.reset();this.speciesSelectStore.removeAll();var key=0;var val_list=1;for(grp in MarineMap.data.FisheryImpactMapSpeciesByGroup){if(MarineMap.data.FisheryImpactMapSpeciesByGroup[grp][key]==sel_group){var this_group=MarineMap.data.FisheryImpactMapSpeciesByGroup[grp][val_list];if(this_group.length==1){this.speciesSelectStore.loadData(this_group[0][val_list]);break;}else{for(port in this_group){if(this_group[port][key]==sel_port){this.speciesSelectStore.loadData(this_group[port][val_list]);break;}}
break;}}}
if(this.speciesSelectStore.find('abbr',prev_species)>=0){this.species_sel.setValue(prev_species);}}});MarineMap.widgets.FisheryImpactMapSelectorWindow=Ext.extend(Ext.Window,{thisForm:undefined,initComponent:function(){this.thisForm=new MarineMap.widgets.FisheryImpactMapSelectorForm();var submitAction={text:'Load Fishery Impact Layer',scope:this,handler:function(){this.scope=!this.scope?this:this.scope;Ext.getCmp('dataLayersMenu').mergeFisheryImpactMapParams(this.thisForm.form.getValues());}};var cancelAction={text:'Close',scope:this,handler:function(){this.hide();}};var keyAction={key:Ext.EventObject.ENTER,fn:function(){submitAction.handler();}};Ext.apply(this,{id:'windowFisheryImpactMapSelector',title:'Select a fishing ground layer',closeAction:'hide',closable:true,width:380,items:[this.thisForm],keys:[this,keyAction],buttons:[submitAction,cancelAction]});MarineMap.widgets.FisheryImpactMapSelectorWindow.superclass.initComponent.apply(this,arguments);}});MarineMap.widgets.FisheryImpactAnalysisSelectorForm=Ext.extend(Ext.form.FormPanel,{id:'FisheryImpactAnalysisSelectorPanel',successPanel:'initialized below',statusPanel:'initialized below',initComponent:function(){this.group_sel=new Ext.form.ComboBox({store:new Ext.data.SimpleStore({fields:['group'],data:this.getGroups()}),displayField:'group',valueField:'group',typeAhead:true,mode:'local',triggerAction:'all',emptyText:'Select a user group',selectOnFocus:true,fieldLabel:'User Group',hiddenName:'group',width:235,forceSelection:true});this.group_sel.on('select',this.selectGroup,this);this.portSelectStore=new Ext.data.SimpleStore({fields:['home'],data:[]});this.port_sel=new Ext.form.ComboBox({store:this.portSelectStore,displayField:'home',valueField:'home',typeAhead:false,mode:'local',triggerAction:'all',emptyText:'Select a port/county',selectOnFocus:true,fieldLabel:'Port/County',hiddenName:'home',width:235,forceSelection:true});Ext.apply(this,{frame:true,border:false,bodyStyle:'padding:5px 5px 0',formId:'frmfianalysis',defaults:{msgTarget:'side'},defaultType:'textfield',items:[this.group_sel,this.port_sel]});MarineMap.widgets.FisheryImpactAnalysisSelectorForm.superclass.initComponent.apply(this,arguments);},getGroups:function(){var groups=MarineMap.data.FisheryImpactAnalysisUserGroups;var group_names=[];for(i=0;i<groups.length;i++){group=groups[i];group_names.push([group.name]);}
return group_names;},getPorts:function(group_name){var groups=MarineMap.data.FisheryImpactAnalysisUserGroups;for(i=0;i<groups.length;i++){group=groups[i];if(group.name==group_name){port_names=[];for(j=0;j<group.homes.length;j++){home_name=group.homes[j];port_names.push([home_name]);}}}
return port_names;},selectGroup:function(){var sel_group=this.group_sel.getValue();this.port_sel.reset();this.portSelectStore.removeAll();this.portSelectStore.loadData(this.getPorts(sel_group));}});MarineMap.widgets.FisheryImpactAnalysisSelectorWindow=Ext.extend(Ext.Window,{thisForm:undefined,initComponent:function(){this.thisForm=new MarineMap.widgets.FisheryImpactAnalysisSelectorForm();var submitAction={text:'Load Fishery Impact Report',scope:this,handler:function(){this.scope=!this.scope?this:this.scope;var values=this.thisForm.form.getValues();if(values.group==''||values.home==''){MarineMap.ui.error.show({errorText:'You must select both a user group and port/county'});return;}
this.runAnalysis(values);}};var cancelAction={text:'Close',scope:this,handler:function(){this.hide();}};var keyAction={key:Ext.EventObject.ENTER,fn:function(){submitAction.handler();}};Ext.apply(this,{id:'windowFisheryImpactAnalysisSelector',closeAction:'hide',title:'Choose report to load',closable:true,width:380,items:[this.thisForm],keys:[this,keyAction],buttons:[submitAction,cancelAction]});MarineMap.widgets.FisheryImpactAnalysisSelectorWindow.superclass.initComponent.apply(this,arguments);},setMPA:function(feature_id){this.feature_id=feature_id;},runAnalysis:function(values){values.output='html';var url=MarineMap.urls.mpaImpactAnalysis+this.feature_id+'?'+Ext.urlEncode(values);MarineMap.ui.modal.show({width:750,url:url,waitMsg:'while the analysis runs<br/>(up to 15 sec.)',afterRender:function(){}});}});Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.HumanUsesMapSelectorForm=Ext.extend(Ext.form.FormPanel,{id:'HumanUsesMapSelectorPanel',successPanel:'initialized below',statusPanel:'initialized below',initComponent:function(){this.group_sel=new Ext.form.ComboBox({store:new Ext.data.SimpleStore({fields:['abbr','group'],data:MarineMap.data.HumanUsesMapGroups}),displayField:'group',valueField:'abbr',typeAhead:true,mode:'local',triggerAction:'all',emptyText:'Select a user group',selectOnFocus:true,fieldLabel:'Group',hiddenName:'group',width:235,forceSelection:true});this.group_sel.on('select',this.selectGroup,this);this.subgroupSelectStore=new Ext.data.SimpleStore({fields:['abbr','subgroup'],data:MarineMap.data.HumanUsesMapSubgroups});this.subgroup_sel=new Ext.form.ComboBox({store:this.subgroupSelectStore,displayField:'subgroup',valueField:'abbr',typeAhead:true,mode:'local',triggerAction:'all',emptyText:'Select a subgroup',selectOnFocus:true,fieldLabel:'Subgroup',hiddenName:'subgroup',width:235,forceSelection:true});this.subgroup_sel.on('select',this.selectSubgroup,this);this.layerSelectStore=new Ext.data.SimpleStore({fields:['id','esrilayer'],data:[]});this.layer_sel=new Ext.form.ComboBox({store:this.layerSelectStore,displayField:'esrilayer',valueField:'id',typeAhead:true,mode:'local',triggerAction:'all',emptyText:'Select a layer',selectOnFocus:true,fieldLabel:'Layer',hiddenName:'esrilayer',width:235,forceSelection:true});Ext.apply(this,{frame:true,border:false,bodyStyle:'padding:5px 5px 0',formId:'frmhumap',defaults:{msgTarget:'side'},defaultType:'textfield',items:[this.group_sel,this.subgroup_sel,this.layer_sel]});MarineMap.widgets.HumanUsesMapSelectorForm.superclass.initComponent.apply(this,arguments);},selectGroup:function(){var sel_group=this.group_sel.getValue();this.subgroup_sel.reset();this.layer_sel.reset();this.layerSelectStore.removeAll();},selectSubgroup:function(){var sel_group=this.group_sel.getValue();var sel_subgroup=this.subgroup_sel.getValue();this.layer_sel.reset();this.layerSelectStore.removeAll();var key=0;var val_list=1;for(grp in MarineMap.data.HumanUsesMapLayersByGroup){if(MarineMap.data.HumanUsesMapLayersByGroup[grp][key]==sel_group){var this_group=MarineMap.data.HumanUsesMapLayersByGroup[grp][val_list];for(subgroup in this_group){if(this_group[subgroup][key]==sel_subgroup){this.layerSelectStore.loadData(this_group[subgroup][val_list]);break;}}}}}});MarineMap.widgets.HumanUsesMapSelectorWindow=Ext.extend(Ext.Window,{thisForm:undefined,initComponent:function(){this.thisForm=new MarineMap.widgets.HumanUsesMapSelectorForm();var submitAction={text:'Load Human Uses Layer',scope:this,handler:function(){this.scope=!this.scope?this:this.scope;Ext.getCmp('dataLayersMenu').mergeHumanUsesMapParams(this.thisForm.form.getValues());}};var cancelAction={text:'Close',scope:this,handler:function(){this.hide();}};var keyAction={key:Ext.EventObject.ENTER,fn:function(){submitAction.handler();}};Ext.apply(this,{id:'windowHumanUsesMapSelector',title:'Select a human uses layer',closeAction:'hide',closable:true,width:380,items:[this.thisForm],keys:[this,keyAction],buttons:[submitAction,cancelAction]});MarineMap.widgets.HumanUsesMapSelectorWindow.superclass.initComponent.apply(this,arguments);}});Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.FisheryImpactReportWindow=Ext.extend(Ext.Window,{initComponent:function(){var restartAction={text:'Load another report',scope:this,handler:function(){console.log('foo');}};var cancelAction={text:'Close',scope:this,handler:function(){this.hide();}};this.reportPanel=new Ext.Panel({id:'report-panel',style:'padding: 10px'});Ext.apply(this,{id:'windowFisheryImpactReport',closeAction:'hide',title:'Fishery Impact Analysis Reports',closable:true,width:380,height:600,layout:'fit',items:[this.reportPanel],buttons:[restartAction,cancelAction]});MarineMap.widgets.FisheryImpactReportWindow.superclass.initComponent.apply(this,arguments);},loadReport:function(result){this.show();Ext.get('report-panel').update(result);}});Ext.BLANK_IMAGE_URL='/marinemap/media/js/extjs/resources/images/default/s.gif';Ext.namespace('MarineMap');MarineMap.backWarn=function(){return"Your MarineMap session will end if you continue.";};MarineMap.app=function(){function onViewportResize(target,adjWidth,adjHeight,width,height){var reportsHeight=350;var tbar=Ext.getCmp('map').getTopToolbar();var nheight=adjHeight-reportsHeight-tbar.getSize().height;var edit=Ext.getCmp('editmodetoolbar');if(edit){edit.setWidth(MarineMap.app.viewport.getSize().width);}}
return{initUser:function(){jQuery.ajax({url:MarineMap.urls.user,dataType:'json',success:function(data){MarineMap.app.userManager.setUser(new MarineMap.data.mlpaFeatures.User(data['user']));MarineMap.app.reportsVisor.activate();},error:function(){MarineMap.app.userManager.setUser(null);MarineMap.app.reportsVisor.activate();}})},init:function(){this.userManager=new MarineMap.ui.UserManager();$('#jLoading').ajaxStart(function(){$(this).show();});$('#jLoading').ajaxStop(function(){$(this).hide();});if(jQuery.browser.msie&&jQuery.browser.version.substr(0,1)=='8'){alert('You will need to enable "Compatibility View" to use MarineMap with Microsoft Internet Explorer 8. Press the broken-page button next to the url field to enable Compatibility View. We are hoping to fix this problem shortly.');return;}
if(jQuery.browser.msie&&jQuery.browser.version.substr(0,1)=='6'){Ext.MessageBox.alert("Browser Check","Sorry MarineMap does not function correctly in Internet Explorer 6.  Supported browsers include Mozilla Firefox 2+, Apple Safari 3+, Opera 9.6+ and Internet Explorer 7+");this.hide_load();return;}
window.onbeforeunload=MarineMap.backWarn;this.selectionManager=new MarineMap.ui.SelectionManager();$(this.selectionManager).bind('selectionChange',function(e,m,f){if(e.caller&&e.caller.id=="selection-breadcrumbs"&&f['model']=='array'){MarineMap.app.map.zoomToFeature(f);}});var options={projection:MarineMap.config.projection,displayProjection:MarineMap.config.displayProjection,units:"m",numZoomLevels:18,maxResolution:156543.0339,studyRegion:new MarineMap.data.StudyRegion({name:"California South Coast",bounds:"-13477376.825366,3752140.84394,-12930699.199147,4134937.481539"}),maxExtent:new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508.34),controls:[]};this.clientStore=new MarineMap.ui.ClientStore();$(this.clientStore).bind('removed',function(e,items){MarineMap.app.selectionManager.clearSelection();if(items['mpa']&&items['mpa'].length){for(var i=0;i<items['mpa'].length;i++){var old_mpa=items['mpa'][i];if(old_mpa.feature){old_mpa.feature.destroy();}}}});$(this.clientStore).bind('updated',function(e,items){var mpas_updated=(items['mpa']&&items['mpa'].length);var arrays_updated=(items['array']&&items['array'].length);if(mpas_updated||arrays_updated){MarineMap.app.selectionManager.clearSelection();if(mpas_updated){for(var i=0;i<items['mpa'].length;i++){var old_mpa=items['mpa'][i][1];if(old_mpa.feature){old_mpa.feature.destroy();}}}}});MarineMap.app.FeaturesMenu=new MarineMap.widgets.FeaturesMenu({selectionManager:this.selectionManager,store:this.clientStore,extWindow:true,userManager:this.userManager});$(MarineMap.app.FeaturesMenu).bind('mpaToggle',function(event,mpas,state){state?MarineMap.app.map.addMPAs(mpas):MarineMap.app.map.removeMPAs(mpas)});$(MarineMap.app.FeaturesMenu).bind('featureDoubleClick',function(e,feature){MarineMap.app.map.zoomToFeature(feature);});$(this.userManager).bind('change',function(e,user,oldUser){MarineMap.app.selectionManager.clearSelection();MarineMap.app.clientStore.clear();MarineMap.app.FeaturesMenu.clear();MarineMap.app.FeaturesMenu.showSpinner();var url;if(user){url='/marinemap/features/';MarineMap.app.FeaturesMenu.showTools();}else{url='/marinemap/public_features/';MarineMap.app.FeaturesMenu.hideTools();}
jQuery.ajax({type:'GET',url:url,success:function(data){MarineMap.app.FeaturesMenu.hideSpinner();var json=eval('('+data+')');var features=MarineMap.app.FeaturesMenu.init(json);delete json['features'];delete json['me'];delete json['mpa'];delete json['array'];var hash=MarineMap.ui.data.from_json(json,MarineMap.data.mlpaFeatures.lookup);hash['mpa']=features['mpa'];hash['array']=features['array'];MarineMap.app.clientStore.load(hash);if(!MarineMap.app.userManager.user){MarineMap.app.FeaturesMenu.tree.append('<br /><div style="color:#6C7C90;"><h3>Public Account</h3><p>Please login to view your saved shapes or create new ones.</p></div>');}},error:function(){MarineMap.ui.error.show({errorText:'There was a problem fetching the feature listing.'});}});});this.mapToolbar=new MarineMap.widgets.MapToolbar({user:this.user,id:'maptoolbar',featuresMenu:MarineMap.app.FeaturesMenu,userManager:this.userManager,onAddMapLayer:function(layer){MarineMap.app.map.addDataLayer(layer);},onRemoveMapLayer:function(layer){MarineMap.app.map.removeDataLayer(layer);},selectionManager:this.selectionManager});this.map=new MarineMap.widgets.Map({id:'map',region:'center',map:new OpenLayers.Map(document.getElementById('map'),options),studyRegion:options.studyRegion,selectionManager:MarineMap.app.selectionManager,listeners:{'resize':onViewportResize},tbar:this.mapToolbar,userManager:this.userManager,store:this.clientStore});this.viewport=new Ext.Viewport({id:'viewport',layout:'border',minWidth:1024,items:[this.map,{region:'south',height:40}]});this.mapToolWindow=new MarineMap.widgets.MapToolWindow();this.mapToolWindow.show();this.reportsVisor=new MarineMap.widgets.ReportsViewer(this.selectionManager,this.userManager,this.clientStore);this.statusPanel=new Ext.Window({html:'',width:400,autoHeight:true,resizable:false,collapsible:true,draggable:false,closable:false,x:2,y:35});this.statusPanel.show();this.statusPanel.hide();var size=this.viewport.getSize();Ext.QuickTips.init();this.initUser();MarineMap.actions.help.execute();MarineMap.actions.setupEconomicAnalysis();this.hide_load();var app=this;$(document).keypress(function(e){if(e.which==181||e.which==109&&e.altKey==true){var ids=prompt("Type in an MPA ID, or multiple ID's seperated by a comma.");ids=ids.split(',');for(var i=0;i<ids.length;i++){if(ids[i]){var id=ids[i].replace(' ','');var feature=app.clientStore.get('mpa',id);if(feature){app.FeaturesMenu.toggleFeature(feature);}}}
if(ids.length==1){var id=ids[0].replace(' ','');var feature=app.clientStore.get('mpa',ids[0]);if(feature){app.selectionManager.setSelectedFeature(feature);}}}});},hide_load:function(){Ext.get('loading-mask').fadeOut({remove:true});Ext.get('loading').fadeOut({remove:true});}};}();Ext.namespace('MarineMap','MarineMap.urls');MarineMap.copy={designationForm:'You must choose a protection category for this marine reserve. To learn about the different choices, see the <a href="http://www.dfg.ca.gov/mlpa/defs.asp#system" target="_blank">full description</a>',dfgFeasabilityGuidanceLabel:'DFG Feasability Guidance',emptyDfgFeasabilityGuidanceText:'The Department of Fish and Game will fill in this information later in the process to inform you whether this MPA meets feasability guidelines.',lopLabel:'Level of Protection',lopDescription:'Level of Protection will be assigned by the Science Advisory Team later in the process.',satExplanationLabel:'SAT Guidance',emptySatExplanationText:'The Science Advisory Team will fill in this area to explain their rational for the assigned Level of Protection',geometryConfirmTitle:'Confirm your geometry',geometryConfirmText:'The server has validated and clipped your geometry according to [these rules]. Do you want to continue with this geometry?'};MarineMap.copy.confirmStudyRegionClippingTitle='Please confirm modifications to your geometry';MarineMap.copy.confirmStudyRegionClipping='<h3>Geometry Clipping</h3><img src="/marinemap/media/figures/clipping.gif" width="369" height="88" /><p>Your geometry has been clipped to match the study region boundaries. Portions not overlapping the study region, or overlapping land, have been removed.</p><br /><p>This operation occurs each time you create a geometry. We also keep a copy of the lines you draw, so you will always have the un-clipped version for editing.</p><p style="color:red;">[Known Bug] In some browsers you may not see a geometry at this stage. This is a known bug and we are working on a fix. Press continue, and your geometry will be saved and then rendered. Don\'t worry, you will be able to see your new geometry in a moment and it is easy to go back and change it by clicking "edit geometry" in the MPA popup.</p>';MarineMap.copy.overlapsEstuaryTitle='Please confirm modifications to your geometry';MarineMap.copy.overlapsEstuaryText='<h3>Your Geometry Overlaped an Estuary</h3><img src="/marinemap/media/figures/estuary.gif" width="368" height="88" /><p>An MPA geometry can either be entirely estuary, or none. In cases like this where a geometry overlaps but is not entirely estuarine, the system creates two polygons. Whichever is larger is the one it assumes you would like to create.</p><br />';MarineMap.copy.overlapsEstuary=[];MarineMap.copy.overlapsEstuaryEndText="<p>If this is not the outcome you wanted, try to refine your selection to better fit the habitat you are trying to capture. Turning on the Estuary layer from the Data Layers menu can help you in this process.</p>";MarineMap.copy.overlapsEstuary[1]=MarineMap.copy.overlapsEstuaryText+'<p>In this case, the system chose the <b>Non-Estuary Part</b></p><br />'+MarineMap.copy.overlapsEstuaryEndText;MarineMap.copy.overlapsEstuary[5]=MarineMap.copy.overlapsEstuaryText+'<p>In this case, the system chose the <b>Estuary Part</b></p><br />'+MarineMap.copy.overlapsEstuaryEndText;MarineMap.copy.errors={mpaValidationService:'There was an error trying to validate this geometry.'};MarineMap.copy.clippedGeometryStatus=[];MarineMap.copy.clippedGeometryStatus[0]='Successful geometry creation';MarineMap.copy.clippedGeometryStatus[1]='System has chosen an MPA';MarineMap.copy.clippedGeometryStatus[2]='<h3>Outside the Study Region</h3><img src="/marinemap/media/figures/outsidestudyregion.gif" width="115" height="84" /><p>The geometry you defined was outside the study region. The study region for Southern California is limited to 3 miles offshore. If you are having trouble, you can turn on the study region layer in the Data Layers menu.</p>';MarineMap.copy.clippedGeometryStatus[3]='<h3>Invalid Geometry</h3><img src="/marinemap/media/figures/invalidgeo.gif" width="121" height="87" /><p>Please try to avoid drawing irregular shapes that intersect themselves like bowties.<br /> To delete a vertex from a geometry, click on it and press "d" on your keyboard.</p>';MarineMap.copy.clippedGeometryStatus[4]='System Error';MarineMap.copy.clippedGeometryErrorText='You have the option of either cancelling this operation or going back to your geometry to fix this error.';MarineMap.copy.createNewGeometry='Draw an MPA geometry by clicking on the map.<br /> When you are ready to create the last point in your geometry, double click.';MarineMap.copy.editGeometry='Edit this geometry by dragging the handles on its vertices.  To delete a vertex, press the D-key <img class="dkey" src="/marinemap/media/images/D.png" />. <br />When you are done, click the finished button.';Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.ReportsViewer=function(selectionManager,userManager,clientStore){var sm=selectionManager;var div=$('#ReportsViewer');var store=clientStore;var header=$(div).find('.header');var instance=this;var userManager=userManager;$(userManager).bind('change',function(e,user,oldUser){instance.update();});function storeEventHandler(e,items){if((items['mpa']&&items['mpa'].length)||(items['array']&&items['array'].length)){refreshSwfLists();}}
$(store).bind('added',storeEventHandler);$(store).bind('updated',storeEventHandler);var contentHeight=$('#reports_content').height;var animationPlaying=false;function animationCallback(){animationPlaying=false;};var requiredFlashVersion="9.0.124";var flashInitialized=false;function flashCapable(){return swfobject.hasFlashPlayerVersion(requiredFlashVersion);};function initFlash(){FABridge.addInitializationCallback("flash",onFlashInitialization);swfobject.embedSWF("media/flash/MarineMapClient.swf","reports_content","100%","320",requiredFlashVersion,false,false,{wmode:"opaque",play:"true"});$(div).css('bottom',-319);flashInitialized=true;};function onFlashInitialization(){FABridge.flash.root().getEconButton().addEventListener('click',function(){MarineMap.actions.openEconomicAnalysis(sm.selectedFeature);});};function setSwfSelection(feature){if(feature&&feature.model=='mpa'){if(typeof FABridge.flash!='undefined'&&typeof FABridge.flash.root!='undefined'){FABridge.flash.root().setSelectedFeature('MPA',feature.pk);}}else{clearSwfSelection();}};function clearSwfSelection(){if(typeof FABridge.flash!='undefined'&&typeof FABridge.flash.root!='undefined'){FABridge.flash.root().setSelectedFeature('MPA',null);}};function refreshSwfLists(){if(typeof FABridge.flash!='undefined'&&typeof FABridge.flash.root!='undefined'){FABridge.flash.root().refresh();}};this.update=function(){if(flashInitialized){refreshSwfLists();}};this.isDisplayed=function(){return $(div).css('bottom')=='0px';};this.isActive=function(){return!$(div).hasClass('inactive');};this.setDisplayState=function(state){if(animationPlaying){return;}
if(this.isDisplayed==state){return;}
animationPlaying=true;setSwfSelection(sm.selectedFeature);if(state){if(!this.isActive()){animationPlaying=false;return;}
$(div).animate({bottom:0},300,'swing',animationCallback);}else{$(div).animate({bottom:-320},300,'swing',animationCallback);}};this.activate=function(){$('#selection-breadcrumbs').selectioncrumbs('enable');$(div).removeClass('inactive');$(header).css('cursor','pointer');if(flashCapable()&&!flashInitialized){initFlash();}
if(flashInitialized&&sm.selectedFeature!=null){setSwfSelection(sm.selectedFeature);}};this.deactivate=function(){$('#selection-breadcrumbs').selectioncrumbs('disable');$(div).addClass('inactive');$(header).css('cursor','default');instance.setDisplayState(false);};this.toggle=function(){instance.setDisplayState(!instance.isDisplayed());};$(header).click(function(){instance.toggle();});$(header).mouseover(function(){if(instance.isActive()){$(div).css('border-top','2px solid white');}});$(header).mouseout(function(){if(instance.isActive()){$(div).css('border-top','none');}});$(sm).bind('selectionChange',function(e,manager,selectedFeature,old){if(instance.isDisplayed()){if(selectedFeature==null){if(flashInitialized){clearSwfSelection();}}else{if(selectedFeature.model=='mpa'){if(flashInitialized){setSwfSelection(selectedFeature);}}else if(selectedFeature.model=='array'){if(flashInitialized){clearSwfSelection();}}else{}}}});$('#selection-breadcrumbs').selectioncrumbs({selectionManager:sm});};if(typeof Ext!='undefined'){Ext.namespace('MarineMap','MarineMap.ui');}else{if(typeof MarineMap!='object'){MarineMap={};}
if(typeof MarineMap.ui!='object'){MarineMap.ui={};}}
MarineMap.ui.handlers={};MarineMap.ui.copy={failedToLoadContent:'We could not load content from this url. The server may be experiencing temporary downtime. Please try again later, and contact an administrator if the error persists.',unknownError:'An unknown error occurred. Please try again and if the problem persists, contact an administrator.',errorTitle:'An Error Occurred',fatalErrorTitle:'A Fatal Error Occurred',fatalErrorMsg:'Due to the nature of this error, the application needs to be restarted. Please press the refresh button on your browser. We have been notified of the problem, but if the error persists please follow up with an administrator.',htmlLoadMessage:'While we load this content.'};MarineMap.ui.showMask=function(){$('#marinemap-mask').css('display','block');};MarineMap.ui.hideMask=function(){$('#marinemap-mask').css('display','none');};MarineMap.ui.accessObjectProperty=function(object,propstring){var trail=propstring.split('.');for(var i=0;i<trail.length;i++){object=object[trail[i]];}
return object;}
MarineMap.ui.modalManager={currentModal:null,nextModal:null,display:function(modal){if(modal.isAsync(modal.options)){modal.startAsync(modal.options);$(modal).bind('asyncDone',{mngr:this},this.asyncDone);MarineMap.ui.wait.show({msg:modal.options['waitMsg']});this.nextModal=modal;}else{if(this.currentModal){this.nextModal=modal;if(this.currentModal.open){if(this.currentModal.animating){this.currentModal.hide(true,true);}else{this.currentModal.hide(true,false);}}else{}}else{this.currentModal=modal;modal.display();}
$(this.currentModal).bind('hidden',{mngr:this},this.afterHide);}},afterHide:function(event){var m=event.data['mngr'];if(m.nextModal){m.currentModal=m.nextModal;$(m.currentModal).bind('hidden',event.handler);m.currentModal.display();}else{m.currentModal=null;}
m.nextModal=null;},asyncDone:function(e,success){if(success){e.data['mngr'].currentModal.hide(true,MarineMap.ui.wait.animating);}else{e.data['mngr'].nextModal=null;}}}
MarineMap.ui.Modal=function(){this.options={}
this.animating=false;this.open=false;this.show=function(opts){this.parseOpts(opts);MarineMap.ui.modalManager.display(this);};this.display=function(opts){var opts=this.options;MarineMap.ui.showMask();showElements(this.elements);this.render(this.options);this.open=true;this.animating=true;var i=this;if(/chrome/.test(navigator.userAgent.toLowerCase())){$(this.animatedElement).show();i.animating=false;i.afterRender(i.options);if(i.options['afterRender']){i.options['afterRender'](i.options);}
$(i).trigger('shown');}else{$(this.animatedElement).animate({height:'show',width:'show',opacity:'show'},'fast',function(){i.animating=false;i.afterRender(i.options);if(i.options['afterRender']){i.options['afterRender'](i.options);}
$(i).trigger('shown');});}};this.hide=function(keepMask,immediately){$(this.animatedElement).stop(true,true);var cleanup=this.cleanup;var opts=this.options;var i=this;this.animating=true;this.open=false;this.beforeHide(this.options);if(immediately||/chrome/.test(navigator.userAgent.toLowerCase())){$(this.animatedElement).hide();this.animating=false;hideElements(this.elements);if(!keepMask){MarineMap.ui.hideMask();}
this.cleanup(this.options);$(this).trigger('hidden');}else{$(this.animatedElement).animate({height:'hide',width:'hide',opacity:'hide'},'fast',function(){i.animating=false;hideElements(i.elements);if(!keepMask){MarineMap.ui.hideMask();}
i.cleanup(i.options);$(i).trigger('hidden');});}};this.render=function(opts){};this.afterRender=function(opts){};this.beforeHide=function(opts){};this.cleanup=function(opts){};this.parseOpts=function(opts){if(typeof opts!='object'){opts={}}
$.extend(this.options,this.defaults,opts);return this.options;};this.isAsync=function(opts){return false;};function showElements(elements){for(var i=0;i<elements.length;i++){$(elements[i]).show();}};function hideElements(elements){for(var i=0;i<elements.length;i++){$(elements[i]).hide();}};function showContent(el,callback){$(el).show('fast',callback);};function hideContent(el,callback){$(el).hide('fast',callback);};return true;}
MarineMap.ui.Wait=function(){this.elements=['#marinemap-small-modals'];this.animatedElement='#marinemap-wait';this.defaults={msg:''};this.render=function(opts){$('#marinemap-wait').find('p').html(opts['msg']);},this.cleanup=function(opts){$('#marinemap-wait').find('p').html('');}};MarineMap.ui.Wait.prototype=new MarineMap.ui.Modal();MarineMap.ui.wait=new MarineMap.ui.Wait();MarineMap.ui.Error=function(){this.elements=['#marinemap-small-modals'];this.animatedElement='#marinemap-error';this.defaults={errorText:MarineMap.ui.copy.unknownError,debugText:false,logText:false,fatal:false};this.render=function(opts){var error=$('#marinemap-error');var button=$('#marinemap-error').find('button');var heading=MarineMap.ui.copy.errorTitle;if(opts['fatal']){heading=MarineMap.ui.copy.fatalErrorTitle;if(opts['errorText']==MarineMap.ui.copy.unknownError){opts['errorText']=MarineMap.ui.copy.fatalErrorMsg;}
button.hide();}else{button.show();}
error.find('h3').html(heading);error.find('p').html(opts['errorText']);if(opts['logText']||opts['fatal']){MarineMap.ui.logToServer(opts['logText']);}},this.afterRender=function(opts){if(!opts['fatal']){var button=$('#marinemap-error').find('button');button.focus();button.click(function(){MarineMap.ui.error.hide()});}},this.cleanup=function(opts){$('#marinemap-error').find('p').html('');}}
MarineMap.ui.Error.prototype=new MarineMap.ui.Modal();MarineMap.ui.error=new MarineMap.ui.Error();MarineMap.ui.ModalWindow=function(){this.elements=['#marinemap-large-modals'];this.animatedElement='#marinemap-htmlmodal';this.defaults={width:500,closable:true,afterRender:false,html:false,url:false,waitMsg:MarineMap.ui.copy.htmlLoadMessage,errorCallback:false,retries:4,logText:'Problem loading url',fatal:false,errorText:MarineMap.ui.copy.failedToLoadContent};this.isAsync=function(opts){if(opts['html']){return false;}else{return true;}};this.startAsync=function(opts){if($.browser.msie){$.ajaxSetup({cache:false});}
var i=this;$('#marinemap-htmlmodal').load(opts['url'],null,function(response,status,request){i.asyncHandler(response,status,request);});};this.asyncHandler=function(response,status,request){modal=$('#marinemap-htmlmodal');if(status=='error'){if(this.options['retries']>0){this.options['retries']=this.options['retries']-1;var i=this;modal.load(this.options['url'],false,function(response,status,request){i.asyncHandler(response,status,request);});}else{$(this).trigger('asyncDone',false);if(this.options['errorCallback']){MarineMap.ui.wait.hide(false);this.options['errorCallback'](response,status,request);}else{this.options['logText']=this.options['logText']+': '+this.options['url'];MarineMap.ui.error.show(this.options);}}}else{$(this).trigger('asyncDone',true);}};this.render=function(opts){var modal=$('#marinemap-htmlmodal');modal.width(opts['width']);var buttons=$('#marinemap-htmlmodalbuttons');if(opts['closable']){buttons.width(opts['width']);$(document).bind('keydown',this.keydownHandler);$('#marinemap-htmlmodal-close')[0].onclick=function(){MarineMap.ui.modal.hide();return false;};}else{}
if(opts['html']){modal.html(opts['html']);}else{}};this.afterRender=function(opts){if(opts['closable']){$('#marinemap-htmlmodalbuttons').show();$('#marinemap-htmlmodal-close').show();}};this.beforeHide=function(opts){$('#marinemap-htmlmodalbuttons').hide();$('#marinemap-htmlmodal-close').hide();};this.cleanup=function(opts){$(document).unbind('keydown',this.keydownHandler);var modal=$('#marinemap-htmlmodal');modal.html('');};this.keydownHandler=function(event){if(event.keyCode==88||event.keyCode==27){$('#marinemap-htmlmodal-close').click();return false;}else{}};}
MarineMap.ui.ModalWindow.prototype=new MarineMap.ui.Modal();MarineMap.ui.modal=new MarineMap.ui.ModalWindow();MarineMap.ui.logToServer=function(msg,success,error){$.ajax({type:'POST',url:'/marinemap/client-logger',data:{msg:msg},success:success,error:error});};(function(){var cache={};this.tmpl=function tmpl(str,data){var fn=!/\W/.test(str)?cache[str]=cache[str]||tmpl(document.getElementById(str).innerHTML):new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};"+"with(obj){p.push('"+
str.replace(/[\r\t\n]/g," ").split("<%").join("\t").replace(/((^|%>)[^\t]*)'/g,"$1\r").replace(/\t=(.*?)%>/g,"',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'")
+"');}return p.join('');");return data?fn(data):fn;};})();MarineMap.ui.ContextMenu={}
MarineMap.ui.ContextMenu.show=function(opts,data,target){MarineMap.ui.ContextMenu.clear();if(target){$(target).addClass('contextified');}
if(!(opts['x']&&opts['y']&&opts['actions'])){throw('MarineMap.ui.ContextMenu.show(opts): you must specify "x", "y", and "actions".');}
if(!opts['icon']){opts['icon']='';}
var div=$('<div />');div.addClass('marinemap-contextmenu');div.attr('style','left:'+opts['x']+'px;top:'+opts['y']+'px;');var ul=$('<ul />');div.append(ul);for(var i=0;i<opts['actions'].length;i++){var li=$('<li class="'+opts['actions'][i]['iconcls']+'"><span>'+opts['actions'][i]['name']+'</span></li>');li.bind('click',data,opts['actions'][i]['handler']);ul.append(li);}
$('body').append(div);var width=div.width();div.width(width+15);var height=div.height();if(jQuery.browser.msie){div.addClass('ie');}
div.height(height);$('body').bind('click',MarineMap.ui.ContextMenu.clear);};MarineMap.ui.ContextMenu.clear=function(){$('.contextified').removeClass('contextified');$('body').unbind('click',MarineMap.ui.ContextMenu.clear);$('.marinemap-contextmenu').remove();};MarineMap.ui.SelectionManager=function(){this.selectedFeature=null;this.setSelectedFeature=function(feature,caller,force){if(force||feature!=this.selectedFeature){var oldFeature=this.selectedFeature;this.selectedFeature=feature;var event=jQuery.Event('selectionChange');if(caller){event.caller=caller;}
$(this).trigger(event,[this,this.selectedFeature,oldFeature]);}};this.clearSelection=function(caller){var oldFeature=this.selectedFeature;this.selectedFeature=null;var event=jQuery.Event('selectionChange');if(caller){event.caller=caller;}
$(this).trigger(event,[this,this.selectedFeature,oldFeature]);};};(function($){var Breadcrumbs={_init:function(){this.element.addClass('marinemap-ui-breadcrumbs');this.element.after('<br style="clear:both;" />');this._li=[];},push:function(object){this.element.find('li:last').removeClass('selected');var label=MarineMap.ui.accessObjectProperty(object,this.options.labelProperty);var li=$(this.options.liTemplate.replace(/#\{label\}/,label));li.css('display','none');li.css('white-space','nowrap');li.addClass('selected');var self=this;li.bind('click',function(event){var index=$(event.target).prevAll().length;self.element.trigger('itemClick',[object,index],self.options.itemClick);event.stopPropagation();event.preventDefault();return false;});this.element.append(li);li.animate({width:'show'},'fast','linear');this._li.push(object);this.element.trigger('push',[object,this._li.length-1],this.options.push);},clear:function(dontAnimate){var lis=this.element.find('li');lis.stop(true,true);this._remove(lis,dontAnimate);this.element.trigger('clear',[this._li],this.options.clear);this._li=[];},pop:function(dontAnimate){this._remove($(this.element.find('li')[this._li.length-1]),dontAnimate);var item=this._li.pop();this.element.trigger('pop',[item],this.options.pop);},length:function(){return this._li.length;},_remove:function(els,dontAnimate){if(dontAnimate){els.remove();}else{els.animate({width:'hide'},'fast','linear',function(){$(this).remove();});}},destroy:function(){this.clear(true);$.widget.prototype.destroy.apply(this,arguments);}}
$.widget('marinemap.breadcrumbs',Breadcrumbs);$.extend($.marinemap.breadcrumbs,{getter:'length',defaults:{labelProperty:'label',liTemplate:'<li>#{label}</li>'}});var SelectionCrumbs=$.extend({},$.marinemap.breadcrumbs.prototype);SelectionCrumbs._init=function(){$.marinemap.breadcrumbs.prototype._init.apply(this,arguments);$(this.options.selectionManager).bind('selectionChange',this,this._onSelectionChange);this.options.labelProperty='bcLabel';var self=this;$(this.element).bind('itemClick',function(event,object,index){if(index==self.length()-1){MarineMap.app.reportsVisor.toggle();}else{if(object.model=='array'){self.options.selectionManager.setSelectedFeature(object,this);}else{}}
return false;});};SelectionCrumbs.disable=function(){$(this.options.selectionManager).unbind('selectionChange',this,this._onSelectionChange);};SelectionCrumbs.enable=function(){$(this.options.selectionManager).unbind('selectionChange',this,this._onSelectionChange);$(this.options.selectionManager).bind('selectionChange',this,this._onSelectionChange);};SelectionCrumbs._onSelectionChange=function(event,mngr,selectedFeature,oldFeature){var self=event.data;if(selectedFeature==null){self.clear();}else{if(selectedFeature.model=='mpa'){selectedFeature.bcLabel=selectedFeature.name;if(oldFeature&&oldFeature.model=='mpa'){var oldArray=oldFeature.get_array();var selArray=selectedFeature.get_array();if(oldArray&&selArray&&oldArray.pk==selArray.pk){self.pop(true);self.push(selectedFeature);return;}else{self.clear();}}else{if(oldFeature&&oldFeature.model=='array'){if(selectedFeature.get_array()&&oldFeature.pk==selectedFeature.get_array().pk){self.push(selectedFeature);return;}else{self.clear();}}else{self.clear();}}
var selArray=selectedFeature.get_array();if(selArray){var a=selArray;a.bcLabel=a.name+'<span class="array-mpa-count"> (contains '+a.get_mpas().length+' MPAs) </span>';self.push(a);}
self.push(selectedFeature);}else{if(selectedFeature.model=='array'){self.clear();selectedFeature.bcLabel=selectedFeature.name+'<span class="array-mpa-count"> (contains '+selectedFeature.get_mpas().length+' MPAs) </span>';self.push(selectedFeature);}else{self.clear();}}}}
$.widget('marinemap.selectioncrumbs',SelectionCrumbs);$.extend($.marinemap.selectioncrumbs,{getter:'length',defaults:{labelProperty:'label',liTemplate:'<li>#{label}</li>'}});})(jQuery);if(typeof Ext!='undefined'){Ext.namespace('MarineMap','MarineMap.ui');}else{if(typeof MarineMap!='object'){MarineMap={};}
if(typeof MarineMap.ui!='object'){MarineMap.ui={};}}
MarineMap.ui.form={};MarineMap.ui.form.show=function(url,success,error,cancel,html){options={closable:false,afterRender:function(){var w=$('#marinemap-htmlmodal');w.find('input:first').focus();w.find('input[value="cancel"]').click(function(){MarineMap.ui.modal.hide();if(cancel){cancel();}});w.find('form').submit(function(){MarineMap.ui.modal.hide(true,true);MarineMap.ui.wait.show({});$.ajax({url:url,dataType:'json',data:$(this).serialize(),type:'POST',error:function(XMLHttpRequest,textStatus,errorThrown){if(XMLHttpRequest.status==400){MarineMap.ui.modal.hide(true,true);MarineMap.ui.form.show(url,success,error,cancel,XMLHttpRequest.responseText);}else if(XMLHttpRequest.status==401){MarineMap.ui.error.show({errorText:'You must be logged in to perform this operation.'});}else if(XMLHttpRequest.status==403){MarineMap.ui.error.show({errorText:'You cannot modify objects owned by other users.'});}else if(XMLHttpRequest.status==404){MarineMap.ui.error.show({errorText:'The object you are trying to edit does not exist.'});}else{MarineMap.ui.error.show({errorText:'An unknown server error occured. Please try again later.'});}},success:function(data,textStatus){success(data);}});return false;});},errorCallback:function(something,textStatus,XMLHttpRequest){if(XMLHttpRequest.status==400){MarineMap.ui.modal.hide(true,true);MarineMap.ui.form.show(url,success,error,cancel,XMLHttpRequest.responseText);}else if(XMLHttpRequest.status==401){MarineMap.ui.error.show({errorText:'You must be logged in to perform this operation.'});}else if(XMLHttpRequest.status==403){MarineMap.ui.error.show({errorText:'You cannot modify objects owned by other users.'});}else if(XMLHttpRequest.status==404){MarineMap.ui.error.show({errorText:'The object you are trying to edit does not exist.'});}else{MarineMap.ui.error.show({errorText:'An unknown server error occured. Please try again later.'});}}}
if(html){options['html']=html;}else{options['url']=url;}
MarineMap.ui.modal.show(options);}
MarineMap.ui.form.hide=function(){MarineMap.ui.model.hide();}
ï»¿Ext.namespace('MarineMap','MarineMap.widgets');MarineMap.widgets.URLViewer=Ext.extend(Ext.Panel,{html:'',title:'',url:'',load:function(url){Ext.Ajax.request({url:this.url,scope:this,success:function(response){this.body.update(response.responseText);},failure:function(){this.body.update('Sorry, there was an error requesting this content.');}});},initComponent:function(){Ext.apply(this,{frame:true,bodyStyle:'padding:10px'});MarineMap.widgets.URLViewer.superclass.initComponent.apply(this,arguments);this.load(this.url);}});mlpa={mpaForm:{}}
mlpa.mpaForm={selector:'#mpaFormTabs',msieDisabledColor:'#cfcfcf',show:function(opts){this.options=opts;if(typeof this.options['editUrl']=="string"&&typeof this.options['geometries']=="array"||(typeof this.options['geometries']!="array"&&typeof['mpa']!="object")){MarineMap.ui.error.show({errorText:'mpaForm called with invalid arguments. specify either mpa or geometries, and not both.'});return;}else{var geometry=false;if(typeof this.options['editUrl']=='string'){url=this.options['editUrl'];}else{url='/marinemap/mpa/new';geometry=this.options['geometries'][0];geometryClipped=this.options['geometries'][1];}
this.options['width']=650,MarineMap.ui.modal.hide(false,true);MarineMap.ui.modal.show({width:this.options['width'],url:url+' '+mlpa.mpaForm.selector,closable:false,afterRender:function(){if(geometry){$('input[name="geometry"]').attr('value',geometry);$('input[name="geometry_clipped"]').attr('value',geometryClipped);}
mlpa.mpaForm.init();},errorCallback:function(){MarineMap.ui.error.show({errorText:'Problem loading MPA attributes form. Please try again in a few minutes and contact an administrator if the problem persists.'})}});}},successHandler:function(mpa){},submitHandler:function(e){e.preventDefault();form=$('form.mpa-form');var i=this;$.ajax({data:form.serializeArray(),dataType:'json',success:function(data,textStatus){mlpa.mpaForm.successHandler(MarineMap.data.mlpaFeatures.mpa_from_geojson(data));},error:function(request,textStatus,errorThrown){i.options['html']=jQuery("<div/>").append(request.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(mlpa.mpaForm.selector);i.options['url']=false;i.options['afterRender']=function(){i.init(i.options);}
if(request.status==400){MarineMap.ui.modal.show(i.options);}else{if(typeof i.options['error']=='function'){i.options['error'](request);}else{MarineMap.ui.error.show({errorText:'There was a problem saving this MPA',debugText:request.responseText,logText:'Problem saving MPA Attributes'});}}},type:'POST',url:form.attr('action')});MarineMap.ui.wait.show({msg:'While we save your MPA'});return false;},allowedUsesPropertyMousedown:function(e){var designation_id=$('select#id_designation option:selected').attr('value');if(this.purposesForDesignation(designation_id).length==0){alert('The current MPA Designation does not allow any types of consumptive use. Please change the designation if you would like to add allowed uses.');return false;e.preventDefault();}},designationChange:function(e){var purposes=this.purposesForDesignation($('select#id_designation option:selected').attr('value'));if($('select#id_allowed_uses option:selected').length>0){var msg=false;if(purposes.length==0){msg="This designation does not allow any consuptive uses. All of your currently selected allowed uses will be removed.\n Do you still wish to change the MPA Designation?";}else if(purposes.length<$('select.purpose option').length-1){msg="This Designation only allows "+$('select.purpose option[value="'+purposes[0]+'"]').html()+" uses. Any other types of allowed uses you have selected will be removed. \n Do you still wish to change the MPA Designation?";}
var answer=true;if(msg){answer=confirm(msg);}
if(answer){this.currentDesignation=e.target.selectedIndex;if(msg){this.removeUsesNotMatchingDesignation();}
this.updatePurposes(purposes);}else{e.target.selectedIndex=this.currentDesignation;}}else{this.currentDesignation=e.target.selectedIndex;this.updatePurposes(purposes);}},updatePurposes:function(purposes){var msg='Any type of allowed use can be added to an MPA of this designation.';var last_select=false;this.clearingAllowedUses=true;$('#allowed_uses_widget select.choose').each(function(){this.selectedIndex=0;last_select=this;});this.clearingAllowedUses=false;$(last_select).trigger('change');if(purposes.length==0){msg='Allowed uses cannot be added to an MPA of this designation type.';$('#allowed_uses_widget select.choose').attr('disabled','disabled');}else if(purposes.length<$('select.purpose option').length-1){$('select.choose').attr('disabled',false);var option=$('select.purpose option[value="'+purposes[0]+'"]');option.attr('selected',true);$('select.purpose').attr('disabled',true);msg='MPAs with this designation can only have <em>'+option.html()+'</em> allowed uses.';}else{$('select.choose').attr('disabled',false);}
$('p#designation_purposes_warning').html(msg);$('#allowed_uses_widget select.choose').triggerHandler('change');},removeUsesNotMatchingDesignation:function(){var purposes=this.purposesForDesignation($('select#id_designation option:selected').attr('value'));var inst=this;$('#allowed_uses_widget table tbody tr').each(function(){var tr=$(this);if(purposes.length==0){inst.removeAllowedUse(tr);}else{var id=jQuery.trim(tr.find('td.pk').html());var remove=true;for(var i=0;i<purposes.length;i++){if(inst.allowed_uses_by_id[id]&&inst.allowed_uses_by_id[id]['purpose_id']==purposes[i]){remove=false;}}
if(remove){inst.removeAllowedUse(tr);}}});},addToLookup:function(obj,use,item,a,b,c){var key=' '+a+','+b+','+c;key=jQuery.trim(key);if(!obj[key]){obj[key]={};}
obj[key][item]=use;},createLookups:function(){this.currentDesignation=$('select#id_designation')[0].selectedIndex;this.allowed_uses=eval('('+$('#all_allowed_uses').html()+')');this.x_designations_purposes=eval('('+$('#x_designations_purposes').html()+')');this.allowed_uses_by_id={};this.allowed_uses_choice_lookup={};this.allowed_use_direct_lookup={};var lookup=this.allowed_uses_choice_lookup;for(var i=0;i<this.allowed_uses.length;i++){var use=this.allowed_uses[i];if(typeof use!='undefined'){this.allowed_uses_by_id[use['id']]=use;this.allowed_use_direct_lookup[' '+use['target_id']+','+use['method_id']+','+use['purpose_id']]=use;this.addToLookup(lookup,use,use['target_id'],'o','x','x');this.addToLookup(lookup,use,use['target_id'],'o',use['method_id'],use['purpose_id']);this.addToLookup(lookup,use,use['target_id'],'o',use['method_id'],'x');this.addToLookup(lookup,use,use['target_id'],'o','x',use['purpose_id']);this.addToLookup(lookup,use,use['method_id'],'x','o','x');this.addToLookup(lookup,use,use['method_id'],use['target_id'],'o',use['purpose_id']);this.addToLookup(lookup,use,use['method_id'],'x','o',use['purpose_id']);this.addToLookup(lookup,use,use['method_id'],use['target_id'],'o','x');this.addToLookup(lookup,use,use['purpose_id'],'x','x','o');this.addToLookup(lookup,use,use['purpose_id'],use['target_id'],use['method_id'],'o');this.addToLookup(lookup,use,use['purpose_id'],use['target_id'],'x','o');this.addToLookup(lookup,use,use['purpose_id'],'x',use['method_id'],'o');}}},makeSureIEDoesntLetUsersSelectDisabledOptions:function(e){var select=e.target;if(select.selectedIndex!=0){var option=select.options[select.selectedIndex];if($(option).css('color')==this.msieDisabledColor){var msg='This option cannot be selected in combination with your other selections';if($(select).hasClass('purpose')){msg=msg+', or the current MPA Designation. ';}else{msg=msg+'. ';}
msg=msg+'For example, you cannot choose method "By Hand" in combination with a target of "Salmon".';alert(msg);select.selectedIndex=0;e.preventDefault();return false;}}},init:function(){this.successHandler=this.options['success']
this.cancelHandler=this.options['cancel'];var inst=this;$('#mpaFormTabs button.cancel').click(function(e){inst.hide();inst.cancelHandler();});$('#allowed_uses_widget select.choose').bind('mousedown',function(e){inst.allowedUsesPropertyMousedown(e);});$('select#id_designation').bind('change',function(e){inst.designationChange(e);});if($.browser.msie){$('#allowed_uses_widget select.choose').bind('change',function(e){inst.makeSureIEDoesntLetUsersSelectDisabledOptions(e);});}
$('td.remove-allowed-use').each(function(){$(this).show();$(this).find('a').bind('click',function(e){inst.removeAllowedUse($(this).parent().parent());e.preventDefault();return false;});});$('a#add-use').click(function(e){var target=$('select.target option:selected').attr('value');var method=$('select.method option:selected').attr('value');var purpose=$('select.purpose option:selected').attr('value');if(target!='x'&&method!='x'&&purpose!='x'){var use=inst.allowed_use_direct_lookup[' '+target+','+method+','+purpose];inst.addAllowedUse(use);}else{alert('You must choose a Target, Method, and Use Type in order to add an Allowed Use');}
e.preventDefault();return false;});$('#allowed_uses_widget select.choose').bind('change',function(e){inst.allowedUsePropertySelectionChange(e);});$('#mpaFormTabs input[type="submit"]').bind('click submit',function(e){inst.submitHandler(e);});$('#forward').click(function(){if($('#forward').css('display')=='block'){var link=$('ul#form_shortcuts li.active').next().children('a');link.click();}
return false;});$('#backward').click(function(){if($(this).css('display')=='block'){var li=$('ul#form_shortcuts li.active').prev();$(li).children('a').click();}
return false;});$('#mpaFormTabs').keydown(function(e){if(e.keyCode==9){e.preventDefault();return false;}else if(e.keyCode==13){if($('#mpaFormTabs.create').length==0){var type=$(e.target).attr('type');if(type=='textarea'||type=='select'||type=='select-one'){return true;}else{e.preventDefault();$("#mpa_attr_submit").click();return false;}}}});$('ul#form_shortcuts li a').click(function(e){if(mlpa.mpaForm.transitioning==true){return false;}else{old_target=$('li.active a').attr('href');var old_href=old_target.replace(/[^#]*/,"");var href=$(this).attr('href');var href=href.replace(/[^#]*/,"");if(href==old_href){e.preventDefault();return false;}
mlpa.mpaForm.transitioning=true;$('ul#form_shortcuts li.active').removeClass('active');$(this).parent().addClass('active');var pos=$(href).prevAll().length
if(!inst.options['editUrl']){if(pos==0){$('#backward').css('display','none');}else{$('#backward').css('display','block');}
if(pos==$('div.formpane').length-1){$('#forward').css('display','none');$('#mpaFormTabs input[type="submit"]').css('display','block');}else{$('#forward').css('display','block');$('#mpaFormTabs input[type="submit"]').css('display','none');}}
var width=$('div.formpane').innerWidth();var offset=pos*width;mlpa.mpaForm.exitPanel($(old_href));$('div.form_content').animate({scrollLeft:offset},350,'linear',function(){mlpa.mpaForm.enterPanel($(href));});e.preventDefault();return false}});var errors=$('ul.errorlist');if(errors.length>0){var id="#"+$(errors[0]).parent().parent()[0].id;$('a[href*="'+id+'"]').click();}else{$('div.form_content').scrollLeft(0);mlpa.mpaForm.enterPanel($("#first_page"));$('#backward').css('display','none');}
this.createLookups();this.updatePurposes(this.purposesForDesignation($('select#id_designation option:selected').attr('value')));},purposesLookup:{},purposesForDesignation:function(des_id){if(des_id==''){des_id='null';}
if(this.purposesLookup[des_id]){return this.purposesLookup[des_id];}else{var purposes=[];for(var i=0;i<this.x_designations_purposes.length;i++){if(typeof this.x_designations_purposes[i]=='object'){if(des_id=='null'||this.x_designations_purposes[i]['designation_id']==des_id){purposes.push(this.x_designations_purposes[i]['purpose_id']);}}}
this.purposesLookup[des_id]=purposes;return this.purposesLookup[des_id];}},clearingAllowedUses:false,allowedUsePropertySelectionChange:function(e){if(this.clearingAllowedUses){return;}
var key=false;var target=e.currentTarget;var inst=this;$('select.choose').each(function(){if(this==target){return;}
var select=$(this);if($(select).hasClass('target')){var key='o'+','+$('select.method option:selected').attr('value')+','+$('select.purpose option:selected').attr('value');}else if($(this).hasClass('method')){var key=$('select.target option:selected').attr('value')+','+'o'+','+$('select.purpose option:selected').attr('value');}else{var key=$('select.target option:selected').attr('value')+','+$('select.method option:selected').attr('value')+','+'o';}
var choices=inst.allowed_uses_choice_lookup[key];if($(this).hasClass('purpose')){var purposes=inst.purposesForDesignation(inst.currentDesignation);}
select.find('option').each(function(){var value=$(this).attr('value');var hide=true;if(value=='x'){hide=false;}
if(!(choices&&!(typeof choices[value]==='object'))){hide=false;}
if(purposes){for(var j=0;j<purposes.length;j++){if(!hide&&purposes[j]==value){hide=false;}}}
if($.browser.msie){$(this).css('color',(hide?inst.msieDisabledColor:''));}else{$(this).attr('disabled',(hide?'disabled':''));}});});},addAllowedUse:function(use){if($('select#id_allowed_uses option[value="'+use['id']+'"]').attr('selected')){alert('You have already added this allowed use.');}else{$('tr.none').hide();$('select#id_allowed_uses option[value="'+use['id']+'"]').attr('selected',true);var row=['<tr style="background-color:#CBF1BE; display:none;">','<td class="pk" style="display:none;">',use['id'],'</td>','<td class="target">',$('select.target option:selected').html(),'</td>','<td class="method">',$('select.method option:selected').html(),'</td>','<td class="purpose">',$('select.purpose option:selected').html(),'</td>','<td class="remove-allowed-use">','<a title="remove" href="#"><img src="/marinemap/media/images/silk/icons/delete.png" /></a>','</td>','</tr>'];$('#allowed_uses_widget table tbody').prepend(row.join(''));var row=$('#allowed_uses_widget table tbody tr:first');var inst=this;row.find('td.remove-allowed-use a').bind('click',function(e){inst.removeAllowedUse($(this).parent().parent());});row.fadeIn(500,function(){row.css('background-color','transparent');});var last_select=false;this.clearingAllowedUses=true;$('#allowed_uses_widget select.choose').each(function(){if(!$(this).attr('disabled')){this.selectedIndex=0;last_select=this;}});this.clearingAllowedUses=false;$(last_select).trigger('change');}},removeAllowedUse:function(tr){tr=$(tr);var pk=jQuery.trim(tr.find('td.pk').html());var option=$('select#id_allowed_uses option[value="'+pk+'"]').attr('selected',false);tr.css('background-color','#ED979A');tr.fadeOut(300,function(){tr.remove();});},enterPanel:function(target){target.css('overflow-y','auto');form_elements=$(target).find(':input');if(form_elements.length>0){form_elements[0].focus();}
$(target).scrollTop(0);mlpa.mpaForm.transitioning=false;},hide:function(){MarineMap.ui.modal.hide();},transitioning:false,exitPanel:function(target){target.css('overflow-y','visible');}};if(typeof MarineMap!='object'){MarineMap={};}
if(typeof MarineMap.ui!='object'){MarineMap.ui={};}
MarineMap.ui.ClientStore=function(){var stores={};var loadCount=0;var self=this;function addToStore(item,updated,added){if(!item.model){throw('No model specified');}
if(!item.pk){throw('No pk specified');}
if(!stores[item.model]){stores[item.model]={}}
if(stores[item.model][item.pk]==undefined){if(added[item.model]==undefined){added[item.model]=[];}
added[item.model].push(item);}else{var olditem=stores[item.model][item.pk];if(item.dateModified!=undefined&&item.dateModified<=olditem.dateModified){}else{if(updated[item.model]==undefined){updated[item.model]=[];}
updated[item.model].push([item,olditem]);}}
stores[item.model][item.pk]=item;}
function removeFromStore(item){if(stores[item.model]){delete stores[item.model][item.pk]}else{throwNoStore(item.model);}}
function throwNoStore(model){var msg='An entry for the store has not been created for model "';throw(msg+model+'"');}
function keys(){var keys=[];for(var key in stores){keys.push(key);}
return keys;}
return{get:function(model,pk){if(stores[model]){return stores[model][pk];}else{throwNoStore(model)}},remove:function(item){var items={};if(jQuery.isArray(item)){for(var i=0;i<item.length;i++){if(items[item[i].model]==undefined){items[item[i].model]=[];}
items[item[i].model].push(item[i])
removeFromStore(item[i]);}}else{items[item.model]=[item];removeFromStore(item)}
$(this).trigger('removed',[items]);},add:function(item){var updated={};var added={};if(jQuery.isArray(item)){for(var i=0;i<item.length;i++){addToStore(item[i],updated,added);item[i].store=this;}}else{addToStore(item,updated,added);item.store=this;}
var callAdded=false;for(var key in added){callAdded=true;}
var callUpdated=false;for(var key in updated){callUpdated=true;}
if(callAdded){$(this).trigger('added',[added]);}
if(callUpdated){$(this).trigger('updated',[updated]);}},clear:function(){stores={};loadCount=0;},each:function(model,func){if(stores[model]){for(var key in stores[model]){func(stores[model][key]);}}else{throwNoStore(model)}},load:function(items){if(loadCount!=0){throw('Load called more than once!');}else{loadCount=1;for(var key in items){var data=items[key];for(var i=0;i<data.length;i++){addToStore(data[i],{},{});data[i].store=this;}}
$(this).trigger('loaded',[items]);}},reload:function(items){var added={};var updated={};var forRemoval=[];for(var key in items){var keep={};for(var i=0;i<items[key].length;i++){var item=items[key][i];addToStore(item,updated,added);item.store=this;keep[item.pk]=true;}
this.each(key,function(data){if(keep[data.pk]==undefined){forRemoval.push(data);}});}
this.remove(forRemoval);$(this).trigger('updated',[updated]);$(this).trigger('added',[added]);},getAll:function(type){return stores[type];}}};(function($){var Tree={_init:function(){var self=this;this.element.addClass('marinemap-tree');this.defaults={classname:'',id:'',context:false,select:false,doubleclick:false,hideByDefault:false,collapsible:false,toggle:false,icon:false,metadata:'',children:false,extra:'',description:false};this._template=tmpl(['<li class="','<%= (context ? "context " : "") %>','<%= (toggle ? "toggle " : "") %>','<%= (select ? "select " : "unselectable ") %>','<%= (doubleclick ? "doubleclick " : "") %>','<%= (hideByDefault ? "hideByDefault " : "") %>','<%= classname %> <%= id %> <%= metadata %> marinemap-tree-item','">','<% if(collapsible) { %>','<span class="collapsible"><img src="/marinemap/media/images/core/arrow-right.png" width="9" height="9" /></span>','<% } %>','<% if(toggle) { %>','<input type="checkbox"></input>','<% } %>','<% if(icon) { %>','<img class="icon" src="<%= icon %>" width="16" height="16" />','<% } %>','<a href="#"><%= name %></a>','<span class="badges"><%= extra %></span>','<% if(description){ %>','<p class="description"><%= description %></p>','<% } %>','<% if(children) { %>','<% if(collapsible) { %>','<ul style="display:none;"><%= children %></ul>','<% }else{ %>','<ul><%= children %></ul>','<% } %>','<% } else if(collapsible) { %>','<ul style="display:none;"></ul>','<% } %>','</li>'].join(''))
$(this).find('span.collapsible').live('click',function(event){event.preventDefault();var list=$(this).parent().find('>ul');if(list.find('li').length==0){list.html('<p class="no-items">No items.</p>');}else{list.find('p.no-items').remove();}
if(list.css('display')=='none'){$(this).toggleClass('expanded',true);}else{$(this).toggleClass('expanded',false);}
if(event&&event.button!=undefined){list.slideToggle('fast');}else{list.toggle();}
var img=$(this).find('img');if($(this).find('img[src*=/marinemap/media/images/core/arrow-right.png]').length!=0){img.attr('src',"/marinemap/media/images/core/arrow-down.png");}else{img.attr('src',"/marinemap/media/images/core/arrow-right.png");}
return false;});$(this).find('li.marinemap-tree-item a').live('dblclick',function(event){if($(event.target).parent().hasClass('doubleclick')){$(self.element).trigger('itemDoubleClick',[$(event.target).parent().metadata(),event]);}
event.preventDefault();return false;});$(this).find('li a').live('contextmenu',function(event){var item=$(event.target).parent();if(item.hasClass('context')){self.element.trigger('itemContext',[event,item.metadata(),item]);}
event.preventDefault();return false;});$(this).find('li.marinemap-tree-item a').live('click',function(event){if(event.button==2){}else{var parent=$(event.target).parent();if(parent.hasClass('select')){var e=jQuery.Event("itemSelect");self.element.trigger(e,[parent.metadata(),parent]);if(!e.isDefaultPrevented()){self.selectItem(parent);}}else{var e=jQuery.Event("itemSelect");self.element.trigger(e,[null,parent]);if(!e.isDefaultPrevented()){self.clearSelection();}}
event.preventDefault();return false;}});$(this).find('li span.collapsible, li span.collapsible a').live('contextmenu',function(event){event.preventDefault();return false;});$(this).find('li.marinemap-tree-item input[type=checkbox]').live('click',function(e){var element=$(this);var checked=element.attr('checked');var parent=element.parent();if(parent.hasClass('selected')){var e=jQuery.Event('itemSelect');self.element.trigger(e,[null,null]);if(!e.isDefaultPrevented()){self.clearSelection();}}
var clickedData=[parent.metadata()];var list=parent.find('>ul');if(list.length>0){self._toggleCheckboxes(list,checked,clickedData);}
parent.parents('li.toggle').each(function(){var el=$(this);if(checked==true){el.find(' > input[type=checkbox]').attr('checked',true);}else{if(el.find('> ul input[type=checkbox][checked=true]').length==0){el.find('> input[type=checkbox]').attr('checked',false);}
if(el.hasClass('selected')){self.clearSelection();self.element.trigger('itemSelect',[null,null]);}}});self.element.trigger('itemToggle',[clickedData,checked]);if(checked==false){if(parent.find('li.selected').length>0){parent.find('li.selected').removeClass('selected');var e=jQuery.Event("itemSelect");self.element.trigger(e,[null,null]);}}});},selectItem:function(item,scrollTo){var wasHidden=false;if(typeof item=='string'){item=this.element.find(item);wasHidden=this._expandAndToggleRecursive(item);}else{item=$(item);}
var input=item.find('>input');var wasChecked=input.attr('checked');if(!wasChecked){input.click();}
var list=item.find('>ul');var checked=[]
if(list.length>0){this._toggleCheckboxes(list,true,checked);}
if(!wasChecked||checked.length){this.element.trigger('itemToggle',[checked,true]);}
var data=[];this.clearSelection();this._toggleCheckboxes(item,true,data);item.addClass('selected');if(scrollTo){var s=(this.options.scrollEl)?$(this.options.scrollEl):$(this.element).parent();var parent=s.parent();var ph=parent.height();var st=s.scrollTop();var visibleBounds=[st,st+ph-20];var position=$(item).position().top+st;if(position>visibleBounds[0]&&position<visibleBounds[1]){}else{s.scrollTop(position-(ph/2)+20);}}},_expandAndToggleRecursive:function(item,wasHidden){if(!(wasHidden===true||wasHidden===false)){wasHidden=false;}
var parent=item.parent().parent();if(parent.hasClass('marinemap-tree-item')){if(parent.find('>ul:visible').length==0){wasHidden=true;parent.find('>span.collapsible').click();}
var input=parent.find('>input');if(input){input.attr('checked',true);}
return this._expandAndToggleRecursive(parent,wasHidden);}else{return wasHidden;}},clearSelection:function(){$(".marinemap-tree li.selected").removeClass('selected');},_toggleCheckboxes:function(el,state,data){var self=this;el.find('>li.toggle').each(function(){var hideByDefault=$(this).hasClass('hideByDefault');if(hideByDefault&&state){}else{var input=$(this).find('>input');if(input.attr('checked')!=state){input.attr('checked',state);data.push($(this).metadata());}
var ul=$(this).find('>ul');if(ul.length>0){self._toggleCheckboxes(ul,state,data);}}});},add:function(options){var element=this._rTemplate(options);var parent;if(typeof options['parent']=='string'){parent=this.element.find(options['parent']);}else if(typeof options['parent']=='undefined'){parent=this.element;}else{parent=options['parent'];}
if(parent==this.element){var ul=parent;}else{var ul=parent.find('>ul');if(ul.size()==0){parent.append('<ul></ul>');var ul=parent.find('>ul');}}
if(ul.find('li').length==0){ul.html('');}
ul.append(element);var element=ul.find('.'+options['id']);options=null;return element;},renderTemplate:function(options){if(jQuery.isArray(options)){var strings=[];for(var i=0;i<options.length;i++){strings.push(this._rTemplate(options[i]));}
return strings.join('');}else{var string=this._rTemplate(options);return string;}},_rTemplate:function(options){return this._template(jQuery.extend({},this.defaults,options));},nodeExists:function(selector){if(this.element.find(selector).length>0){return true;}else{return false;}}}
$.widget('marinemap.tree',Tree);$.extend($.marinemap.tree,{getter:['add','nodeExists','renderTemplate'],defaults:{defaultItemTemplate:'<li><h3><%= name %></h3></li>',categoryTemplate:'<li><h2><img src="<%= ( obj.icon ? icon : "/marinemap/media/images/silk/icons/folder.png") %>" width="9" height="9" /><%= label %></h2></li>',idProperty:'id',modelProperty:'model',modelTemplates:{},scrollEl:false,contextMenu:function(event,element,id){}}});})(jQuery);if(typeof Ext!='undefined'){Ext.namespace('MarineMap','MarineMap.ui');}else{if(typeof MarineMap!='object'){MarineMap={};}
if(typeof MarineMap.ui!='object'){MarineMap.ui={};}}
MarineMap.ui.data={from_json:function(json,lookup){var hash={}
for(var key in json){var klass=lookup[key];hash[key]=[];for(var i=0;i<json[key].length;i++){hash[key].push(new klass(json[key][i]));}}
return hash;}};if(typeof Ext!='undefined'){Ext.namespace('MarineMap','MarineMap.ui');}else{if(typeof MarineMap!='object'){MarineMap={};}
if(typeof MarineMap.ui!='object'){MarineMap.ui={};}}
MarineMap.ui.UserManager=function(){return{user:null,setUser:function(user,caller){var oldUser=this.user;this.user=user;$(this).trigger('change',[user,oldUser,this,caller]);}}}
if(window.MarineMap==undefined){MarineMap={};}
if(MarineMap.data==undefined){MarineMap.data={};}
MarineMap.data.extend=function(self,data,required){jQuery.extend(self,data);if(self['display_properties']){delete self['display_properties']['child_nodes'];}
for(var i=0;i<required.length;i++){if(data[required[i]]==undefined){throw(required[i]+' was undefined');}}};MarineMap.data.mlpaFeatures={MPA:function(data){MarineMap.data.extend(this,data,['model','pk','user']);this.client_id=this.model+'_'+this.pk;return this;},Array:function(data){MarineMap.data.extend(this,data,['model','pk','mpa_ids','user']);this.client_id=this.model+'_'+this.pk;return this;},User:function(data){MarineMap.data.extend(this,data,['model','pk','name']);this.client_id=this.model+'_'+this.pk;return this;},Group:function(data){MarineMap.data.extend(this,data,['model','pk','users']);this.client_id=this.model+'_'+this.pk;return this;},Designation:function(data){MarineMap.data.extend(this,data,['model','pk']);this.client_id=this.model+'_'+this.pk;return this;},parser:new OpenLayers.Format.GeoJSON({})};jQuery.extend(MarineMap.data.mlpaFeatures.MPA.prototype,{editUrl:function(){return'/marinemap/mpa/edit/'+this.pk;},get_array:function(){if(!this.array){return null;}else{if(this.store){return this.store.get('array',this.array);}else{throw('Cannot find Array, this MPA does not belong to a store.');}}},callWithFeature:function(func){if(!this._listeners){this._listeners=[];}
this._listeners.push(func);if(this.feature){this._featureLoadedCallback();}else{if(this._loadingFeatures!=true){this._requestFeature();}}},_requestFeature:function(){return this.array&&this.store.get('array',this.array)?this.get_array().loadFeatures():this.loadFeature()},loadFeature:function(){var mpa=this;mpa._loadingFeatures=true;jQuery.ajax({error:function(XMLHttpRequest,textStatus,errorThrown){mpa._loadingFeatures=false;mpa._listeners=[];MarineMap.ui.error.show({errorText:'Could not load MPA geometry. Please try turning the MPA on/off again. If the error persists, please contact <a href="mailto:help@lists.marinemap.org?subject=mpa_geometry_broken">email help</a>'});},success:function(data,textStatus){mpa._loadingFeatures=false;var parser=MarineMap.data.mlpaFeatures.parser;mpa.feature=parser.read(data,'Feature');mpa._featureLoadedCallback();},type:'GET',url:'/marinemap/geojson/mpa/'+this.pk});},_featureLoadedCallback:function(){this.feature.attributes.mpa=this;if(this._listeners){while(this._listeners.length){var callback=this._listeners.shift();callback(this,this.feature);}}},setFeature:function(f){this.feature=f;this._featureLoadedCallback();},get_user:function(){if(this.store){return this.store.get('user',this.user);}else{throw('Cannot find User, this MPA does not belong to a store.');}},get_sharing_groups:function(){if(this.sharing_groups==undefined){return[];}
if(this.store){var sharing_groups=[];for(var i=0;i<this.sharing_groups.length;i++){var sg=this.store.get('group',this.sharing_groups[i]);if(sg){sharing_groups.push(sg);}}
return sharing_groups;}else{throw('Cannot find sharing_groups, this MPA does not belong to a store.');}},get_designation:function(){if(!this.store){throw('Cannot find Designation. This MPA does not belong to a store.');}else{if(this.designation){return this.store.get('designation',this.designation);}else{return null;}}},saveGeometryChanges:function(geometry,geometry_clipped,opts){$.ajax({data:{geometry:geometry,geometry_clipped:geometry_clipped},url:'/marinemap/mpa/editgeom/'+this.pk,success:function(data,textStatus){var mpa=MarineMap.data.mlpaFeatures.mpa_from_geojson(data);if(typeof opts['success']=='function'){opts['success'](mpa);}},error:opts['error'],dataType:'json',type:'POST'});}});MarineMap.data.mlpaFeatures.mpa_from_geojson=function(data){var mpa=new MarineMap.data.mlpaFeatures.MPA(data.properties);var parser=MarineMap.data.mlpaFeatures.parser;mpa.setFeature(parser.read(data,'Feature'));return mpa;}
MarineMap.data.mlpaFeatures.array_and_mpas_from_geojson=function(data){var array=new MarineMap.data.mlpaFeatures.Array(data['properties']);array.feature=true;var mpas=[];var features=MarineMap.data.mlpaFeatures.parser.read(data);for(var i=0;i<features.length;i++){var mpa=new MarineMap.data.mlpaFeatures.MPA(features[i].attributes);mpa.setFeature(features[i]);mpas.push(mpa);}
return[array,mpas];}
jQuery.extend(MarineMap.data.mlpaFeatures.Array.prototype,{get_user:function(){if(this.store){return this.store.get('user',this.user);}else{throw('Cannot find User, this Array does not belong to a store.');}},get_sharing_groups:function(){if(this.sharing_groups==undefined){return[];}
if(this.store){var sharing_groups=[];for(var i=0;i<this.sharing_groups.length;i++){var sg=this.store.get('group',this.sharing_groups[i]);if(sg){sharing_groups.push(sg);}}
return sharing_groups;}else{throw('Cannot find sharing_groups, this Array does not belong to a store.');}},get_mpas:function(){var pk=this.pk;if(this.store){var mpas=[];this.store.each('mpa',function(mpa){if(mpa.array==pk){mpas.push(mpa);}});return mpas;}else{throw('Cannot find MPAs, this Array does not belong to a store.');}},callWithFeature:function(func){if(!this._listeners){this._listeners=[];}
this._listeners.push(func);if(this.feature){this._featureLoadedCallback();}else{if(this._loadingFeatures!=true){this.loadFeatures();}}},loadFeatures:function(){if(this._loadingFeatures!=true){this._loadingFeatures=true;var array=this;jQuery.ajax({error:function(XMLHttpRequest,textStatus,errorThrown){array._loadingFeatures=false;array._listeners=[];MarineMap.ui.error.show({errorText:'Could not load Array FeatureCollection. Please try turning the Array on/off again. If the error persists, please contact <a href="mailto:help@lists.marinemap.org?subject=mpa_geometry_broken">email help</a>'});},success:function(data,textStatus){var parser=MarineMap.data.mlpaFeatures.parser;array.feature=true;var features=parser.read(data);array.each_mpa(function(mpa){for(var i=0;i<features.length;i++){if(features[i].fid=='mpa_'+mpa.pk){var f=features[i];}}
if(f){mpa.setFeature(f);}else{alert('could not find mpa',f.fid);}});array._loadingFeatures=false;array._featureLoadedCallback();},type:'GET',url:'/marinemap/geojson/array/'+this.pk});}},_featureLoadedCallback:function(){if(this._listeners){while(this._listeners.length){var callback=this._listeners.shift();callback(this);}}},each_mpa:function(func){var pk=this.pk;if(this.store){this.store.each('mpa',function(mpa){if(mpa.array==pk){func(mpa);}});}else{throw('Cannot find MPAs, this Array does not belong to a store.');}},get_users:function(){if(!this.store){throw('Object not in store.');}else{var users=[];for(var i=0;i<this.users.length;i++){users.push(this.store.get('user',this.users[i]));}
return users;}}});MarineMap.data.mlpaFeatures.lookup={'user':MarineMap.data.mlpaFeatures.User,'group':MarineMap.data.mlpaFeatures.Group,'mpa':MarineMap.data.mlpaFeatures.MPA,'array':MarineMap.data.mlpaFeatures.Array,'designation':MarineMap.data.mlpaFeatures.Designation};(function($){$.extend({metadata:{defaults:{type:'class',name:'metadata',cre:/({.*})/,single:'metadata'},setType:function(type,name){this.defaults.type=type;this.defaults.name=name;},get:function(elem,opts){var settings=$.extend({},this.defaults,opts);if(!settings.single.length)settings.single='metadata';var data=$.data(elem,settings.single);if(data)return data;data="{}";if(settings.type=="class"){var m=settings.cre.exec(elem.className);if(m)data=m[1];}else if(settings.type=="elem"){if(!elem.getElementsByTagName)return;var e=elem.getElementsByTagName(settings.name);if(e.length)data=$.trim(e[0].innerHTML);}else if(elem.getAttribute!=undefined){var attr=elem.getAttribute(settings.name);if(attr)data=attr;}if(data.indexOf('{')<0)data="{"+data+"}";data=eval("("+data+")");$.data(elem,settings.single,data);return data;}}});$.fn.metadata=function(opts){return $.metadata.get(this[0],opts);};})(jQuery);if(window.MarineMap==undefined){MarineMap={};}
if(MarineMap.widgets==undefined){MarineMap.widgets={};}
MarineMap.widgets.FeaturesMenu=function(options){var self=this;if(!(options&&options['selectionManager']&&options['store']&&(options['renderTo']||options['extWindow']))){throw('MarineMap.widgets.FeaturesMenu created without appropriate options');}
if(options['extWindow']){this.extWindow=new Ext.Window({x:50,y:50,width:350,height:420,html:'<div id="extTreeContainer" style="font-size:1.4em;"><ul id="extWindow"></ul></div>',autoScroll:true,closable:false,minimizable:true,listeners:{'minimize':function(w){self.getExtButton().toggle(false);}},bbar:[MarineMap.actions.drawMPA,MarineMap.actions.createArray],tbar:[{text:'How to Use This',handler:function(){MarineMap.actions.nonExt.openTreeTutorial();},iconCls:'new-help'}]});this.extWindow.show();this.extWindow.hide();this.extWindow.getBottomToolbar().hide();options['renderTo']=$('#extWindow');var _scrollEl=$(this.extWindow.element).find('.x-window-body');}else{var _scrollEl=$(options['renderTo'].parent());}
if(!$(options['renderTo']).length){throw('MarineMap.widgets.FeaturesMenu: Could not find root object');}
var _userManager=options['userManager'];var _sm=options['selectionManager'];var _store=options['store'];var _renderTo=options['renderTo'];this.tree=$(options['renderTo']).tree({scrollEl:_scrollEl});var self=this;$(_store).bind('added',function(e,data){if(data['array']){for(var i=0;i<data['array'].length;i++){var array=data['array'][0];self._addArray(array);}}
if(data['mpa']&&data['mpa'].length){for(var i=0;i<data['mpa'].length;i++){var mpa=data['mpa'][i];self._addMpa(mpa);}}else{}});$(_store).bind('removed',function(e,items){if(items['array']&&items['array'].length){for(var i=0;i<items['array'].length;i++){var array=items['array'][0];self.tree.find('li.'+items['array'][0].client_id).css('background-color','red').fadeOut('slow',function(){$(this).remove();});}}else if(items['mpa']&&items['mpa'].length){for(var i=0;i<items['mpa'].length;i++){self.tree.find('li.'+items['mpa'][0].client_id).css('background-color','red').fadeOut('slow',function(){$(this).remove();});}}else{}});$(_store).bind('updated',function(e,items){if(items['array']&&items['array'].length){for(var i=0;i<items['array'].length;i++){self._replaceArray(items['array'][i][0],items['array'][i][1]);}}
if(items['mpa']&&items['mpa'].length){for(var i=0;i<items['mpa'].length;i++){self._replaceMpa(items['mpa'][i][0],items['mpa'][i][1]);}}});$(_sm).bind('selectionChange',function(event,oldFeature,newFeature){if(event.caller!=self){if(newFeature){self.tree.tree('selectItem','.'+newFeature.model+'_'+newFeature.pk,true);}else{self.tree.tree('clearSelection');}}});$(this.tree).bind('itemSelect',function(event,meta,element){if(meta&&meta.model){_sm.setSelectedFeature(_store.get(meta.model,meta.pk),self);}else{_sm.clearSelection(self);}});this.tree.bind('itemToggle',function(event,items,state){var features=[];for(var i=0;i<items.length;i++){if(items[i]['model']=='mpa'){features.push(_store.get(items[i]['model'],items[i]['pk']));}}
$(self).trigger('mpaToggle',[features,state]);});this.tree.find('a.sharedmsg img').live('click',function(e){var m=$(this).parent().parent().parent().metadata();var item=_store.get(m.model,m.pk);var groups=item.get_sharing_groups();var names=[];for(var i=0;i<groups.length;i++){names.push(groups[i].name);}
alert('This item is shared with the following groups: '+names.join(', '));e.preventDefault();return false;});this.tree.bind('itemDoubleClick',function(e,data,originalEvent){if(data['model']=='array'||data['model']=='mpa'){var feature=_store.get(data['model'],data['pk']);$(self).trigger('featureDoubleClick',[feature]);}});this.tree.bind('itemContext',function(event,mouseEvent,data,target){var item=_store.get(data.model,data.pk);var actions=[];var data={};if(item.model=='mpa'){actions=[{name:'View Attributes',handler:function(e){MarineMap.actions.openMpaAttributes.execute(e.data,{});},iconcls:'mm-context-view'},{name:'Download KML',iconcls:'mm-context-kml',handler:function(e){MarineMap.actions.openUrl('/marinemap/kml/mpa/'+e.data.mpa.pk);}}];if(_userManager.user){actions.push({name:'Copy',iconcls:'mm-context-copy',handler:function(e){MarineMap.actions.nonExt.copyMpa(e.data.mpa.pk);}});}
if(_userManager.user&&item.user==_userManager.user.pk){actions.push({name:'Edit',handler:MarineMap.actions.nonExt.editMpaAttributes,iconcls:'mm-context-edit'});actions.push({name:'Delete',handler:MarineMap.actions.nonExt.deleteMPA,iconcls:'mm-context-delete'})}
data={mpa:item};}else if(item.model=='array'){data={array:item};actions=[{name:'Basic Info',iconcls:'mm-context-view',handler:function(e){MarineMap.actions.nonExt.openArrayBasicInfo(e.data.array.pk);}},{name:'Download KML',iconcls:'mm-context-kml',handler:function(e){MarineMap.actions.openUrl('/marinemap/kml/array/'+e.data.array.pk);}},{name:'Download Shapefile',iconcls:'mm-context-view',handler:function(e){MarineMap.actions.openUrl('/marinemap/array/shapefile/'+e.data.array.pk);}}];if(_userManager.user){actions.push({name:'Copy',iconcls:'mm-context-copy',handler:function(e){MarineMap.actions.nonExt.copyArray(e.data.array.pk);}});actions.push({name:'Replication Report',iconcls:'mm-context-view',handler:function(e){MarineMap.actions.openArrayReplication(e.data.array.pk);}});}
if(_userManager.user&&_userManager.user.pk==item.user){actions.push({name:'Edit',iconcls:'mm-context-edit',handler:function(e){MarineMap.actions.nonExt.createOrModifyArray(e.data.array.pk);}});actions.push({name:'Delete',iconcls:'mm-context-delete',handler:function(e){MarineMap.actions.nonExt.deleteArray(e.data.array);}});actions.push({name:'Delete Array and MPAs',iconcls:'mm-context-delete',handler:function(e){MarineMap.actions.nonExt.deleteArrayAndMpas(e.data.array);}});}
actions.push({name:'Array Summary',iconcls:'mm-context-view',handler:function(e){MarineMap.actions.openStaffSummary(e.data.array.pk);}});if(_userManager.user&&_userManager.user.is_staff){actions.push({name:'habitat cross-tab',iconcls:'mm-context-view',handler:function(e){MarineMap.actions.openHabitatPauloFormat(e.data.array.pk);}});actions.push({name:'Attributes Spreadsheet',iconcls:'mm-context-view',handler:function(e){MarineMap.actions.openAttributesCSV(e.data.array.pk);}});actions.push({name:'Spacing Matrix Spreadsheet',iconcls:'mm-context-view',handler:function(e){MarineMap.actions.openSpacingMatrixCSV(e.data.array.pk);}});}}else if(item.model=='user'){data={user:item};actions=[{name:'About this User',handler:function(e){MarineMap.actions.nonExt.openUserInfo(e.data.user);},iconcls:'mm-context-view'}]}else{throw('cannot create contextmenu for item that is not an mpa or array.');}
MarineMap.ui.ContextMenu.show({x:mouseEvent.pageX,y:mouseEvent.pageY,actions:actions},data,target);});var features=[];var me;this.init=function(data){features=[];var hash={'mpa':[],'array':[]}
for(var i=0;i<data.features.length;i++){features.push(_renderNodeToString(data.features[i],hash,this.tree));}
$(_store).bind('loaded',function(){$(self.tree).html(features.join(''));});for(var i=0;i<hash['mpa'].length;i++){delete hash['mpa'][i]['children'];}
for(var i=0;i<hash['array'].length;i++){delete hash['array'][i]['children'];}
var self=this;return hash;};this._addMpa=function(mpa){var opts=this._optionsForMpa(mpa);if(mpa.array){opts['parent']='.'+mpa.get_array().client_id;}else{opts['parent']='.'+mpa.folder;}
var node=self.tree.tree('add',opts);};this._optionsForMpa=function(mpa){var opts=mpa.display_properties;opts['metadata']="{model: '"+mpa.model+"', pk: "+mpa.pk+"}";opts['name']=mpa.name;opts['id']=mpa.model+'_'+mpa.pk;if(_userManager.user&&mpa.user==_userManager.user.pk&&mpa.sharing_groups.length){opts['extra']='<a href="#" class="sharedmsg" title=""><img class="sharing" src="/marinemap/media/images/silk/icons/star.png" width="16" height="16" /></a>';}
return opts;};this._replaceMpa=function(mpa,old_mpa){var existing=this.tree.find('.'+mpa.client_id);if(mpa.array==old_mpa.array&&existing.length){var html=this._renderMpaToHtml(mpa);existing.replaceWith(html);}else{existing.remove();this._addMpa(mpa);}};this._renderMpaToHtml=function(mpa){var options=this._optionsForMpa(mpa);return this.tree.tree('renderTemplate',options);};this._addArray=function(array){var opts=this._optionsForArray(array);if(array.public_proposal){opts['parent']='.folder_publicProposals';}else if(array.proposed){opts['parent']='.folder_draftProposals';}else{opts['parent']='.folder_user_arrays';}
var node=self.tree.tree('add',opts);};this._replaceArray=function(array,old_array){if(array.proposed==old_array.proposed&&array.public_proposal==old_array.public_proposal){var html=this._renderArrayToHtml(array);this.tree.find('.'+array.client_id).replaceWith(html);}else{this.tree.find('li.'+array.client_id).remove();this._addArray(array);}};this._renderArrayToHtml=function(array){var options=this._optionsForArray(array);return this.tree.tree('renderTemplate',options);};this._optionsForArray=function(array){var opts=array.display_properties;opts['metadata']="{model: '"+array.model+"', pk: "+array.pk+"}";opts['name']=array.name;opts['id']=array.model+'_'+array.pk;if(_userManager.user&&array.user==_userManager.user.pk&&array.sharing_groups.length){opts['extra']='<a href="#" class="sharedmsg" title=""><img class="sharing" src="/marinemap/media/images/silk/icons/star.png" width="16" height="16" /></a>';}
return opts;};function _renderNodeToString(node,data,tree){var s;var children=false;if(node.display_properties.children){var rendered=[]
for(var i=0;i<node.display_properties.children.length;i++){rendered.push(_renderNodeToString(node.display_properties.children[i],data,tree));}
children=rendered.join('');}
var opts=node.display_properties;if(typeof node.pk=='string'){opts['metadata']="{model: '"+node.model+"', pk: '"+node.pk+"'}";}else{opts['metadata']="{model: '"+node.model+"', pk: "+node.pk+"}";}
opts['name']=node.name;opts['id']=node.model+'_'+node.pk
if(node.model=='mpa'||node.model=='array'){data[node.model].push(new MarineMap.data.mlpaFeatures.lookup[node.model](node));if(_userManager.user&&node.user==_userManager.user.pk&&node.sharing_groups.length&&!node.proposed&&!node.public_proposal){opts['extra']='<a href="#" class="sharedmsg" title=""><img class="sharing" src="/marinemap/media/images/silk/icons/star.png" width="16" height="16" /></a>';}}
if(children){opts['children']=children;}
s=tree.tree('renderTemplate',opts);return s;};this.disable=function(){};this.enable=function(){};this.showSpinner=function(){this.tree.append('<div class="marinemap-text-right-spinner">Loading</div>');};this.hideSpinner=function(){this.tree.find('.marinemap-text-right-spinner').remove();};this.toggleFeature=function(feature){this.tree.find('li.'+feature.model+'_'+feature.pk+' > input').click();};this.showTools=function(){this.extWindow.getBottomToolbar().show();},this.hideTools=function(){this.extWindow.getBottomToolbar().hide();this.extWindow.doLayout();},this.clear=function(){this.tree.html('');};this.getExtButton=function(){if(this._button){return this._button;}else{var self=this;this._button=new Ext.Button({text:'MPAs, Arrays, and Proposals',enableToggle:true,toggleHandler:function(button,state){if(state){self.extWindow.show(button.id);}else{self.extWindow.hide(button.id);}}});return this._button;}};}