var currentFlag = null;

/*
 Google Map Icons
 */

var currentFlag=null;var baseIcon=new GIcon();baseIcon.shadow="/images/shadow_standard.png";baseIcon.iconSize=new GSize(16,30);baseIcon.shadowSize=new GSize(37,34);baseIcon.iconAnchor=new GPoint(8,30);baseIcon.infoWindowAnchor=new GPoint(8,2);baseIcon.infoShadowAnchor=new GPoint(12,17);var selfIcon=new GIcon(baseIcon);selfIcon.image="/images/flag_self.png";var friendIcon=new GIcon(baseIcon);friendIcon.image="/images/flag_friend.png";var publicIcon=new GIcon(baseIcon);publicIcon.image="/images/flag_public.png";var newIcon=new GIcon(baseIcon);newIcon.image="/images/flag_new.png";var Flag=Class.create();Flag.prototype={initialize:function(map,flagId,longitude,latitude,title,owner,relationship){this.map=map;if(this.map.browser)this.browser=this.map.browser;this.id=flagId;this.owner=owner;this.title=title;this.element=$("flag-"+flagId);this.point=new GLatLng(latitude,longitude);this.createGmarker(longitude,latitude,relationship);GEvent.addListener(this.marker,"click",this.clicked.bind(this));GEvent.addListener(this.marker,"mouseover",this.mousedOver.bind(this));GEvent.addListener(this.marker,"mouseout",this.mousedOut.bind(this));this.map.gmap.addOverlay(this.marker);},createGmarker:function(longitude,latitude,relationship){switch(relationship){case"self":this.marker=new GMarker(this.point,selfIcon);break;case"friend":this.marker=new GMarker(this.point,friendIcon);break;case"public":this.marker=new GMarker(this.point,publicIcon);break;}},destroy:function(){this.map.gmap.removeOverlay(this.marker);this.element=null;},reset:function(){GEvent.removeListener(this.map.closeInfoWindowListener);this.map.closeInfoWindowListener=null;this.marker.openInfoWindow(currentFlag);setTimeout("map.closeInfoWindowListener = GEvent.addListener(map.gmap, 'infowindowclose', Map.prototype.infoWindowClosed.bind(map))",500);},load:function(){var login=new Cookie("login").get();var is_logged_in=new Cookie("is_logged_in").get();if(this.owner==login&&is_logged_in){url="/flags/"+this.id+"/map_edit";}else{url="/flags/"+this.id+"/map_view";}
this.map.busy();this.map.gmap.closeInfoWindow();if(this.browser&&this.browser.activeFlag){this.browser.activeFlag(this);this.browser.showDialog("/flags/"+this.id+"/preview");}
new Ajax.Request(url,{method:'get',evalScripts:true,onFailure:this.errored,onComplete:this.loaded.bind(this)});},updateTitle:function(title){var element=$("preview_title");if(title.length>26){title=title.substring(0,26)+"...";}
Element.hide(element);element.innerHTML=title;Element.show(element);this.title=title;},loaded:function(request){this.map.complete();page.state["current_flag"]=this.id;currentFlag=document.createElement("div");currentFlag.id="current_gmap_flag";Element.update(currentFlag,request.responseText);this.marker.openInfoWindow(currentFlag);this.map.gmap.getInfoWindow().hide();this.map.infoWindowOpen=true;initLightbox();},mousedOver:function(){if(this.title!=""){this.tooltip=new Tooltip(this);this.map.gmap.addOverlay(this.tooltip);}},mousedOut:function(){if(this.tooltip){this.map.gmap.removeOverlay(this.tooltip);}},errored:function(request){alert("Oops! There was an error retrieving the flags. Try again.");},clicked:function(){if(!this.map.addFlagMode){this.map.flagClick=true;this.load();}}}
function Tooltip(flag){this.flag=flag;}
Tooltip.prototype=new GOverlay();Tooltip.prototype.initialize=function(map){this.map=map;this.div=document.createElement("div");var point,top,left;point=this.map.fromLatLngToDivPixel(this.flag.marker.getPoint());left=point.x;top=point.y;this.div.id="map_tooltip";this.div.style.top=top+'px';this.div.style.left=left+'px';Element.update(this.div,this.flag.title);map.getPane(G_MAP_MARKER_PANE).appendChild(this.div);}
Tooltip.prototype.remove=function(){this.div.parentNode.removeChild(this.div);}
Tooltip.prototype.copy=function(){return new Tooltip(this.flag);}
Tooltip.prototype.redraw=function(force){if(!force)return;var point=this.map.fromLatLngToDivPixel(this.flag.marker.getPoint());this.div.style.left=point.x+"px";this.div.style.top=point.y+"px";}
var Map=Class.create();Map.prototype={infoWindowOpen:false,firstLoad:true,browser:false,map:null,resizeToFill:true,lastCLat:null,lastCLng:null,minLng:null,maxLng:null,minLat:null,maxLat:null,newFlag:null,initialize:function(){this.flags=new Array();this.flagIdsToFlags=new $H([]);this.addFlagMode=false;this.gMapDblClick=false;this.flagClick=false;this.gmap=new GMap2($("map"));new GKeyboardHandler(this.gmap);this.gmap.addControl(new GLargeMapControl());this.gmap.addControl(new GMapTypeControl());GEvent.addListener(this.gmap,'maptypechanged',this.mapChanged.bind(this));window.onresize=this.resized.bindAsEventListener(this);this.moveListener=GEvent.addListener(this.gmap,'moveend',this.moved.bind(this));this.moveBegunListener=GEvent.addListener(this.gmap,'movestart',this.moveBegun.bind(this));this.zoomListener=GEvent.addListener(this.gmap,'zoomend',this.zoomed.bind(this));this.clickListener=GEvent.addListener(this.gmap,'click',this.clicked.bind(this));this.closeInfoWindowListener=GEvent.addListener(this.gmap,'infowindowclose',this.infoWindowClosed.bind(this));},setMap:function(id){this.map=id;this.clear();this.load("/maps/"+this.map+"/flags","inclusive");},getMap:function(){return this.map},getQueryString:function(){var query=$H([]);if(!this.map&&page.state["ownership"])query["ownership"]=page.state["ownership"];if(page.state["page"])query["page"]=page.state["page"];if(page.state["min_lat"])query["min_lat"]=page.state["min_lat"];if(page.state["max_lat"])query["max_lat"]=page.state["max_lat"];if(page.state["min_lng"])query["min_lng"]=page.state["min_lng"];if(page.state["max_lng"])query["max_lng"]=page.state["max_lng"];if(page.state["search"])query["search"]=page.state["search"];if(this.firstLoad&&page.state["c_lat"]&&page.state["c_lat"]){this.setCenterQuietly(new GLatLng(page.state["c_lat"],page.state["c_lng"]),parseInt(page.state["map_zoom"]));bounds=this.gmap.getBounds();page.state["min_lat"]=bounds.getSouthWest().lat();page.state["max_lat"]=bounds.getNorthEast().lat();page.state["min_lng"]=bounds.getSouthWest().lng();page.state["max_lng"]=bounds.getNorthEast().lng();query["min_lat"]=page.state["min_lat"];query["max_lat"]=page.state["max_lat"];query["min_lat"]=page.state["min_lat"];query["max_lng"]=page.state["max_lat"];}
return query.toQueryString();},getDefaultUrl:function(){var user=page.getOwner();if(user!==""){if(this.map){return"/maps/"+this.map+"/flags?"+this.getQueryString();}else{return"/flags/"+user+"/xml?"+this.getQueryString();}}else{if(this.map){return"/maps/"+this.map+"/flags?"+this.getQueryString();}else{return"/flags/xml?"+this.getQueryString();}}},setCenterQuietly:function(latLng,zoom){if(this.moveBegunListener){GEvent.removeListener(this.moveBegunListener);delete this.moveBegunListener;}
if(this.moveListener){GEvent.removeListener(this.moveListener);delete this.moveListener;}
this.gmap.setCenter(latLng,zoom);this.moveListener=GEvent.addListener(this.gmap,'moveend',this.moved.bind(this));this.moveBegunListener=GEvent.addListener(this.gmap,'movestart',this.moveBegun.bind(this));},addFlag:function(longitude,latitude){if(map){this.removeNewestFlag();var point=new GLatLng(latitude,longitude);var marker=new GMarker(point,newIcon);this.gmap.addOverlay(marker);this.newFlag=marker;}},removeNewestFlag:function(){if(this.newFlag!=null){this.gmap.removeOverlay(this.newFlag);delete this.newFlag;this.newFlag=null;}},enableAddFlagMode:function(){if(!this.addFlagMode){this.closeInfoWindowQuietly();if(browserName=="Safari"){$('map').ondblclick=this.dblClicked.bind(this);}else{Event.observe("map","dblclick",this.dblClicked.bind(this),false);}
this.addFlagMode=true;}},disableAddFlagMode:function(){if(!this.addFlagMode)return;if(this.browser&&this.browser.klass=='Browser')this.browser.prepareBusy();flag_title="";flag_description="";flag_tag_names="";if(browserName=="Safari"){$('map').ondblclick=null;}else{Event.stopObserving("map","dblclick",this.dblClicked.bind(this),false);}
if(page.state["limbo_id"])delete page.state["limbo_id"];this.addFlagMode=false;if(this.browser&&this.browser.klass=='Browser')this.browser.flags(page.state["ownership"]);},showTip:function(){new Effect.Appear('map_search_tip');setTimeout("new Effect.Fade('map_search_tip')",5000);},busy:function(){busy("map_busy");},complete:function(){complete("map_busy");},closeInfoWindowQuietly:function(){GEvent.removeListener(this.closeInfoWindowListener);this.gmap.closeInfoWindow();this.closeInfoWindowListener=GEvent.addListener(this.gmap,'infowindowclose',this.infoWindowClosed.bind(this));},load:function(url,zoom){this.busy();this.lastCLat=page.state["c_lat"];this.lastCLng=page.state["c_lng"];this.zoom=zoom;if(url===""||url===undefined)url=this.getDefaultUrl();new Ajax.Request(url,{method:"get",onComplete:this.loaded.bind(this)});},clear:function(){sorted=this.flags.sort();for(i=0;i<sorted.length;i++){this.flagIdsToFlags[sorted[i][1]].destroy();delete this.flagIdsToFlags[sorted[i][1]];}
this.flags=new Array();},loaded:function(request){var flag,sorted,max,i;var xmlDoc=request.responseXML;var markers=xmlDoc.documentElement.getElementsByTagName("marker");this.complete();if(this.moveListener){GEvent.removeListener(this.moveListener);delete this.moveListener;}
if(this.moveBegunListener){GEvent.removeListener(this.moveBegunListener);delete this.moveBegunListener;}
if(this.zoomListener){GEvent.removeListener(this.zoomListener);delete this.zoomListener;}
var cLat=xmlDoc.documentElement.getAttribute("lat");var cLng=xmlDoc.documentElement.getAttribute("lng");var zoomLevel=parseInt(xmlDoc.documentElement.getAttribute("zoom"));if(page.state["c_lng"]&&page.state["map_zoom"]&&this.firstLoad){this.gmap.setCenter(new GLatLng(page.state["c_lat"],page.state["c_lng"]),parseInt(page.state["map_zoom"]));}else if(this.zoom=="inclusive"){this.gmap.setCenter(new GLatLng(cLat,cLng),zoomLevel);}
if(page.state["map_type"]){if(page.state["map_type"]=="hybrid"){this.gmap.setMapType(G_HYBRID_MAP);}else if(page.state["map_type"]=="satellite"){this.gmap.setMapType(G_SATELLITE_MAP);}else{this.gmap.setMapType(G_NORMAL_MAP);}}else{this.gmap.setMapType(G_NORMAL_MAP);}
sorted=this.flags.sort();max=Math.min(125,sorted.length);for(i=0;i<max;i++){sorted[i][0]-=1;}
for(i=125;i<sorted.length;i++){this.flagIdsToFlags[sorted[i][1]].destroy();delete this.flagIdsToFlags[sorted[i][1]];}
delete this.flags;this.flags=sorted.slice(0,max);if(markers.length>0){for(i=0;i<markers.length;i++){if(!this.flagIdsToFlags[markers[i].getAttribute("flag_id")]){flag=new Flag(this,markers[i].getAttribute("flag_id"),parseFloat(markers[i].getAttribute("lng")),parseFloat(markers[i].getAttribute("lat")),markers[i].getAttribute("title"),markers[i].getAttribute("user"),markers[i].getAttribute("ownership"));if(parseFloat(markers[i].getAttribute("lng"))<this.minLng||this.minLng==null)this.minLng=parseFloat(markers[i].getAttribute("lng"));if(parseFloat(markers[i].getAttribute("lng"))>this.maxLng||this.maxLng==null)this.maxLng=parseFloat(markers[i].getAttribute("lng"));if(parseFloat(markers[i].getAttribute("lat"))<this.minLat||this.minLat==null)this.minLat=parseFloat(markers[i].getAttribute("lat"));if(parseFloat(markers[i].getAttribute("lat"))>this.maxLat||this.maxLat==null)this.maxLat=parseFloat(markers[i].getAttribute("lat"));this.flagIdsToFlags[markers[i].getAttribute("flag_id")]=flag;this.flags.push([0,markers[i].getAttribute("flag_id")])}else{this.flags.find(function(value,index){if(value[1]==markers[i].getAttribute("flag_id")){return true}else{return false}})[0]=0;}}
if(page.state["current_flag"]&&page.state["current_flag"]!==""&&this.firstLoad){if(this.flagIdsToFlags[page.state["current_flag"]]){this.flagIdsToFlags[page.state["current_flag"]].load();if(this.browser.activeFlag){this.browser.activeFlag(this.flagIdsToFlags[page.state["current_flag"]]);}}else if(this.map){flag_lat=$('flag-'+page.state["current_flag"]+'-lat').innerHTML;flag_long=$('flag-'+page.state["current_flag"]+'-long').innerHTML;if(flag_lat&&flag_long){setTimeout("zoomTo("+flag_lat+","+flag_long+")",1000);setTimeout("loadFlag('"+page.state["current_flag"]+"')",4000);}}}
if(!page.state["c_lat"]&&this.zoom=="inclusive"){var zoom,cLat,cLng;cLat=(this.minLat+this.maxLat)/2;cLng=(this.minLng+this.maxLng)/2;bounds=new GLatLngBounds(new GLatLng(this.minLat,this.minLng),new GLatLng(this.maxLat,this.maxLng));zoom=G_NORMAL_MAP.getBoundsZoomLevel(bounds,this.gmap.getSize());this.gmap.setCenter(new GLatLng(cLat,cLng),zoom);this.lastCLng=cLng;this.lastCLat=cLat;}}
bounds=this.gmap.getBounds();page.state["min_lat"]=bounds.getSouthWest().lat();page.state["max_lat"]=bounds.getNorthEast().lat();page.state["min_lng"]=bounds.getSouthWest().lng();page.state["max_lng"]=bounds.getNorthEast().lng();coordinate=this.gmap.getCenter();page.state["c_lat"]=coordinate.lat();page.state["c_lng"]=coordinate.lng();page.state["map_zoom"]=this.gmap.getZoom();this.moveListener=GEvent.addListener(this.gmap,'moveend',this.moved.bind(this));this.moveBegunListener=GEvent.addListener(this.gmap,'movestart',this.moveBegun.bind(this));this.zoomListener=GEvent.addListener(this.gmap,'zoomend',this.zoomed.bind(this));this.firstLoad=false;},zoomed:function(oldZoomLevel,newZoomLevel){if(this.dataTimeout)clearTimeout(this.dataTimeout);if(!this.addFlagMode){if(this.browser&&this.browser.klass=='Browser'){this.dataTimeout=setTimeout(function(){this.browser.search();}.bind(this),800);}else{this.dataTimeout=setTimeout(function(){map.load("","none");},800);}}
return true;},moveBegun:function(){if(this.dataTimeout)clearTimeout(this.dataTimeout);},moved:function(){bounds=this.gmap.getBounds();page.state["min_lat"]=bounds.getSouthWest().lat();page.state["max_lat"]=bounds.getNorthEast().lat();page.state["min_lng"]=bounds.getSouthWest().lng();page.state["max_lng"]=bounds.getNorthEast().lng();coordinate=this.gmap.getCenter();page.state["c_lat"]=coordinate.lat();page.state["c_lng"]=coordinate.lng();page.state["map_zoom"]=this.gmap.getZoom();if(this.lastCLat&&this.lastCLng){dx=this.lastCLat-coordinate.lat();dy=this.lastCLng-coordinate.lng();distance=Math.sqrt(Math.pow(dx,2)+Math.pow(dy,2));distance=distance/((this.gmap.getBounds().toSpan().lat())+(this.gmap.getBounds().toSpan().lng()));if(distance>0.10&&!this.addFlagMode){if(this.dataTimeout)clearTimeout(this.dataTimeout);if(this.browser&&this.browser.klass=='Browser'){this.dataTimeout=setTimeout(function(){this.browser.search();}.bind(this),800);}else{this.dataTimeout=setTimeout(function(){map.load("","none");},800);}}}
if(this.gMapDblClick&&this.browser&&this.addFlagMode){var longitude,latitude,params,login;longitude=this.gmap.getCenter().x;latitude=this.gmap.getCenter().y;login=new Cookie("login").get();url="/flags/"+login+"/geocode";params="location[longitude]="+longitude;params+="&location[latitude]="+latitude;if(page.state["limbo_id"]){params+="&limbo_id="+page.state["limbo_id"];delete page.state["limbo_id"];}
this.browser.prepareBusy();this.browser.busy();new Ajax.Updater({success:String(this.browser.div.id)},url,{method:"post",parameters:params,evalScripts:true,onComplete:this.browser.loaded.bind(this.browser)});this.gMapDblClick=false;}},resized:function(){if(this.resizeToFill){var height,topHeight;if(browserName=="Safari"){height=document.clientHeight;width=document.clientWidth;}else{height=document.documentElement.clientHeight;width=document.documentElement.clientWidth;}
topHeight=$("top").clientHeight+$("heading_bar").clientHeight;height-=topHeight+49;if($("map")){if(withAds=="true"){$("map").style.height=(height-60)+"px";}else{$("map").style.height=(height-41)+"px";}}
if(this.browser){if(Element.visible("above_browser")){$("browser").style.height=height-67+"px";}else{$("browser").style.height=height-5+"px";}}}},mapChanged:function(){if(this.gmap.getCurrentMapType()==G_HYBRID_MAP){page.state["map_type"]="hybrid";}else if(this.gmap.getCurrentMapType()==G_SATELLITE_MAP){page.state["map_type"]="satellite";}else{page.state["map_type"]="map";}},infoWindowClosed:function(){this.infoWindowOpen=false;if(currentFlag!=null)delete currentFlag;delete page.state["current_flag"];if(this.browser&&this.browser.dialogOpen)this.browser.hideDialog();},clicked:function(overlay,point){},dblClicked:function(e){if(this.addFlagMode){if($('flag_title'))this.browser.flag_title=$F('flag_title');if($('flag_description'))this.browser.flag_description=$F('flag_description');if($('flag_tag_names'))this.browser.flag_tag_names=$F('flag_tag_names');}
map.gMapDblClick=true;}}
function busy(id){if($(id)){new Effect.Appear(id,{duration:0.1});}}
function complete(id){if($(id)){new Effect.Fade(id,{duration:0.1});}}
function addTag(element){tagString=$F('flag_tag_names');tags=tagString.split(" ")
if(tags.indexOf(element.innerHTML)==-1){if(tagString[tagString.length-1]!=' '){$('flag_tag_names').value+=' '+element.innerHTML;}else{$('flag_tag_names').value+=element.innerHTML;}
element.style.color="#aaaaaa";element.style.textDecoration="none";}}

