/*
 * Mapping application
 * Author Steve McArthur.
 * Copyright(c)  London Borough of Hackney,2009.
 * 
 * This code is licensed under BSD license. Use it as you wish, 
 * but keep this copyright intact.
 */


Ext.namespace('Ext.ux');Ext.ux.GMapPanel=Ext.extend(Ext.Panel,{initComponent:function(){var defConfig={plain:true,zoomLevel:3,yaw:180,pitch:0,zoom:0,gmapType:'map',border:false,ieResize:function(){},afterMapReady:function(){},coorFn:function(point){alert("coorFn");return point;}};Ext.applyIf(this,defConfig);Ext.ux.GMapPanel.superclass.initComponent.call(this);},afterRender:function(){var wh=this.ownerCt.getSize();Ext.applyIf(this,wh);Ext.ux.GMapPanel.superclass.afterRender.call(this);if(this.gmapType==='map'){this.gmap=new GMap2(this.body.dom);GEvent.bind(this.gmap,'load',this,function(){this.onMapReady();});if(Ext.isIE){this.ieResize=function(){this.gmap.checkResize();}}}
if(this.gmapType==='panorama'){this.gmap=new GStreetviewPanorama(this.body.dom);}
if(typeof this.addControl=='object'&&this.gmapType==='map'){this.gmap.addControl(this.addControl);}
if(typeof this.setCenter==='object'){if(typeof this.setCenter.geoCodeAddr==='string'){this.geoCodeLookup(this.setCenter.geoCodeAddr);}else{if(this.gmapType==='map'){var point=new GLatLng(this.setCenter.lat,this.setCenter.lng);this.gmap.setCenter(point,this.zoomLevel);}
if(typeof this.setCenter.marker==='object'&&typeof point==='object'){this.addMarker(point,this.setCenter.marker,this.setCenter.marker.clear);}}
if(this.gmapType==='panorama'){this.gmap.setLocationAndPOV(new GLatLng(this.setCenter.lat,this.setCenter.lng),{yaw:this.yaw,pitch:this.pitch,zoom:this.zoom});}}
this.baseIcon=new GIcon();this.baseIcon.iconSize=new GSize(32,32);this.baseIcon.shadowSize=new GSize(56,32);this.baseIcon.iconAnchor=new GPoint(16,16);this.baseIcon.infoWindowAnchor=new GPoint(32,0);this.smallIcon=new GIcon();this.smallIcon.iconSize=new GSize(16,16);this.smallIcon.iconAnchor=new GPoint(8,8);this.smallIcon.infoWindowAnchor=new GPoint(16,0);},onMapReady:function(){this.addMarkers(this.markers);this.addMapControls();this.addOptions();this.afterMapReady();},onResize:function(w,h){if(typeof this.getMap()=='object'){this.gmap.checkResize();this.ieResize.defer(250,this);}
Ext.ux.GMapPanel.superclass.onResize.call(this,w,h);},onGeocode:function(){},assignCoordFn:function(Fn){this.coorFn=Fn;},setSize:function(width,height,animate){if(typeof this.getMap()=='object'){this.gmap.checkResize();}
Ext.ux.GMapPanel.superclass.setSize.call(this,width,height,animate);},getMap:function(){return this.gmap;},getMapDomContainer:function(){return this.body.dom},getCenter:function(){return this.getMap().getCenter();},setCenter:function(LL){this.gmap.setCenter(LL);},getCenterLatLng:function(){var ll=this.getCenter();return{lat:ll.lat(),lng:ll.lng()};},addMarkers:function(markers){if(Ext.isArray(markers)){for(var i=0;i<markers.length;i++){var mkr_point=new GLatLng(markers[i].lat,markers[i].lng);this.addMarker(mkr_point,markers[i].marker,false,markers[i].setCenter,markers[i].listeners);}}},getIcon:function(image,shadow,type){if(type==="small"){return new GIcon(this.smallIcon,image,null,"");}else{return new GIcon(this.baseIcon,image,null,shadow);}},addMarker:function(point,marker,clear,center,listeners){Ext.applyIf(marker,G_DEFAULT_ICON);if(clear===true){this.getMap().clearOverlays();}
if(center===true){this.getMap().setCenter(point);}
var mark=new GMarker(point,marker);if(typeof listeners==='object'){for(evt in listeners){GEvent.bind(mark,evt,this,listeners[evt]);}}
this.getMap().addOverlay(mark);return mark;},addMapControls:function(){if(this.gmapType==='map'){if(Ext.isArray(this.mapControls)){for(i=0;i<this.mapControls.length;i++){this.addMapControl(this.mapControls[i]);}}else if(typeof this.mapControls==='string'){this.addMapControl(this.mapControls);}else if(typeof this.mapControls==='object'){this.getMap().addControl(this.mapControls);}}},addMapControl:function(mc){var mcf=window[mc];if(typeof mcf==='function'){this.getMap().addControl(new mcf());}},addOptions:function(){if(Ext.isArray(this.mapConfOpts)){var mc;for(i=0;i<this.mapConfOpts.length;i++){this.addOption(this.mapConfOpts[i]);}}else if(typeof this.mapConfOpts==='string'){this.addOption(this.mapConfOpts);}},addOption:function(mc){var mcf=this.getMap()[mc];if(typeof mcf==='function'){this.getMap()[mc]();}},setMapType:function(mapType){var m=this.getMap();if(mapType==='SAT'){m.setMapType(G_SATELLITE_MAP);}else if(mapType==='HYB'){m.setMapType(G_HYBRID_MAP);}else if(mapType==='NORM'){m.setMapType(G_NORMAL_MAP);}},svOverlay:null,svPano:null,hideStreetView:function(){if(this.svOverlay){this.getMap().removeOverlay(this.svOverlay);this.svOverlay=null;}},checkResize:function(){this.getMap().checkResize();},resizeStreetView:function(){if(this.svPano){this.svPano.checkResize();}},geoCodeLookup:function(addr){this.geocoder=new GClientGeocoder();this.geocoder.getLocations(addr,this.addAddressToMap.createDelegate(this));},addAddressToMap:function(response){if(!response||response.Status.code!=200){Ext.MessageBox.alert('Error','Code '+response.Status.code+' Error Returned');}else{place=response.Placemark[0];addressinfo=place.AddressDetails;accuracy=addressinfo.Accuracy;if(accuracy===0){Ext.MessageBox.alert('Unable to Locate Address','Unable to Locate the Address you provided');}else{if(accuracy<7){Ext.MessageBox.alert('Address Accuracy','The address provided has a low accuracy.<br><br>Level '+accuracy+' Accuracy (8 = Exact Match, 1 = Vague Match)');}else{point=new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);if(typeof point==='object'){this.addMarker(point,null,true,true,null);}}}
this.onGeocode();}}});Ext.reg('gmappanel',Ext.ux.GMapPanel);

Ext.namespace('HK');HK.MapApp=Ext.extend(Ext.Viewport,{iconpath:'http://www.map.hackney.gov.uk/Icons/silk/',disclaim:'disclaimer.txt',showDisclaim:false,startupMask:true,loadIndicator:true,startUpFn:Ext.emptyFn,distFn:Ext.emptyFn,typeAheadFn:Ext.emptyFn,defLat:51.545023,defLng:-0.069724,defZoom:13,orgName:'London Borough of Hackney',maskHtml:'<div id="loading-mask" style="width:100%;height:100%;background:#aca899;position:absolute; z-index:20000;left:0;top:0;"></div>',loadingHtml:'<div id="loading2">'+'<div class="loading-indicator" id="loading-ind">'+'<span>London Borough of Hackney</span>'+'<img src="images/Wait_Ani3.gif" style="width: 108px; height: 64px;" align="absmiddle">'+'<span>Please wait...</span></div></div>',layout:'border',id:'myViewPort',headerContent:'',headerLoad:'',headerStyle:'',typeAheadURL:'',initComponent:function(){var defheaderConfig={region:'north',border:false,collapsible:true,collapseMode:'mini',split:true,height:90};Ext.applyIf(this.headerConfig,defheaderConfig);this.headerPanel=new Ext.Panel(this.headerConfig);Ext.apply(this,{items:[this.headerPanel,{region:'center',id:'vp-center',layout:'fit',titlebar:true,autoScroll:true,closeOnTab:true}]});HK.MapApp.superclass.initComponent.call(this);},AddToolBar:function(themap){var self=this;var tb=new Ext.Toolbar({id:'tbar',autoHeight:true,renderTo:'top-div'});tb.addSpacer();var srchRec=Ext.data.Record.create([{name:'name',mapping:'name'},{name:'id',mapping:'id'}]);var ds=null;if(!Ext.isEmpty(this.typeAheadURL)){ds=new Ext.data.Store({proxy:new Ext.data.ScriptTagProxy({url:this.typeAheadURL}),reader:new Ext.data.JsonReader({id:'post_id',root:'results',totalProperty:'thecount'},srchRec)});}
var resultTpl=new Ext.XTemplate('<tpl for="."><div class="search-item">','<span>{name}</span>','</div></tpl>');var comboObj={id:'searchBox',displayField:'name',loadingText:'Searching...',enableKeyEvents:true,emptyText:"Address,street or postcode",typeAhead:false,hideTrigger:true,minChars:3,tpl:resultTpl,itemSelector:'div.search-item',blankText:"Please enter a property description,postcode or UPRN first"}
if(ds){comboObj.store=ds;}
var stxtbox=new Ext.form.ComboBox(comboObj);tb.add('<span style="color:#000000">Search:</span>',stxtbox);var mybtn=new Ext.Toolbar.Button({text:'GO!',handler:onButtonClick,icon:this.iconpath+'lightning_go.png',height:40,cls:'x-btn-text-icon bsearch'});tb.addButton(mybtn);function onTestClick(btn){var el=Ext.getCmp('center-map').body.dom;HK.mapcontrol.ResizeTheMap();HK.mapcontrol.DrawBounds();msg("Test wid="+el.style.width+", ht="+el.style.height);}
function onButtonClick(btn){var s=stxtbox.getValue();self.addressSearch(s);}
var queryIntecept=function(e){var newValue=e.query;newValue=newValue.replace(/\b\d*\s?/,"");if((newValue.length<3)||(Ext.isEmpty(ds)))
return false
else
return true;}
function onFireKey(f,e){if(e.isSpecialKey()){onButtonClick();return;}}
stxtbox.addListener('beforequery',queryIntecept);stxtbox.addListener('keypress',onFireKey);return tb;},afterRender:function(){HK.MapApp.superclass.afterRender.call(this);this.showLoadingIndicator(this.loadIndicator);this.showStartupMask(this.startupMask);this.disclaimer(this.showDisclaim);this.createPanels();},getCenter:function(){return Ext.getCmp('vp-center');},createPanels:function(){var vp=this;if(!this.mapPanel){this.bottomPanel=new Ext.Panel({region:'south',closable:false,header:true,defaults:{style:'text-align:left'},layout:'fit',height:200,collapsible:true,collapseMode:'mini',collapsed:true,split:true});this.mapPanel=new Ext.Panel({layout:'border',items:[{xtype:'gmappanel',region:'center',zoomLevel:this.defZoom,id:'themap',coorFn:this.distFn,home:{lat:this.defLat,lng:this.defLng,zoomLevel:this.defZoom},gmapType:'map',setCenter:{lat:this.defLat,lng:this.defLng}},this.bottomPanel]});}
this.theMap=this.mapPanel.findByType('gmappanel')[0];this.theMap.bottom=this.bottomPanel;var noFlash=function(){var btn=Ext.getCmp('btn-sv');if(btn){btn.hide();}};this.theMap.afterMapReady=function(){Ext.ux.StreetViewPanel(this.bottom,this,noFlash);};this.tb=this.AddToolBar(this.theMap);this.topPanel=new Ext.BoxComponent({region:'north',el:'top-div',items:[this.tb]});this.mtb=new Ext.Toolbar({id:'mapbar',hidden:false,autoHeight:true});this.centerPanel=new Ext.Panel({region:'center',id:'center-pnl',autoScroll:false,closeOnTab:true,defaults:{style:'text-align:left'},layout:'fit',tbar:this.mtb,bbar:[{hidden:true,style:"text-align:left"}],items:[this.mapPanel]});this.centerPanel.addListener('render',function(scope){vp.AddMapButtons(vp.mtb,vp.theMap);});this.tabs=new Ext.TabPanel({border:false,activeTab:0,tabPosition:'top',id:'west-tab-pnl'});this.innerlayout=new Ext.Panel({layout:'border',defaults:{bodyStyle:'text-align:left'},items:[this.topPanel,this.centerPanel,{region:'west',id:'west-panel',split:true,width:250,header:true,collapsible:true,collapsed:false,layout:'fit',animate:true,items:this.tabs}]});Ext.getCmp('vp-center').add(this.innerlayout);this.addressSearch=function(sAdd){this.theMap.geoCodeLookup(sAdd);}},AddMapButtons:function(tb,m){var self=this;var map=m;var btn=new Ext.Toolbar.Button({handler:onHomeClick,text:'Home',height:40,icon:this.iconpath+'house_go.png',tooltip:{title:'Return map to start position',autoHide:true},disabled:false,cls:'x-btn-text-icon bsearch'});tb.addButton(btn);var btnZin=new Ext.Toolbar.Button({handler:zoomIn,text:'Zoom in',height:40,icon:this.iconpath+'zoom_in.png',tooltip:{title:'Zoom map in for closer look',autoHide:true},disabled:false,cls:'x-btn-text-icon bsearch'});tb.addButton(btnZin);var btnZout=new Ext.Toolbar.Button({handler:zoomOut,text:'Zoom out',height:40,icon:this.iconpath+'zoom_out.png',tooltip:{title:'Zoom map out for wider look',autoHide:true},disabled:false,cls:'x-btn-text-icon bsearch'});tb.addButton(btnZout);tb.addSpacer();tb.addSeparator();tb.addSpacer();var btnMap4=new Ext.Toolbar.Button({handler:satSV,text:'Street View Map',id:'btn-sv',mapType:'STREETVIEW',height:40,icon:this.iconpath+'page_world.png',tooltip:{title:'Street View Panorama',autoHide:true},disabled:false,cls:'x-btn-text-icon bsearch'});tb.addButton(btnMap4);var btnMap1=new Ext.Toolbar.Button({handler:satMap,text:'Satellite Map',id:'btn-sat',mapType:'SAT',height:40,icon:this.iconpath+'page_world.png',tooltip:{title:'Satellite map view',autoHide:true},disabled:false,cls:'x-btn-text-icon bsearch'});tb.addButton(btnMap1);var btnMap2=new Ext.Toolbar.Button({handler:satMap,text:'Hybrid Map',id:'btn-hyb',mapType:'HYB',height:40,icon:this.iconpath+'page_world.png',tooltip:{title:'Combination of normal map view and satellite map view',autoHide:true},disabled:false,cls:'x-btn-text-icon bsearch'});tb.addButton(btnMap2);var btnMap3=new Ext.Toolbar.Button({handler:satMap,text:'Normal Map',id:'btn-norm',mapType:'NORM',height:40,icon:this.iconpath+'page_world.png',tooltip:{title:'Normal map view',autoHide:true},disabled:true,cls:'x-btn-text-icon bsearch'});tb.addButton(btnMap3);tb.addSpacer();tb.addSeparator();tb.addSpacer();function satSV(btn){var close=map.svOverlay;self.showStreetView(close);}
function satMap(btn){map.setMapType(btn.mapType);btnMap1.setDisabled(false);btnMap2.setDisabled(false);btnMap3.setDisabled(false);btn.setDisabled(true);}
function onHomeClick(btn){var h=map.home;var point=new GLatLng(h.lat,h.lng);map.getMap().setCenter(point,h.zoomLevel);}
function zoomOut(){map.getMap().zoomOut();setZoomBtns(map.getMap().getZoom());}
function zoomIn(){map.getMap().zoomIn();setZoomBtns(map.getMap().getZoom());}
function setZoomBtns(i){if(i>16){btnZin.disable();btnZout.enable();}
else
if(i<13){btnZin.enable();btnZout.disable();}
else{btnZin.enable();btnZout.enable();}}},showLoadingIndicator:function(show){if(show==true){var loader=Ext.get('loading2');if(Ext.isEmpty(loader)){var html=this.loadingHtml;var bod=Ext.getBody();bod.insertHtml('beforeEnd',html);loader=Ext.get('loading2');}
loader.setVisible(true);}
else{var loader=Ext.get('loading2');if(!Ext.isEmpty(loader)){loader.remove();}}},showStartupMask:function(show){var mask=Ext.get('loading-mask');if(show==true){if(Ext.isEmpty(mask)){var html=this.maskHtml;var bod=Ext.getBody();bod.insertHtml('beforeEnd',html);mask=Ext.get('loading-mask');}
mask.setOpacity(.8);}
else{if(!Ext.isEmpty(mask)){mask.setVisible(false);}}},disclaimer:function(show){var then=this;var AAfn=this.startUpFn;if(show==true){Ext.Ajax.request({url:this.disclaim,method:'GET',success:disclaimSuccess,failure:disclaimFailed});}
else{var dis=Ext.get("loading");if(!Ext.isEmpty(dis)){dis.setVisible(false);this.startUpFn();}}
function disclaimSuccess(result){var AAobj=result.responseText
var bod=Ext.getBody();bod.insertHtml('beforeEnd',AAobj);Ext.get("loading").setVisible(true);var by=Ext.get('btnyes');var bn=Ext.get('btnno');by.on('click',acceptClick);bn.on('click',declineClick);}
function disclaimFailed(result){alert('Disclaimer not found');}
function declineClick(){acceptClick('N');}
function acceptClick(s){if(s=='N'){window.location.assign("http://www.hackney.gov.uk");}
else{var loading=Ext.get('loading');if(!Ext.isEmpty(loading)){loading.remove();}
loading=Ext.get('loading2');var mask=Ext.get('loading-mask');if((!Ext.isEmpty(mask))&&(!Ext.isEmpty(loading))){mask.shift({xy:loading.getXY(),width:loading.getWidth(),height:loading.getHeight(),remove:true,duration:1,opacity:.3,easing:'bounceOut',callback:function(){loading.fadeOut({duration:.2,remove:true});then.startUpFn();}});}}
return false;}
if(this.showDisclaim==false){acceptClick('Y');}},collapseWest:function(){var pnl=Ext.getCmp('west-panel');pnl.collapse(true);},expandWest:function(){var pnl=Ext.getCmp('west-panel');pnl.expand(false);},collapseBanner:function(collapse){var pnl=this.headerPanel;if(collapse){pnl.collapse(true);}
else{pnl.expand(true);}},closeBanner:function(close,time){this.collapseBanner.defer(time,this,[close]);},assignDistFn:function(fn){this.distFn=fn;this.theMap.assignCoordFn(fn);},searchFunction:function(fn){this.addressSearch=fn;},showLoading:function(show){showLoadingIndicator(show);},getsearchFunction:function(){return this.addressSearch;},getMapPanel:function(){return this.theMap;},closeWest:function(close,time){if(close==true){this.collapseWest.defer(time);}
else{this.expandWest.defer(time);}},addTab:function(id,title,html){this.tabs.add({id:id,title:title,html:html,autoHeight:false,autoScroll:true,layout:'fit'}).show();},showStreetViewDlg:function(){return this.bottomPanel.body.dom;},showStreetView:function(){if(!this.bottomPanel.collapsed){this.bottomPanel.collapse();}
else{this.bottomPanel.expand();}},getTab:function(name){var theTab=tabs.findById(name);if(Ext.isEmpty(theTab)){theTab=tabs.find('title',name);}
return theTab;},getTabPanel:function(){return this.tabs;},getToolbar:function(){return this.tb;},getMapToolbar:function(){return this.mtb;}});Ext.reg('hkmap',HK.MapApp);
