/*

  QMaps :: Interactive Map Editing Library

  Copyright (c) 2007 Spatial North Technologies Inc.
  
  http://quikmaps.com | http://spatialnorth.com

  Released under the Creative Commons Attribution-NonCommercial-ShareAlike 2.5 licence.
  
  http://creativecommons.org/licenses/by-nc-sa/2.5/
  
  This means you can use the software in any non-commercial endeavour, provided
  you make attribution to the author / licensor.
  
  For commercial endeavours, contact info@spatialnorth.com.

  For commercial use, the following copyright notice applies:
  
  COPYRIGHT © Spatial North Technologies Inc., all rights reserved.  No part of this 
  publication may be reproduced, stored in a retrieval system, or transmitted in any form or 
  by any means, electronic, mechanical, photocopying, recording or otherwise, without the 
  prior written approval of Spatial North Technologies Inc. which also owns all proprietary 
  rights to the intellectual property set forth in this publication.  
*/


_mSvgEnabled=true;_mSvgForced=true;Q_NORMAL_MAP=G_NORMAL_MAP;Q_HYBRID_MAP=G_HYBRID_MAP;Q_SATELLITE_MAP=G_SATELLITE_MAP;Q_PHYSICAL_MAP=G_PHYSICAL_MAP;QMaps={_apiName:"google",_maptypes:[Q_HYBRID_MAP,Q_SATELLITE_MAP,Q_NORMAL_MAP,Q_PHYSICAL_MAP,G_MOON_VISIBLE_MAP,G_MOON_ELEVATION_MAP,G_MARS_VISIBLE_MAP,G_MARS_ELEVATION_MAP,G_MARS_INFRARED_MAP,G_SKY_VISIBLE_MAP],_dmaptypes:[G_NORMAL_MAP,G_SATELLITE_MAP,G_HYBRID_MAP,G_PHYSICAL_MAP,G_MOON_VISIBLE_MAP,G_MOON_ELEVATION_MAP,G_MARS_VISIBLE_MAP,G_MARS_ELEVATION_MAP,G_MARS_INFRARED_MAP,G_SKY_VISIBLE_MAP]};Q_MAP_MARKER_PANE=G_MAP_MARKER_PANE;Q_MAP_MARKER_SHADOW_PANE=G_MAP_MARKER_SHADOW_PANE;Q_MAP_FLOAT_PANE=G_MAP_FLOAT_PANE;Q_MAP_FLOAT_SHADOW_PANE=G_MAP_FLOAT_SHADOW_PANE;Q_MAP_EVENT_PANE=G_MAP_MAP_PANE;QMapTypeControl=GMapTypeControl;QSmallZoomControl=GSmallZoomControl;QSmallMapControl=GSmallMapControl;QLargeMapControl=GLargeMapControl;QScaleControl=GScaleControl;QOverviewMapControl=GOverviewMapControl;QEvent=GEvent;QBrowserIsCompatible=GBrowserIsCompatible;QUnload=GUnload;AbstractQControl=function(){this.inheritFrom=GControl;this.inheritFrom(true);}
AbstractQControl.prototype=GControl.prototype;AbstractQIcon=function(copy,image){this.inheritFrom=GIcon;this.inheritFrom(copy,image);}
AbstractQIcon.prototype=GIcon.prototype;AbstractQLatLng=function(lat,lng,unbounded){this.inheritFrom=GLatLng;this.inheritFrom(lat,lng,unbounded);}
AbstractQLatLng.prototype=GLatLng.prototype;AbstractQLatLng.prototype.latitude=function(){return parseFloat(this.lat());}
AbstractQLatLng.prototype.longitude=function(){return parseFloat(this.lng());}
AbstractQLatLngBounds=function(sw,ne){this.inheritFrom=GLatLngBounds;this.inheritFrom(sw,ne);}
AbstractQLatLngBounds.prototype=GLatLngBounds.prototype;AbstractQMap=function(container,opts){this.inheritFrom=GMap2;this.inheritFrom(container,opts);this._markers=[];this._polylines=[];}
Object.extend(AbstractQMap.prototype,GMap2.prototype);AbstractQMap.prototype.overlays=function(){return this._markers.concat(this._polylines);}
AbstractQMap.prototype.markers=function(){return this._markers;}
AbstractQMap.prototype.polylines=function(){return this._polylines;}
AbstractQMap.prototype.addOverlay=function(overlay,noAdd){if(overlay.getPoint)this._markers.push(overlay);else if(overlay.getPoints)this._polylines.push(overlay);GMap2.prototype.addOverlay.call(this,overlay);}
AbstractQMap.prototype.removeOverlay=function(overlay){if(overlay.getPoint){this._markers=this._markers.without(overlay);}else if(overlay.getPoints){this._polylines=this._polylines.without(overlay);}
GMap2.prototype.removeOverlay.call(this,overlay);}
AbstractQMap.prototype.clearOverlays=function(){this._markers=[];this._polylines=[];GMap2.prototype.clearOverlays.call(this);}
AbstractQMap.prototype.getMouseEventTarget=function(){return this.getPane(Q_MAP_EVENT_PANE).parentNode;}
AbstractQMarker=function(point,b,c){this.inheritFrom=GMarker;this.inheritFrom(point,b,c);this.imageElem=null;this.unique_id=(new Date()).getTime()+Math.round(10000*Math.random());}
AbstractQMarker.prototype=GMarker.prototype;AbstractQMarker.prototype.getUniqueId=function(){return this.unique_id;}
AbstractQMarker.prototype.setUniqueId=function(_unique_id){this.unique_id=_unique_id;}
AbstractQMarker.prototype.getImageElement=function(){if(!this.imageElem){var key=$H(this).keys().each(function(key){if((this[key]instanceof Array)&&(this[key].length>0)&&(this[key][0].filters||this[key][0].src)){this.imageElem=this[key][0];return true;}else{return false;}}.bind(this));}
return this.imageElem;}
AbstractQPoint=function(x,y){this.inheritFrom=GPoint;this.inheritFrom(x,y);}
AbstractQPoint.prototype=GPoint.prototype;AbstractQPolyline=function(points,colour,weight,opacity)
{this.inheritFrom=GPolyline;this.inheritFrom(points,colour,weight,opacity);this._colour=(colour)?colour:'#000099';this._weight=(weight)?weight:5;this._opacity=(opacity)?opacity:0.8;this.unique_id=(new Date()).getTime()+Math.round(10000*Math.random());}
AbstractQPolyline.prototype=GPolyline.prototype;AbstractQPolyline.prototype.getUniqueId=function()
{return this.unique_id;}
AbstractQPolyline.prototype.setUniqueId=function(_unique_id)
{this.unique_id=_unique_id;}
AbstractQPolyline.prototype.getColour=function()
{return this._colour;}
AbstractQPolyline.prototype.getWidth=function()
{return this._weight;}
AbstractQPolyline.prototype.getOpacity=function()
{return this._opacity;}
AbstractQPolyline.prototype.getPoints=function()
{var _points=[];for(var i=0;i<this.getVertexCount();i++)
{_points.push(this.getVertex(i));}
return _points;}
AbstractQSize=function(width,height){this.inheritFrom=GSize;this.inheritFrom(width,height);}
AbstractQSize.prototype=GSize.prototype;QConfig=function(){};var scriptLocation=function(){var SCRIPT_NAME_RE=/QMaps/i;var script=$A(document.getElementsByTagName('script')).find(function(s){return s.src.match(SCRIPT_NAME_RE);});if(script){var index=script.src.lastIndexOf("/");return(index>-1)?script.src.slice(0,index+1):"";}else{return"";}}();QConfig.baseUrl=scriptLocation;QConfig.imageLocation=QConfig.baseUrl+"assets/images/";QConfig.defaultCss=QConfig.baseUrl+"assets/css/default.css";QConfig.colourPickerCSS=QConfig.baseUrl+"assets/css/colourpicker.css";QConfig.defaultLineColour="#003399";QConfig.defaultLineWidth=5;QConfig.defaultLineOpacity=0.8;QConfig.defaultIcon='http://google.com/intl/en_ALL/mapfiles/marker.png';QConfig.logoLocation="http://quikmaps.com";QSize=function(width,height){this.inheritFrom=AbstractQSize;this.inheritFrom(width,height);}
QSize.prototype=AbstractQSize.prototype;QSize.prototype.toString=function(){return"w="+this.width+",h="+this.height;}
QPoint=function(x,y){this.inheritFrom=AbstractQPoint;this.inheritFrom(x,y);}
QPoint.prototype=AbstractQPoint.prototype;QLatLngBounds=function(sw,ne){this.inheritFrom=AbstractQLatLngBounds;this.inheritFrom(sw,ne);}
QLatLngBounds.prototype=AbstractQLatLngBounds.prototype;QLatLngBounds.prototype.toString=function(){return"southwest=("+this.getSouthWest().toShortString()+") "+"northeast=("+this.getNorthEast().toShortString()+")";}
QLatLng=function(lat,lng,unbounded){this.inheritFrom=AbstractQLatLng;this.inheritFrom(lat,lng,unbounded);}
QLatLng.prototype=AbstractQLatLng.prototype;QLatLng.prototype.toString=function(){return"("+this.latitude()+","+this.longitude()+")";},QLatLng.prototype.toShortString=function(){return this.latitude()+","+this.longitude();}
QMapData=Class.create();Object.extend(QMapData.prototype,{initialize:function()
{this.clear();},currentPath:function()
{return this.paths[this.currentid].points;},extendPath:function(point,unique_id)
{var _unique_id=unique_id||(new Date()).getTime()+Math.round(10000*Math.random());this.paths[this.currentid].points.push({point:point,id:_unique_id});this.paths[this.currentid].length=(new QPolyline(this.paths[this.currentid].points.pluck("point"))).getLength();return _unique_id;},newPath:function(mode,mycolour,mywidth,points,snap)
{var thepoints=(points)?points:[];this.paths.push({type:mode,points:thepoints,colour:mycolour,width:mywidth,length:(new QPolyline(thepoints.pluck("point"))).getLength(),snap:snap});this.currentid=this.paths.length-1;return this.paths[this.currentid];},idLoc:function(unique_id)
{var pathid=-1;var itemid=-1;this.paths.each(function(path,i)
{path.points.pluck("id").each(function(id,j)
{if(id==unique_id)
{itemid=j;pathid=i;return;}});});return[pathid,itemid];},pointLoc:function(point,map)
{var pathid=-1;var itemid=-1;var pixel_diff=5;this.paths.each(function(path,i)
{path.points.pluck("point").each(function(p,j)
{var div_point=map.fromLatLngToDivPixel(p);if((Math.abs(div_point.x-point.x)<=pixel_diff)&&(Math.abs(div_point.y-point.y)<=pixel_diff))
{itemid=j;pathid=i;return;}});});return[pathid,itemid];},removeScribblePoint:function(pathinfo)
{var path=this.paths[pathinfo[0]];if(path)
{var _ret_point=path.points[pathinfo[1]].point;this.paths=this.paths.without(path);if(pathinfo[1]!=0&&path.points.slice(0,pathinfo[1]).length>1)
this.newPath('scribble',path.colour,path.width,path.points.slice(0,pathinfo[1]));if(pathinfo[1]!=(path.points.length-1)&&path.points.slice(pathinfo[1]+1).length>1)
this.newPath('scribble',path.colour,path.width,path.points.slice(pathinfo[1]+1));this.currentid=this.paths.length-1;return _ret_point;}
else
{return null;}},removeDrawPoint:function(unique_id)
{var pathinfo=this.idLoc(unique_id);var path=this.paths[pathinfo[0]];if(path)
{var _ret_point=path.points[pathinfo[1]].point;if(path.points.length>2)
{this.paths[pathinfo[0]].points=path.points.findAll(function(p){return p.id!=unique_id;});this.currentid=pathinfo[0];path.length=(new QPolyline(this.paths[pathinfo[0]].points.pluck("point"))).getLength();}
else
{this.paths=this.paths.without(path);this.currentid=this.paths.length-1;}
return _ret_point;}
else
{return null;}},addBetween:function(point,id,prev_point,prev_id,next_point,next_id,mode,mycolour,mywidth)
{var newarray=[];var prev=false;var next=false;this.paths.each(function(path)
{if(path.points[path.points.length-1].id==prev_id)prev=path;if(path.points[0].id==next_id)next=path;});if(prev&&next)
{this.paths=this.paths.without(prev);this.paths=this.paths.without(next);prev.points.push({point:point,id:id});var newpoints=prev.points.concat(next.points);this.newPath(mode,mycolour,mywidth,newpoints,prev.snap||next.snap);this.currentid=-1;}
else if(prev&&mode==QMap.SCRIBBLE)
{this.addAfter(point,id,prev_point,prev_id,mode,mycolour,mywidth);this.addAfter(next_point,next_id,point,id,mode,mycolour,mywidth);}
else if(next&&mode==QMap.SCRIBBLE)
{this.addBefore(point,id,next_point,next_id,mode,mycolour,mywidth);this.addBefore(prev_point,prev_id,point,id,mode,mycolour,mywidth);}
else if(mode==QMap.SCRIBBLE)
{var points=[{point:prev_point,id:prev_id},{point:point,id:id},{point:next_point,id:next_id}];this.newPath(mode,mycolour,mywidth,points);}
else
{this.addBefore(point,id,next_point,next_id,mode,mycolour,mywidth);}},addBefore:function(point,id,next_point,next_id,mode,mycolour,mywidth)
{this.insert(point,id,next_point,next_id,false,mode,mycolour,mywidth);},addAfter:function(point,id,prev_point,prev_id,mode,mycolour,mywidth)
{this.insert(point,id,prev_point,prev_id,true,mode,mycolour,mywidth);},insert:function(point,id,thepoint,thepointid,after,mode,mycolour,mywidth)
{if(this.currentid==-1)
{var points=(after)?[{point:thepoint,id:thepointid},{point:point,id:id}]:[{point:point,id:id},{point:thepoint,id:thepointid}];this.newPath(mode,mycolour,mywidth,points);}
else
{var newarray=[];this.paths[this.currentid].points.each(function(p)
{if(after)newarray.push(p);if(p.id==thepointid){newarray.push({point:point,id:id});}
if(!after)newarray.push(p);});this.paths[this.currentid].points=newarray;this.paths[this.currentid].length=(new QPolyline(newarray.pluck("point"))).getLength();}},clear:function()
{this.paths=[];this.currentid=null;}});QTextMarker=function(point,label){var icon=new QIcon(QConfig.imageLocation+"markers/spacer.gif",1,1);this.inheritFrom=AbstractQMarker;this.inheritFrom(point,icon);this.pane=Q_MAP_MARKER_SHADOW_PANE;this.uniqueId=new Date().getTime();this.setLabel(label);this.type='text';}
Object.extend(QTextMarker.prototype,AbstractQMarker.prototype);Object.extend(QTextMarker.prototype,{enableEvents:function(controller){this.map=controller.map;this.setLabel(this.labelRaw);this.showLabel();try{this.labelObject.marker=this;QEvent.addDomListener(this.labelObject,"mousedown",controller.markerMouseDown.bind(controller));QEvent.addDomListener(this.labelObject,"mouseover",controller.markerMouseOver.bind(controller));if(QMaps._apiName=="google")QEvent.bind(this.map,"moveend",this,this.reposition);}catch(e){}},disableEvents:function(){},reposition:function(){if((this.labelObject)&&(this.labelObject.style.display=="block"))
this.setLabelPosition();},getLabel:function(){return(this.labelRaw)?this.labelRaw:"";},setLabel:function(label){this.labelRaw=label||'';this.labelText="<div class='markerLabel' style='cursor:pointer;'>"+this.labelRaw+"</div>";if(this.labelObject)
this.labelObject.innerHTML=this.labelText;this.deleteLabelObject();},showLabel:function(map){if(map)this.map=map;if(this.labelText){if(!this.labelObject)
this.initLabel();this.setLabelPosition();this.labelObject.style.display="block";}},deleteLabelObject:function(){if(this.labelObject){this.map.getPane(this.pane).removeChild(this.labelObject);this.labelObject=null;}},remove:function(){AbstractQMarker.prototype.remove.call(this);this.deleteLabelObject();},initLabel:function(){this.objId='lb'+this.uniqueId;var b=document.createElement('span');this.labelObject=b;b.setAttribute('id',this.objId);b.innerHTML=this.labelText;document.body.appendChild(b);b.style.position="absolute";b.style.bottom="5px";b.style.left="5px";b.style.zIndex=1;var tempObj=document.getElementById(this.objId);this.lbWidth=tempObj.offsetWidth;this.lbHeight=tempObj.offsetHeight;document.body.removeChild(b);b.style.zIndex=600000;b.style.bottom="";b.style.left="";b.style.minWidth=this.lbWidth+"px";this.map.getPane(this.pane).appendChild(b);QEvent.bind(this.map,"zoomend",this,this.reposition);},setLabelPosition:function(){var lbPos=this.map.fromLatLngToDivPixel(this.getPoint());if(this.labelObject){this.labelObject.style.left=lbPos.x+"px";this.labelObject.style.top=lbPos.y+"px";}}});QXml=function(){}
QXml.parse=function(xmlText){var xmlDoc=Try.these(function(){return new DOMParser().parseFromString(xmlText,'text/xml');},function(){var xmldom=new ActiveXObject('Microsoft.XMLDOM');xmldom.loadXML(xmlText);return xmldom;});return xmlDoc;}
QLogo=Class.create();Object.extend(QLogo.prototype,AbstractQControl.prototype);Object.extend(QLogo.prototype,{initialize:function(map){if(map){var container=document.createElement('div');container.innerHTML='<img id="qmaps_logo" style="cursor:pointer;" src="'+QConfig.imageLocation+'quikmaps2.png" border="0" title="Click to see this map at Quikmaps" />';container.style.width="106px";container.style.height="22px";GEvent.addDomListener(container,"click",function(){window.top.location=QConfig.logoLocation;}.bind(this));map.getContainer().appendChild(container);if(window.correctImgPng)correctImgPng("qmaps_logo");this.bottom=5;return container;}},getDefaultPosition:function(){return new GControlPosition(G_ANCHOR_BOTTOM_LEFT,new GSize(65,(this.bottom)?this.bottom:5));}});QPolyline=function(points,color,weight,opacity,type)
{this.inheritFrom=AbstractQPolyline;this.inheritFrom(points,color,weight,((opacity)?opacity:QConfig.defaultLineOpacity));this._type=(type)?type:QMap.DRAW;}
QPolyline.prototype=AbstractQPolyline.prototype;Object.extend(QPolyline.prototype,{getType:function()
{return this._type;},enableEvents:function(controller)
{},disableEvents:function()
{}});function QWmsMapType(__map,__wmsdata){var __newlayer=new QWmsTileLayer(__map,__wmsdata[0],__wmsdata[1],1,__wmsdata[2]);var __basemap=G_NORMAL_MAP;this.__inheritFrom=GMapType;this.__inheritFrom([__newlayer],__basemap.getProjection(),__wmsdata[4],{shortName:__wmsdata[4],tileSize:256});}
QWmsMapType.prototype=GMapType.prototype;QMapEditor=function(container,opts){this._container=container;this._opts=opts;this._initializeDom();this.initializeQMap(opts);this.initializeEvents();}
var themarkers=function(){var img=['marker_20_black.png','marker_20_purple.png','marker_34_blue.png','marker_34_red.png','warning.png','marker_20_blue.png','marker_20_red.png','marker_34_brown.png','marker_34_white.png','zleftarrow.png','marker_20_brown.png','marker_20_white.png','marker_34_green.png','marker_34_yellow.png','zrightarrow.png','marker_20_green.png','marker_20_yellow.png','marker_34_orange.png','start.png','zzbookmark.png','marker_20_orange.png','marker_34_black.png','marker_34_purple.png','startend.png'].sort();return img.collect(function(node){return QConfig.imageLocation+"markers/default/"+node;});}();QMapEditor.MARKER_LIST=themarkers;QMapEditor.prototype.initializeQMap=function(opts){if(!opts)opts={editable:true,hidetools:false};this.map=new QMap(this._mapContainer,opts);this.map.addControl(new GMapTypeControl());this.map.addControl(new GLargeMapControl());}
QMapEditor.prototype.initializeEvents=function(){document.getElementsByClassName('quikeditmode').each(function(node){node.onclick=function(){this.map.setDrawingMode(node.id);return false;}.bind(this);}.bind(this));$('geocoderok').onclick=function(){this.map.centerOnGeoText($('geocodertext').value);}.bind(this);$('geocodertext').onkeydown=function(event){if(QUtils.keycode(event)==Event.KEY_RETURN)
this.map.centerOnGeoText($('geocodertext').value);}.bind(this);GEvent.addDomListener(this.cpDom,"mousedown",function(event){this.onDocumentMouseDown(this.cpDom.id);}.bind(this));GEvent.addDomListener(document,"mousedown",function(event){this.onDocumentMouseDown('doc');}.bind(this));$('drawcol').onChangeEvent=function(){var new_col=$('drawcol').value.replace(/^([0-9a-fA-F])/,function(str,p1){return'#'+p1;});if(new_col!=this.map.getDrawingColour()){this.map.setDrawingColour(new_col);}}.bind(this);GEvent.addDomListener($('drawcol'),"change",$('drawcol').onChangeEvent);GEvent.addDomListener($('drawcol'),"keyup",$('drawcol').onChangeEvent);GEvent.addDomListener($('drawwidth'),"keyup",function(event){var new_width=Number($('drawwidth').value);if(new_width!=this.map.getDrawingWidth()){this.map.setDrawingWidth(new_width);}}.bind(this));var oldSetDrawingModeFunc=this.map.setDrawingMode;this.map.setDrawingMode=function(mode){var preveditmode=this.map.getDrawingMode();oldSetDrawingModeFunc.call(this.map,mode);this.setDrawingMode(mode,preveditmode);}.bind(this);}
QMapEditor.prototype._initializeDom=function(){var cssSheet=Builder.node('link',{rel:"stylesheet",type:"text/css",href:QConfig.defaultCss});document.getElementsByTagName("head")[0].appendChild(cssSheet);if(!this._opts.hidetools)this._toolsContainer=Builder.node('div',{className:"tools"});this._leftContainer=Builder.node('div',{className:"leftContainer"});this._aboveMapContainer=Builder.node('div',{className:"aboveMapContainer"});this._mapContainer=Builder.node('div',{className:"mapContainer"});this._leftContainer.appendChild(this._aboveMapContainer);this._leftContainer.appendChild(this._mapContainer);if(!this._opts.hidetools)this._container.appendChild(this._toolsContainer);this._container.appendChild(this._leftContainer);this._aboveMapDomElements();if(!this._opts.hidetools)this._toolsDomElements();var id=(QUtils.isIE)?"offset":"client";this._mapContainer.style.height=(this._container[id+"Height"]-this._aboveMapContainer[id+"Height"])+"px";this._mapContainer.style.width=(this._container[id+"Width"]-230)+"px";}
QMapEditor.prototype._aboveMapDomElements=function(){var modes=Builder.node('div',{className:"modes"},[Builder.node('b',{},"Edit modes:"),Builder.node('img',{alt:"",className:"quikeditmodeicon",src:QConfig.imageLocation+"selection.gif"}),Builder.node('a',{href:'#',id:"markers",className:"quikeditmode selected"},"normal"),Builder.node('img',{alt:"",className:"quikeditmodeicon",src:QConfig.imageLocation+"line_tool.gif"}),Builder.node('a',{href:'#',id:"draw",className:"quikeditmode"},"draw lines"),Builder.node('img',{alt:"",className:"quikeditmodeicon",src:QConfig.imageLocation+"pencilSmooth.gif"}),Builder.node('a',{href:'#',id:"scribble",className:"quikeditmode"},"scribble"),]);this._geocoder=Builder.node('div',{className:"geocoder"},[" Go to: ",Builder.node('input',{id:"geocodertext",name:"[]",size:18,type:"text",value:"My hometown"}),Builder.node('input',{id:"geocoderok",type:"button",value:"Go"})]);var cpDom=Builder.node('div',{className:"cpContainer",id:"colsec"});cpDom.appendChild(Builder.node('span',{},"Color "));cpDom.appendChild(Builder.node('input',{id:"drawcol",size:"7",type:"text",value:QConfig.defaultLineColour}));cpDom.appendChild(Builder.node('span',{}," "));this.cp=new QColourPicker(QConfig.defaultLineColour);this.cp.mkColor=function(newColour){$('drawcol').value="#"+newColour;$('drawcol').onChangeEvent();};var cplink=Builder.node('a',{href:"#"},"Pick");cplink.onclick=function(){this.cp.show(cplink,$('drawcol').value);return false;}.bind(this);cpDom.appendChild(cplink);cpDom.appendChild(Builder.node('span',{}," | Width "));cpDom.appendChild(Builder.node('input',{id:"drawwidth",size:"1",type:"text",value:"5"}));this.cpDiv=cpDiv=Builder.node('div',{id:"colorPickerDiv",className:"colorPickerContainer"});this.cpDiv.appendChild(this.cp._pickerContainer);cpDom.appendChild(this.cpDiv);this.cpDom=cpDom;this._aboveMapContainer.appendChild(modes);this._aboveMapContainer.appendChild(this._geocoder);this._aboveMapContainer.appendChild(cpDom);}
QMapEditor.prototype._toolsDomElements=function(){this._markerDomElements();this._toolsContainer.appendChild(Builder.node('b',{},"Other stuff"));var tabletext='<table><tr><td style="width:32%;text-align:center;">';tabletext+='<img src="'+QConfig.imageLocation+'text.gif" alt="" class="maptext" id="textlabel" />';tabletext+='<br />text label';tabletext+='</td><td style="width:32%;text-align:center;">';tabletext+='<img src="'+QConfig.imageLocation+'eraser.png" alt="" class="eraser" id="eraser" />';tabletext+='<br />erase';tabletext+='</td><td style="width:35%;text-align:center;">';tabletext+='<input type="button" value="Clear" class="clear" id="undo" />';tabletext+='<br />clear map';tabletext+='</td></tr></table>';this._toolsContainer.innerHTML+=tabletext;}
QMapEditor.prototype._markerDomElements=function(){var img=QMapEditor.MARKER_LIST;var markerText=Builder.node('b',{},"Markers");var markers=Builder.node('div',{});var table=Builder.node('table',{className:"qmapMarkerTable"});var row=null;img.each(function(node,ind){if((ind%5)==0){if(row)table.appendChild(row);row=Builder.node('tr',{});}
row.appendChild(Builder.node('td',{},[Builder.node('div',{style:"padding:4px; text-align:center;"},[Builder.node('img',{className:"mapicon",id:"img"+ind,src:node})])]));});if(row)table.appendChild(row);markers.appendChild(table);this._toolsContainer.appendChild(markerText);this._toolsContainer.appendChild(markers);}
QMapEditor.prototype.hideAboveMapTools=function(){$(this._aboveMapContainer).hide();}
QMapEditor.prototype.showAboveMapTools=function(){$(this._aboveMapContainer).show();}
QMapEditor.prototype.hideGeocoder=function(){$(this._geocoder).hide();}
QMapEditor.prototype.showGeocoder=function(){$(this._geocoder).show();}
QMapEditor.prototype.hideRHSTools=function(){$(this._toolsContainer).hide();}
QMapEditor.prototype.showRHSTools=function(){$(this._toolsContainer).show();}
QMapEditor.prototype.enableEditing=function(){this.map.enableEditing();}
QMapEditor.prototype.disableEditing=function(){this.map.disableEditing();document.getElementsByClassName('quikeditmode').each(function(node){node.onclick=function(){}});}
QMapEditor.prototype.onDocumentMouseDown=function(source){if(source==this.cpDom.id){this.incolour=true;}else if(!this.incolour){this.map.setDrawingMode(QMap.MARKERS);this.incolour=false;}else{this.incolour=false;}}
QMapEditor.prototype.setDrawingMode=function(mode,preveditmode){document.getElementsByClassName('quikeditmode').each(function(n){Element.removeClassName(n,"selected");});Element.addClassName($(mode),"selected");if(mode!=preveditmode){if(mode==QMap.SCRIBBLE){this.cpDom.style.display='block';}
else{this.cp.hide();Element.hide(this.cpDom);}
if(mode==QMap.DRAW){this.cpDom.style.display='block';}
else{if(mode!=QMap.SCRIBBLE){this.cp.hide();Element.hide(this.cpDom);}}}}
function QWmsTileLayer(__map,__baseUrl,__layerName,__opacity,__imageFormat){this.__inheritFrom=GTileLayer;this.__inheritFrom(new GCopyrightCollection(""),1,17);this.__myBaseURL=__baseUrl;this.__myLayers=__layerName;this.__myOpacity=(__opacity)?__opacity:0.69;this.__myImageFormat=(__imageFormat)?__imageFormat:"image/png";this.__map=__map;}
Object.extend(QWmsTileLayer.prototype,GTileLayer.prototype);Object.extend(QWmsTileLayer.prototype,{__MAGIC_NUMBER:6356752.3142,__DEG2RAD:0.0174532922519943,__MERC_ZOOM_DEFAULT:5,__dd2MercMetersLng:function(__p_lng){return this.__MAGIC_NUMBER*(__p_lng*this.__DEG2RAD);},__dd2MercMetersLat:function(__p_lat){if(__p_lat>=85)__p_lat=85;if(__p_lat<=-85)__p_lat=-85;return this.__MAGIC_NUMBER*Math.log(Math.tan(((__p_lat*this.__DEG2RAD)+(Math.PI/2))/2));},isPng:function(){return this.__myImageFormat.match(/png/);},getTileUrl:function(__a,__b,__c){if(this.__myMercZoomLevel==undefined){this.__myMercZoomLevel=this.__MERC_ZOOM_DEFAULT;}
if(this.__myMapname==undefined){this.__myMapname="map";}
if(typeof(window['this.__myStyles'])=="undefined")this.__myStyles="";var __lULP=new GPoint(__a.x*256,(__a.y+1)*256);var __lLRP=new GPoint((__a.x+1)*256,__a.y*256);var __lUL=G_NORMAL_MAP.getProjection().fromPixelToLatLng(__lULP,__b,__c);var __lLR=G_NORMAL_MAP.getProjection().fromPixelToLatLng(__lLRP,__b,__c);var __lwz=this.__map.getZoom();if(this.__myMercZoomLevel!=0&&__lwz<this.__myMercZoomLevel){var __lBbox=this.__dd2MercMetersLng(__lUL.x)+","+this.__dd2MercMetersLat(__lUL.y)+","+this.__dd2MercMetersLng(__lLR.x)+","+this.__dd2MercMetersLat(__lLR.y);var __lSRS="EPSG:41001";}else{var __lBbox=__lUL.x+","+__lUL.y+","+__lLR.x+","+__lLR.y;var __lSRS="EPSG:4326";}
var __lURL=this.__myBaseURL;__lURL+="&REQUEST=GetMap";__lURL+="&SERVICE=WMS";__lURL+="&VERSION=1.1.1";__lURL+="&LAYERS="+this.__myLayers;__lURL+="&STYLES="+this.__myStyles;__lURL+="&FORMAT="+this.__myImageFormat;__lURL+="&BGCOLOR=0xFFFFFF";__lURL+="&TRANSPARENT=TRUE";__lURL+="&SRS="+__lSRS;__lURL+="&BBOX="+__lBbox;__lURL+="&WIDTH=256";__lURL+="&HEIGHT=256";__lURL+="&reaspect=false";if(this.__sldUrl){if(this.__sldUrl.indexOf("%3F")<0){__lURL+="&SLD="+this.__sldUrl+"%3FzoomLevel%3D"+this.__map.getZoom();}else{__lURL+="&SLD="+this.__sldUrl+"%26zoomLevel%3D"+this.__map.getZoom();}}
return __lURL;},getOpacity:function(){return this.__myOpacity;}});QMapUndo=Class.create();Object.extend(QMapUndo.prototype,{initialize:function(drawing_controller){this._drawing_controller=drawing_controller;this.clear();},clear:function(){this.undoactions=[];this.redoactions=[];},registerAction:function(type,data){this.undoactions.push(this.buildAction(type,data));this.redoactions=[];this._drawing_controller.map.changed=true;},undo:function(){if(this.undoactions.length>0){var action=this.undoactions.pop();this.redoactions.push(action);this.applyUndoAction(action);}else{}},redo:function(){if(this.redoactions.length>0){var action=this.redoactions.pop();this.undoactions.push(action);alert('not implemented');}
else alert('no actions to redo!');},buildAction:function(type,data){return{type:type,data:data};},applyUndoAction:function(action){this._drawing_controller.setUndoing(true);if(action.type=='movemarker'){var marker=this._drawing_controller.markerForId(action.data.unique_id);if(marker)marker.setPoint(action.data.prevPoint);}else if(action.type=='addmarker'){var marker=this._drawing_controller.markerForId(action.data);if(marker)this._drawing_controller.clickDeleteMarker(marker);}else if(action.type=='deletemarker'){this._drawing_controller.dropImage(action.data);}else if(action.type=='movetextmarker'){var marker=this._drawing_controller.markerForId(action.data.unique_id);if(marker){marker.setPoint(action.data.prevPoint);marker.reposition();}}else if(action.type=='addtextmarker'){var marker=this._drawing_controller.markerForId(action.data);if(marker)this._drawing_controller.clickDeleteMarker(marker);}else if(action.type=='deletetextmarker'){this._drawing_controller.renderText(action.data,action.data.value,false);}else if(action.type=='addscribble'){var marker=this._drawing_controller.markerForId(action.data);if(marker){this._drawing_controller.setEditMode(QMap.MARKERS);this._drawing_controller.clickDeleteMarker(marker);}}else if(action.type=='deletescribble'){action.data.prevmarker=this._drawing_controller.realMarker(action.data.prevmarker);action.data.nextmarker=this._drawing_controller.realMarker(action.data.nextmarker);this._drawing_controller.dropImage(action.data,true);}else if(action.type=='movedrawline'){var marker=this._drawing_controller.markerForId(action.data.unique_id);if(marker){this._drawing_controller.clickDeleteMarker(marker);this._drawing_controller.data.currentid=action.data.currentid;action.data.prevmarker=this._drawing_controller.realMarker(action.data.prevmarker);action.data.nextmarker=this._drawing_controller.realMarker(action.data.nextmarker);this._drawing_controller.dropImage(action.data);}}else if(action.type=='adddrawline'){var marker=this._drawing_controller.markerForId(action.data);if(marker){this._drawing_controller.setEditMode(QMap.MARKERS);this._drawing_controller.clickDeleteMarker(marker);}}else if(action.type=='deletedrawline'){this._drawing_controller.data.currentid=action.data.currentid;action.data.prevmarker=this._drawing_controller.realMarker(action.data.prevmarker);action.data.nextmarker=this._drawing_controller.realMarker(action.data.nextmarker);this._drawing_controller.dropImage(action.data);}else if(action.type=='markerinfo'){var marker=this._drawing_controller.markerForId(action.data.unique_id);if(marker){marker.info=action.data.info;this._drawing_controller.markerOpenInfoWindow(marker);}}else if(action.type=='mapmove'){if(action.data.from.zoom==action.data.to.zoom)
this._drawing_controller.map.panTo(action.data.from.point);else
this._drawing_controller.map.setCenter(action.data.from.point,action.data.from.zoom);}else if(action.type=='maptypechanged'){this._drawing_controller.map.setMapType(action.data.last);}
this._drawing_controller.setUndoing(false);},applyRedoAction:function(action){}});QDataUtils={initMapPos:function(xmlDoc){var meta=xmlDoc.getElementsByTagName('meta')[0];return{y:Number(meta.getAttribute("y")),x:Number(meta.getAttribute("x")),zoom:Number(meta.getAttribute("zoom")),maptype:Number(meta.getAttribute("maptype")),canvas:meta.getAttribute("canvas")};},nodeData:function(node){if(node.getAttribute("text"))
var nodeData=node.getAttribute("text");else if(node.getAttribute("data"))
var nodeData=node.getAttribute("data");else{nodes=node.getElementsByTagName('cont');if((nodes.length>0)&&(nodes[0].firstChild))var nodeData=nodes[0].firstChild.nodeValue;}
return nodeData;},getLinePoints:function(text){var arr=text.split('),(');if((arr.length==1)&&(arr[0]==''))
return[]
else
return arr.collect(function(node){var tmp=QDataUtils.getPoints(node);return[tmp[0],tmp[1]];});},getPoints:function(text){text.match(/^\(?([^,]*),\s*([^\)]*)\)?$/);return[Number(RegExp.$1),Number(RegExp.$2)];}};QMapController=Class.create();Object.extend(QMapController.prototype,{initialize:function(map)
{this.erasing=false;this.draw_colour=QConfig.defaultLineColour;this.draw_width=QConfig.defaultLineWidth;this.editMode=QMap.MARKERS;this.snap=false;this.scribbling=false;this.open_iw_on_drop=map._opts.open_iw_on_drop||false;this.last_marker=null;this.last_polyline=null;this.polyline_index={};this.downmarker=null;this.cached_drag=null;this.cached_drop_text=null;this.dragged=0;this.data=new QMapData();this.map=map;this._undo_handler=new QMapUndo(this);this.setUndoing(false);this.setupMapStateUndo();if(this.map.editingEnabled())
{this.enableEditing();}},enableEditing:function()
{QEvent.addListener(this.map,"click",function(overlay,point)
{this.onMapClick(overlay,point);}.bind(this));QEvent.addListener(this.map,"singlerightclick",function(point,source,overlay)
{if(source.nodeName.toUpperCase()!='IMG')this.onMapRightClick(point);}.bind(this));QEvent.addDomListener(this.map.getMouseEventTarget(),"mousedown",function(event)
{this.onMouseDown(event);}.bind(this));QEvent.addDomListener(this.map.getMouseEventTarget(),"mouseup",function(event)
{this.onMouseUp(event);}.bind(this));QEvent.addDomListener(document,"mousemove",function(event)
{this.onMouseMove(event);}.bind(this));var oldcontext=document.oncontextmenu;this.map.getContainer().onmouseover=function()
{document.oncontextmenu=new Function("return false");}
this.map.getContainer().onmouseout=function()
{document.oncontextmenu=oldcontext;}
document.getElementsByClassName('clear').each(function(node)
{node.onclick=function()
{this.map.clearOverlays();}.bind(this);}.bind(this));document.getElementsByClassName('mapicon').each(function(node)
{new Draggable(node.id,{revert:true});});document.getElementsByClassName('maptext').each(function(node)
{new Draggable(node.id,{revert:true});});document.getElementsByClassName('eraser').each(function(node)
{new Draggable(node.id,{revert:true});});Droppables.add(this.map.getContainer(),{accept:['maptext','mapicon','draggablemarker','draggabletextmarker'],onDrop:this.onDrop.bind(this)});this.element=true;Draggables.addObserver(this);this.map.disableDoubleClickZoom();this.setEditMode(this.editMode,this.snap);},disableEditing:function()
{QEvent.clearInstanceListeners(this.map);QEvent.clearInstanceListeners(document);this.map.getContainer().onmouseover=function(){}
this.map.getContainer().onmouseout=function(){}
document.getElementsByClassName('clear').each(function(node)
{node.onclick=function(){}});Draggables.drags.each(function(node)
{node.destroy();});Droppables.remove(this.map.getContainer().style.id);Draggables.removeObserver(this.element);this.disableDataEvents();this.map.enableDragging();this.map.enableDoubleClickZoom();},enableDataEvents:function()
{this.map.markers().each(function(node)
{node.enableEvents(this);}.bind(this));this.map.polylines().each(function(node)
{this.map.removeOverlay(node);}.bind(this));this.data.paths.each(function(path)
{this.renderEditablePath(path);}.bind(this));},renderEditablePath:function(path)
{if(path.type==QMap.DRAW)
{var _prev_marker=null;path.points.each(function(p){var marker=new QPolyLineMarker(p.point);if(_prev_marker)
{var line=new QPolyline([_prev_marker.getPoint(),p.point],path.colour,path.width);this.map.addOverlay(line,true);_prev_marker.nextmarker=marker;_prev_marker.nextline=line;marker.prevmarker=_prev_marker;marker.prevline=line;}
_prev_marker=marker;this.map.addOverlay(marker);}.bind(this));}
else if(path.type==QMap.SCRIBBLE)
{var polyline=new QPolyline(path.points.pluck("point"),path.colour,path.width);this.map.addOverlay(polyline,true);path.points.pluck("point").each(function(p){var _index=p.lat().toFixed(6)+'-'+p.lng().toFixed(6)
this.polyline_index[_index]=this.polyline_index[_index]||[];this.polyline_index[_index].push(polyline);}.bind(this));}},disableDataEvents:function()
{this.map.markers().each(function(node)
{if((node.type=='default')||(node.type=='text'))node.disableEvents();});},onStart:function(event,draggable)
{this.map.setDrawingMode(QMap.MARKERS);if(draggable.element.className=='eraser')this.erasing=true;},onEnd:function(event,draggable)
{if(draggable.element.className=='eraser')
{this.erasing=false;}
if((this.downmarker)&&(this.dragged<=2))
{if(this.downmarker.type=='default')
{this.markerOpenInfoWindow(this.downmarker);}}
this.downmarker=null;this.dragged=0;},onDrag:function(event,draggable)
{this.dragged++;if(this.editMode==QMap.MARKERS&&draggable.element.line)
{var imageElement=draggable.element;var point=(QMaps._apiName=="google")?QUtils.centerPixelToLatLng(imageElement,this.map):QUtils.topLeftPixelToLatLng(imageElement,this.map);this.renderMarkerSideLines(imageElement.marker,point);}},undo:function()
{this._undo_handler.undo();},redo:function()
{this._undo_handler.redo();},setUndoing:function(undoing)
{this._undoing=undoing;},markerForId:function(unique_id)
{return this.map.markers().find(function(__m){return __m.getUniqueId()==unique_id;});},realMarker:function(marker)
{if(marker)
{var m=this.markerForId(marker.getUniqueId());return(m)?m:marker;}
else
{return null;}},onMapClick:function(overlay,point)
{if(this.editMode==QMap.DRAW)
{if(!point&&overlay instanceof QPolyline)
{point=overlay.getPoints().pop();}
if(point)
{this.extendDrawPolyLine(point);this.setDrawCursor();}
else if(QMaps._apiName=="openlayers")
{var event=overlay;var pointer=[Event.pointerX(event),Event.pointerY(event)];var point=QUtils.pixelToLatLng(pointer,this.map);this.extendDrawPolyLine(point);}}},onMouseMove:function(event)
{if(this.editMode==QMap.DRAW)
{this.renderPolyline(event,true);}
else if((this.editMode==QMap.SCRIBBLE)&&(this.scribbling))
{this.scribblePolyline(event);}},onMouseDown:function(event)
{if((QUtils.leftclick(event))&&(this.editMode==QMap.SCRIBBLE))
{this.scribbling=true;this.startDraw(QMap.SCRIBBLE);}},onMouseUp:function(event)
{if(this.editMode==QMap.SCRIBBLE)
{this.scribbling=false;this.endDraw();}},markerMouseDown:function(event){var marker=$(Event.element(event)).marker;if(!marker){var theanc=$(Event.element(event)).ancestors().find(function(n){return(n.marker!=undefined);});marker=theanc.marker;}
this.downmarker=marker;if(QUtils.leftclick(event)){if(!((marker.type=='poly')&&(!marker.draggable))){if($(Event.element(event)).marker){this.startDragMarker(event);}else{this.startDragTextMarker(event);}}}else if(QUtils.rightclick(event)){this.clickDeleteMarker(event);}},markerMouseOver:function(event)
{if(this.erasing)this.clickDeleteMarker(event);},onMapRightClick:function(point)
{var div_point=this.map.fromLatLngToDivPixel(this.map.fromContainerPixelToLatLng(point));var path_info=this.data.pointLoc(div_point,this.map);if(path_info[0]!=-1)
{var removed_point=this.data.removeScribblePoint(path_info);if(removed_point)
{var _index=removed_point.lat().toFixed(6)+'-'+removed_point.lng().toFixed(6);this.polyline_index[_index].each(function(p)
{this.map.removeOverlay(p);}.bind(this));this.polyline_index[_index]=null;}}},setDrawCursor:function()
{this.map.getContainer().style.cursor='url("'+QConfig.imageLocation+'pencil.cur"), pointer';this.map.getContainer().firstChild.firstChild.style.cursor='url("'+QConfig.imageLocation+'pencil.cur"), pointer';},setMarkerCursor:function()
{this.map.getContainer().firstChild.firstChild.style.cursor='url("http://www.google.com/intl/en_ALL/mapfiles/openhand.cur"), default';},setEditMode:function(mode,snap)
{if(this.map.editingEnabled()){if(mode==QMap.SCRIBBLE){if(this.map.draggingEnabled())this.map.disableDragging();this.setDrawCursor();}
else{if(!this.map.draggingEnabled())this.map.enableDragging();}
if(mode==QMap.DRAW){this.startDraw(mode,snap);this.setDrawCursor();}
else{this.endDraw();}
if(mode==QMap.MARKERS){this.setMarkerCursor();}}
this.editMode=mode;},invokeDrag:function(event,element){new Draggable(element.id,{revert:function(elem){if(!elem.dropped)this.revertMarker(elem);}.bind(this)}).initDrag(event);Draggables.updateDrag(event);},revertMarker:function(elem){elem.point=elem.prevPoint;if(elem.className=='draggabletextmarker')this.renderText(elem,true);else this.dropImage(elem);},onDrop:function(element){if(element.className=='maptext'){element.dropped=true;this.dropText(element);}
else if(element.className=='mapicon'){element.dropped=true;var marker=this.dropImage(element);if(this.open_iw_on_drop)this.markerOpenInfoWindow(marker);}
else if(element.className=='draggablemarker'){element.dropped=true;this.dropImage(element);}
else if(element.className=='draggabletextmarker'){element.dropped=true;this.renderText(element,true);}},createTextMarker:function(point,value){var marker=new QTextMarker(point,value);this.map.addOverlay(marker);return marker;},renderText:function(element,move)
{var point=element.point;if(!point)point=QUtils.topLeftPixelToLatLng(element,this.map);var value=null;if(element.marker)
{var marker=element.marker;marker.setPoint(point);element.marker.show();value=element.marker.getLabel();}
else if(element.value)
{var marker=this.createTextMarker(point,element.value);if(element.unique_id)marker.setUniqueId(element.unique_id);if(!move)element.hide();value=element.value;}
if(value)
{if(!this._undoing){if(move){if(this.dragged>1)
this._undo_handler.registerAction('movetextmarker',{unique_id:marker.getUniqueId(),prevPoint:element.prevPoint});}else{this._undo_handler.registerAction('addtextmarker',marker.getUniqueId());}}}},dropText:function(element)
{var pos=Position.cumulativeOffset(element);var divelem=this.cached_drop_text;if(!divelem)
{divelem=$(Builder.node('div',{style:'background-color:#ffffff; padding:1px; position:absolute; display:none;'}));var textelem=$(Builder.node('input',{type:'text',size:'10'}));textelem.onkeydown=function(event)
{if(QUtils.keycode(event)==Event.KEY_RETURN)
{divelem.value=$F(textelem);this.renderText(divelem,false);}}.bind(this);var linkelem=$(Builder.node('a',{href:'#'},'OK'));linkelem.onclick=function()
{divelem.value=$F(textelem);this.renderText(divelem,false);}.bind(this);divelem.appendChild(textelem);divelem.appendChild(linkelem);document.body.appendChild(divelem);divelem.textelem=textelem;}
divelem.style.left=pos[0]+'px';divelem.style.top=pos[1]+'px';divelem.show();divelem.textelem.focus();},dropImage:function(imageElement,scribble)
{var point=imageElement.point;if(!point)
{point=(QMaps._apiName=="google")?QUtils.centerPixelToLatLng(imageElement,this.map):QUtils.topLeftPixelToLatLng(imageElement,this.map);}
if(imageElement.marker)
{var marker=imageElement.marker;marker.setPoint(point);marker.show();}
else
{var thesrc=imageElement.src;if(!thesrc)
{var re=imageElement.outerHTML.match(/src='([^']*)',/);thesrc=RegExp.$1;}
var myicon=new QIcon(thesrc,imageElement.clientWidth,imageElement.clientHeight);imageElement.unique_id=imageElement.unique_id||null;var marker=(imageElement.line)?new QPolyLineMarker(point,{unique_id:imageElement.unique_id}):new QMarker(point,{icon:myicon,html:imageElement.info,unique_id:imageElement.unique_id});this.map.addOverlay(marker);}
if(imageElement.line)
{var draw_type=(scribble)?QMap.SCRIBBLE:QMap.DRAW;this.renderMarkerSideLines(marker,point,(draw_type==QMap.DRAW&&this.snap));if(marker.prevmarker&&marker.nextmarker)
{this.data.addBetween(point,marker.getUniqueId(),marker.prevmarker.getPoint(),marker.prevmarker.getUniqueId(),marker.nextmarker.getPoint(),marker.nextmarker.getUniqueId(),draw_type,marker.prevline.getColour(),marker.prevline.getWidth());if(!this.markerForId(marker.prevmarker.getUniqueId()))
{this.map.addOverlay(marker.prevmarker);marker.prevmarker.enableEvents(this);}
if(!this.markerForId(marker.nextmarker.getUniqueId()))
{this.map.addOverlay(marker.nextmarker);marker.nextmarker.enableEvents(this);}}
else if(marker.prevmarker)
{this.data.addAfter(point,marker.getUniqueId(),marker.prevmarker.getPoint(),marker.prevmarker.getUniqueId(),draw_type,marker.prevline.getColour(),marker.prevline.getWidth());if(!this.markerForId(marker.prevmarker.getUniqueId()))
{this.map.addOverlay(marker.prevmarker);marker.prevmarker.enableEvents(this);}}
else if(marker.nextmarker)
{this.data.addBefore(point,marker.getUniqueId(),marker.nextmarker.getPoint(),marker.nextmarker.getUniqueId(),draw_type,marker.nextline.getColour(),marker.nextline.getWidth());if(!this.markerForId(marker.nextmarker.getUniqueId()))
{this.map.addOverlay(marker.nextmarker);marker.nextmarker.enableEvents(this);}}}
if(imageElement.className=='draggablemarker')
{imageElement.hide();}
this.downmarker=marker;if(imageElement.unique_id)marker.setUniqueId(imageElement.unique_id);if(!this._undoing)
{if(imageElement.line&&!scribble)
{if(this.dragged>1)
{var data={point:imageElement.prevPoint,src:marker.getIcon().image,clientWidth:marker.getIcon().iconSize.width,clientHeight:marker.getIcon().iconSize.height,info:'',line:true,prevmarker:marker.prevmarker,prevline:marker.prevline,nextmarker:marker.nextmarker,nextline:marker.nextline,currentid:this.data.currentid,unique_id:marker.getUniqueId()};this._undo_handler.registerAction('movedrawline',data);}}
else if(imageElement.className=='draggablemarker')
{if(this.dragged>1)
this._undo_handler.registerAction('movemarker',{unique_id:marker.getUniqueId(),prevPoint:imageElement.prevPoint});}
else
{this._undo_handler.registerAction('addmarker',marker.getUniqueId());}}
return marker;},renderMarkerSideLines:function(marker,point,doSnap)
{if(marker.prevline)this.map.removeOverlay(marker.prevline);if(marker.nextline)this.map.removeOverlay(marker.nextline);if(marker.prevmarker&&marker.prevmarker.nextline)this.map.removeOverlay(marker.prevmarker.nextline);if(marker.nextmarker&&marker.nextmarker.prevline)this.map.removeOverlay(marker.nextmarker.prevline);if(marker.prevmarker)
{var dofunc=function(points)
{marker.prevline=new QPolyline(points,marker.prevline.getColour(),marker.prevline.getWidth());marker.prevmarker.nextmarker=marker;marker.prevmarker.nextline=marker.prevline;this.map.addOverlay(marker.prevline,true);}.bind(this);if(doSnap)
{this.loadRoadPolyline([marker.prevmarker.getPoint(),point],dofunc);}
else
{dofunc([marker.prevmarker.getPoint(),point]);}}
if(marker.nextmarker)
{marker.nextline=new QPolyline([point,marker.nextmarker.getPoint()],marker.nextline.getColour(),marker.nextline.getWidth());marker.nextmarker.prevmarker=marker;marker.nextmarker.prevline=marker.nextline;this.map.addOverlay(marker.nextline,true);}},clickDeleteMarker:function(input)
{var marker=(input.getPoint)?input:$(Event.element(input)).marker;if(!marker){var theanc=$(Event.element(input)).ancestors().find(function(n){return(n.marker!=undefined);});marker=theanc.marker;}
if(marker.type=='poly'){this.deletePolylines(marker);if((marker.prevmarker)&&(marker.nextmarker)&&(marker.draggable)){var newline=new QPolyline([marker.prevmarker.getPoint(),marker.nextmarker.getPoint()],marker.draw_colour,marker.draw_width)
this.map.addOverlay(newline,true);marker.nextmarker.prevline=newline;marker.nextmarker.prevmarker=marker.prevmarker;marker.prevmarker.nextline=newline;marker.prevmarker.nextmarker=marker.nextmarker;}else if((marker.prevmarker)&&(!marker.prevmarker.prevline)){this.map.removeOverlay(marker.prevmarker);}else if((marker.nextmarker)&&(!marker.nextmarker.nextline)){this.map.removeOverlay(marker.nextmarker);}}
this.map.removeOverlay(marker);if(!this._undoing){if(marker.type=='text'){var data={point:marker.getPoint(),value:marker.getLabel(),unique_id:marker.getUniqueId()};this._undo_handler.registerAction('deletetextmarker',data);}else if(marker.type=='default'){var data={point:marker.getPoint(),src:marker.getIcon().image,clientWidth:marker.getIcon().iconSize.width,clientHeight:marker.getIcon().iconSize.height,info:marker.info,unique_id:marker.getUniqueId()};this._undo_handler.registerAction('deletemarker',data);}else if(marker.type=='poly'&&marker.draggable){var data={point:marker.getPoint(),src:marker.getIcon().image,clientWidth:marker.getIcon().iconSize.width,clientHeight:marker.getIcon().iconSize.height,info:'',line:true,prevmarker:marker.prevmarker,prevline:marker.prevline,nextmarker:marker.nextmarker,nextline:marker.nextline,currentid:this.data.currentid,unique_id:marker.getUniqueId()};this._undo_handler.registerAction('deletedrawline',data);}else if(marker.type=='poly'&&!marker.draggable){var data={point:marker.getPoint(),src:marker.getIcon().image,clientWidth:marker.getIcon().iconSize.width,clientHeight:marker.getIcon().iconSize.height,info:'',line:true,prevmarker:marker.prevmarker,prevline:marker.prevline,nextmarker:marker.nextmarker,nextline:marker.nextline,currentid:this.data.currentid,unique_id:marker.getUniqueId()};this._undo_handler.registerAction('deletescribble',data);}}},deletePolylines:function(marker)
{if(marker.prevline)
{this.map.removeOverlay(marker.prevline);marker.prevmarker.nextmarker=null;marker.prevmarker.nextline=null;marker.draw_colour=marker.prevline.getColour();marker.draw_width=marker.prevline.getWidth();}
if(marker.nextline)
{this.map.removeOverlay(marker.nextline);marker.nextmarker.prevmarker=null;marker.nextmarker.prevline=null;marker.draw_colour=marker.nextline.getColour();marker.draw_width=marker.nextline.getWidth();}
if(marker.nextline||marker.prevline)
{this.data.removeDrawPoint(marker.getUniqueId());}},startDragTextMarker:function(event)
{var theanc=$(Event.element(event)).ancestors().find(function(n){return(n.marker!=undefined);});var marker=theanc.marker;var divElement=$(marker.labelObject);divElement.addClassName('draggabletextmarker');if(!QUtils.shiftKey(event))
{divElement.marker=marker;marker.hide();}
else
{divElement.marker=null;divElement.value=marker.getLabel();}
divElement.prevPoint=marker.getPoint();divElement.unique_id=marker.getUniqueId();this.invokeDrag(event,divElement);},startDragMarker:function(event)
{var marker=$(Event.element(event)).marker;var pos=Position.cumulativeOffset(marker.getImageElement());if((pos[0]==0)&&(pos[1]==0))
{GLog.write('pos == 0 return?');return;}
var imgelem=this.cached_drag;if(!imgelem)
{imgelem=$(Builder.node('img',{id:new Date().getTime(),className:'draggablemarker',src:'',style:'position:absolute;display:none;'}));document.body.appendChild(imgelem);this.cached_drag=imgelem;}
imgelem.style.left=pos[0]+'px';imgelem.style.top=pos[1]+'px';imgelem.src=marker.getIcon().image;if(!QUtils.shiftKey(event))
{this.deletePolylines(marker);imgelem.marker=marker;marker.hide();}
else
{imgelem.marker=null;imgelem.info=marker.info;}
if(marker.type=='poly')
{imgelem.line=true;}
imgelem.prevPoint=marker.getPoint();imgelem.unique_id=marker.getUniqueId();imgelem.show();this.invokeDrag(event,imgelem);},extendDrawPolyLine:function(point)
{this.killTempPolyline();var marker=new QPolyLineMarker(point);this.map.addOverlay(marker);var path=this.data.currentPath();if(path.length>0)
{var newline=new QPolyline([path[path.length-1].point,point],this.draw_colour,this.draw_width);this.map.addOverlay(newline,true);marker.prevline=newline;marker.prevmarker=this.last_marker;this.last_marker.nextmarker=marker;this.last_marker.nextline=newline;}
this.last_marker=marker;this.data.extendPath(point,marker.getUniqueId());var center=this.map.getCenter();var diff=new QLatLng(Math.abs(center.latitude()-point.latitude()),Math.abs(center.longitude()-point.longitude()));var span=this.map.getBounds().toSpan();var hspan=new QLatLng(span.latitude()/2,span.longitude()/2);if((diff.latitude()>(0.8*hspan.latitude()))||(diff.longitude()>(0.8*hspan.longitude())))
this.map.panTo(point);if(!this._undoing)
{if(path.length>1)
{this._undo_handler.registerAction('adddrawline',marker.getUniqueId());}}},extendScribblePolyLine:function(point)
{var path=this.data.currentPath();if(path.length>0)
{var points=[path[path.length-1].point,point];var polyline=new QPolyline(points,this.draw_colour,this.draw_width);this.map.addOverlay(polyline,true);points.each(function(p){var _index=p.lat().toFixed(6)+'-'+p.lng().toFixed(6)
this.polyline_index[_index]=this.polyline_index[_index]||[];this.polyline_index[_index].push(polyline);}.bind(this));}
var unique_id=this.data.extendPath(point,null);if(!this._undoing)
{if(path.length>1)
{this._undo_handler.registerAction('addscribble',unique_id);}}},scribblePolyline:function(event)
{if(this.renderPolyline(event,false))
{var point=QUtils.pixelToLatLng([Event.pointerX(event),Event.pointerY(event)],this.map);this.extendScribblePolyLine(point);}},renderPolyline:function(event,temp)
{var pointer=[Event.pointerX(event),Event.pointerY(event)];if(QUtils.insideElement(pointer,Position.cumulativeOffset(this.map.getContainer()),this.map.getContainer()))
{if(temp)
{var path=this.data.currentPath();if(path.length>0)
{var point=QUtils.pixelToLatLng(pointer,this.map);this.killTempPolyline();this.last_polyline=new QPolyline([path[path.length-1].point,point],this.draw_colour,this.draw_width);this.map.addOverlay(this.last_polyline,true);}}
return true;}
else
{if(temp)this.killTempPolyline();return false;}},killTempPolyline:function()
{if(this.last_polyline)
{this.map.removeOverlay(this.last_polyline);this.last_polyline=null;}},markerOpenInfoWindow:function(marker)
{var area=Builder.node('div',{},['Marker info',Builder.node('br',{}),Builder.node('textarea',{id:'ta'+marker.getUniqueId(),cols:'20',rows:'5'})]);marker.openInfoWindow(area);$('ta'+marker.getUniqueId()).value=marker.info;$('ta'+marker.getUniqueId()).onkeyup=function(){marker.info=this.value;}
window.setTimeout("$('ta"+marker.getUniqueId()+"').focus()",50);var oldinfo=marker.info||'';GEvent.addListener(marker,'infowindowclose',function(){if(marker.info!=oldinfo&&!this._undoing){var data={unique_id:marker.getUniqueId(),info:oldinfo};this._undo_handler.registerAction('markerinfo',data);}}.bind(this));},startDraw:function(mode,snap)
{this.data.newPath(mode,this.draw_colour,this.draw_width,[],this.snap);},endDraw:function()
{if(this.editMode==QMap.DRAW)
{this.killTempPolyline();}},restartDraw:function()
{this.endDraw();this.startDraw(this.editMode);},outAndBack:function()
{var path=this.data.paths[this.data.currentid];if(path)
{var pts=path.points.concat([]);pts.reverse();pts.shift();pts.each(function(p)
{this.extendDrawPolyLine(p.point);}.bind(this));}},setupMapStateUndo:function(){this.__from=null;GEvent.addListener(this.map,'movestart',function(){if(this._undoing)this.__undoingNextMove=true;else if(this.map.isLoaded()&&!this._undoing)this.__from={point:this.map.getCenter(),zoom:this.map.getZoom()};else if(!this.__from)this.__from={point:this.map.getCenter(),zoom:this.map.getZoom()};}.bind(this));GEvent.addListener(this.map,'moveend',function(){if(this.__from&&this.__from.zoom!=this.map.getZoom())return;if(!this.dragged){if(this.__undoingNextMove)this.__undoingNextMove=false;else if(this.map.isLoaded()&&this.__from&&!this._undoing){var data={from:this.__from,to:{point:this.map.getCenter(),zoom:this.map.getZoom()}};this._undo_handler.registerAction('mapmove',data);}}else{this.dragged=false;}}.bind(this));GEvent.addListener(this.map,'dragstart',function(){this.dragged=false;if(this.map.isLoaded()&&!this._undoing)this.__from={point:this.map.getCenter(),zoom:this.map.getZoom()};}.bind(this));GEvent.addListener(this.map,'dragend',function(){if(this.map.isLoaded()&&this.__from&&!this._undoing){var data={from:this.__from,to:{point:this.map.getCenter(),zoom:this.map.getZoom()}};this._undo_handler.registerAction('mapmove',data);}}.bind(this));GEvent.addListener(this.map,'drag',function(){this.dragged=true;}.bind(this));GEvent.addListener(this.map,'zoomend',function(oldLevel,newLevel){if(this.map.isLoaded()&&oldLevel&&oldLevel!=newLevel&&!this._undoing){var data={from:{point:this.map.getCenter(),zoom:oldLevel},to:{point:this.map.getCenter(),zoom:newLevel}};this._undo_handler.registerAction('mapmove',data);}}.bind(this));this.__lastMapType=null;GEvent.addListener(this.map,'maptypechanged',function(){if(this.map.isLoaded()&&!this._undoing&&this.__lastMapType){var data={last:this.__lastMapType,current:this.map.getCurrentMapType()}
this._undo_handler.registerAction('maptypechanged',data);}
if(this.map.isLoaded())this.__lastMapType=this.map.getCurrentMapType();}.bind(this));},_road_semaphore:0,loadRoadPolyline:function(waypoints,callback){var dirn=new GDirections();GEvent.addListener(dirn,"load",function(){var points=[];for(var i=0;i<dirn.getPolyline().getVertexCount();i++){points.push(dirn.getPolyline().getVertex(i));}
this._road_semaphore--;if(this._road_semaphore==0)callback(points);else callback(waypoints);}.bind(this));GEvent.addListener(dirn,"error",function(){GLog.write(dirn.getStatus());}.bind(this));this._road_semaphore++;dirn.loadFromWaypoints(waypoints,{getPolyline:true});}});function QMap(container,opts){this.inheritFrom=AbstractQMap;this.inheritFrom($(container),opts);this._opts=(opts)?opts:{};this._editable=(this._opts.editable)?this._opts.editable:false;this.geocoder=null;this._markers=[];this._polylines=[];this.enableContinuousZoom();this.enableScrollWheelZoom();this.initializeController();if(!this._opts.hidelogo&&QMaps._apiName=="google")this.addControl(new QLogo());var oldEvt=window.onunload;window.onunload=function(){if(oldEvt)oldEvt();QUnload();}
if(this._opts.topo){var wmsdata=["http://www.terraserver-usa.com/ogcmap6.ashx?","DRG","image/jpeg","TerraServer Topo","Topo"];var newmaptype=new QWmsMapType(this,wmsdata);QMaps._maptypes.push(newmaptype);this.addMapType(newmaptype);}
this.setCanvas('earth');}
QMap.SCRIBBLE='scribble';QMap.DRAW='draw';QMap.MARKERS='markers';QMap.EARTH=[G_NORMAL_MAP,G_SATELLITE_MAP,G_HYBRID_MAP,G_PHYSICAL_MAP];QMap.MOON=[G_MOON_VISIBLE_MAP,G_MOON_ELEVATION_MAP];QMap.MARS=[G_MARS_VISIBLE_MAP,G_MARS_ELEVATION_MAP,G_MARS_INFRARED_MAP];QMap.SKY=[G_SKY_VISIBLE_MAP];Object.extend(QMap.prototype,AbstractQMap.prototype);QMap.prototype._drawing_controller=null,QMap.prototype.initializeController=function(){this._drawing_controller=new QMapController(this);}
QMap.prototype.setCanvas=function(id)
{if(id=='earth')
{this.setMapTypes(QMap.EARTH);}
else if(id=='moon')
{this.setMapTypes(QMap.MOON);}
else if(id=='mars')
{this.setMapTypes(QMap.MARS);}
else if(id=='sky')
{this.setMapTypes(QMap.SKY);}
this._canvas=id;}
QMap.prototype.getCanvas=function()
{return this._canvas;}
QMap.prototype.setMapTypes=function(maptypes)
{QMaps._dmaptypes.each(function(__m){this.addMapType(__m);}.bind(this));QMaps._dmaptypes.each(function(__m)
{if(!maptypes.member(__m))this.removeMapType(__m);}.bind(this));}
QMap.prototype.addOverlay=function(overlay,noDataAdd)
{if((overlay.getPoints)&&(!noDataAdd))
{var path_points=overlay.getPoints().collect(function(p)
{return{point:p,id:(new Date()).getTime()+Math.round(10000*Math.random())};});var path=this._drawing_controller.data.newPath(overlay.getType(),overlay.getColour(),overlay.getWidth(),path_points);if(this.editingEnabled())
{this._drawing_controller.renderEditablePath(path);return;}}
AbstractQMap.prototype.addOverlay.call(this,overlay);if((overlay.getPoint)&&(overlay.type=='text'))
{overlay.showLabel(this);}
if(this.editingEnabled()&&overlay.enableEvents)
{overlay.enableEvents(this._drawing_controller);}}
QMap.prototype.clearOverlays=function(){this._drawing_controller.data.clear();AbstractQMap.prototype.clearOverlays.call(this);}
QMap.prototype.enableEditing=function(){this._editable=true;var data=this.getObject();this._drawing_controller.enableEditing();this.setObject(data);}
QMap.prototype.disableEditing=function(){this._editable=false;var data=this.getObject();this._drawing_controller.disableEditing();this.setObject(data);}
QMap.prototype.editingEnabled=function(){return this._editable;}
QMap.prototype.setDrawingMode=function(mode){this._drawing_controller.setEditMode(mode);}
QMap.prototype.getDrawingMode=function(){return this._drawing_controller.editMode;}
QMap.prototype.setDrawingColour=function(colour){this._drawing_controller.draw_colour=colour;this._drawing_controller.restartDraw();}
QMap.prototype.getDrawingColour=function(){return this._drawing_controller.draw_colour;}
QMap.prototype.setDrawingWidth=function(width){this._drawing_controller.draw_width=width;this._drawing_controller.restartDraw();}
QMap.prototype.getDrawingWidth=function(){return this._drawing_controller.draw_width;}
QMap.prototype.undo=function(){this._drawing_controller.undo();}
QMap.prototype.redo=function(){this._drawing_controller.redo();}
QMap.prototype.getDistance=function(){return(this.getObject()).meta.total_length;}
QMap.prototype.getLongestPath=function(){var res=[];var longest=0;this._drawing_controller.data.paths.each(function(path){if(path.length>longest){longest=path.length;res=path.points.collect(function(p){return[p.point.latitude().toFixed(7),p.point.longitude().toFixed(7)];});}});return res;}
QMap.prototype.centerZoomOnData=function(){var bounds=null;this.getObject().overlays.each(function(o){if(o.type=='marker'||o.type=='textmarker'){if(!bounds)bounds=new GLatLngBounds(new GLatLng(o.point[0],o.point[1]),new GLatLng(o.point[0],o.point[1]));else bounds.extend(new GLatLng(o.point[0],o.point[1]));}else{o.points.each(function(p){if(!bounds)bounds=new GLatLngBounds(new GLatLng(p[0],p[1]),new GLatLng(p[0],p[1]));else bounds.extend(new GLatLng(p[0],p[1]));});}});if(bounds)this.setCenter(bounds.getCenter(),this.getBoundsZoomLevel(bounds));}
QMap.prototype.centerOnGeoText=function(text,suppressAlert,callback){if(!this.geocoder)this.geocoder=new GClientGeocoder();this.geocoder.getLocations(text,function(response){if(!response||response.Status.code!=200){if(!suppressAlert)alert("Sorry, unable to geocode that address");if(callback)callback(false);}else{place=response.Placemark[0];point=new QLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);var zoom;if(place.AddressDetails.Accuracy==8)zoom=16;else if(place.AddressDetails.Accuracy==7)zoom=16;else if(place.AddressDetails.Accuracy==6)zoom=14;else if(place.AddressDetails.Accuracy==5)zoom=13;else if(place.AddressDetails.Accuracy==4)zoom=11;else if(place.AddressDetails.Accuracy==3)zoom=10;else if(place.AddressDetails.Accuracy==2)zoom=6;else zoom=5;this.setCenter(point,zoom);if(callback)callback(true);}}.bind(this));}
QMap.prototype.outAndBack=function(){this._drawing_controller.outAndBack();}
QMap.prototype.getJSON=function(){return QUtils.toJsonString(this.getObject());}
QMap.prototype.getXml=function(){return this.data2xml(this.getObject());}
QMap.prototype.getKml=function(){return this.data2kml(this.getObject());}
QMap.prototype.getGpx=function(){return this.data2gpx(this.getObject());}
QMap.prototype.importJSON=function(json){this.importObject(eval('('+json+')'));}
QMap.prototype.setJSON=function(json){this.setObject(eval('('+json+')'));}
QMap.prototype.importXml=function(xml){this.importObject(this.xml2object(xml));}
QMap.prototype.setXml=function(xml){this.setObject(this.xml2object(xml));}
QMap.prototype.importGpx=function(gpx){this.importObject(this.gpx2object(gpx));}
QMap.prototype.setGpx=function(gpx){this.setObject(this.gpx2object(gpx));}
QMap.prototype.importKml=function(kml){this.importObject(this.kml2object(kml));}
QMap.prototype.setKml=function(kml){this.setObject(this.kml2object(kml));}
QMap.prototype.importExt=function(str){if(str.match(/<placemark/i))
{this.importObject(this.kml2object(str));}
else if(str.match(/<trkpt|<wpt/i))
{this.importObject(this.gpx2object(str));}
else
{alert('unsupported data format!');}}
QMap.prototype.setExt=function(kml){if(str.match(/placemark/i))
{this.setObject(this.kml2object(str));}
else if(str.match(/trkpt|wpt/i))
{this.setObject(this.gpx2object(str));}
else
{alert('unsupported data format!');}}
QMap.prototype.loadXml=function(url,append,callback){var retfunc=(append)?this.importXml:this.setXml;new Ajax.Request(url,{method:'get',onComplete:function(req){if(req.responseText.match(/[^\s]/))retfunc.call(this,req.responseText);if(callback)callback((req.responseText.match(/[^\s]/))?true:false);}.bind(this)});}
QMap.prototype.loadJSON=function(url,append,callback){var retfunc=(append)?this.importJSON:this.setJSON;new Ajax.Request(url,{method:'get',onComplete:function(req){if(req.responseText.match(/[^\s]/))retfunc.call(this,req.responseText);if(callback)callback((req.responseText.match(/[^\s]/))?true:false);}.bind(this)});}
QMap.prototype.loadGpx=function(url,append,callback){var retfunc=(append)?this.importGpx:this.setGpx;new Ajax.Request(url,{method:'get',onComplete:function(req){if(req.responseText.match(/[^\s]/))retfunc.call(this,req.responseText);if(callback)callback((req.responseText.match(/[^\s]/))?true:false);}.bind(this)});}
QMap.prototype.getObject=function(){var obj={overlays:[],meta:{zoom:this.getZoom(),maptype:QUtils.maptype2num(this.getCurrentMapType()),x:this.getCenter().longitude().toFixed(7),y:this.getCenter().latitude().toFixed(7),canvas:this.getCanvas(),total_length:0}};this.markers().each(function(node){if(node.type=='text'){obj.overlays.push({type:"textmarker",point:[node.getPoint().latitude().toFixed(7),node.getPoint().longitude().toFixed(7)],data:node.getLabel()});}else if(node.type=='default'){obj.overlays.push({type:"marker",point:[node.getPoint().latitude().toFixed(7),node.getPoint().longitude().toFixed(7)],icon:node.getIcon().image,width:node.getImageElement().clientWidth,height:node.getImageElement().clientHeight,data:node.info});}});this._drawing_controller.data.paths.each(function(path){if(path.points.length>0){var dpoints=path.points.collect(function(p){return[p.point.latitude().toFixed(7),p.point.longitude().toFixed(7)];});obj.overlays.push({type:path.type,points:dpoints,colour:path.colour,width:path.width,length:path.length});}
obj.meta.total_length+=path.length;});return obj;}
QMap.prototype.data2xml=function(obj){var text='<data>';text+='<meta x="'+obj.meta.x+'" y="'+obj.meta.y+'" zoom="'+obj.meta.zoom
+'" maptype="'+obj.meta.maptype+'" total_length="'+obj.meta.total_length+'"'
+' canvas="'+obj.meta.canvas+'" />';text+='<overlays>';obj.overlays.each(function(o){text+='<o ';var data=null;for(var i in o){if(i=='data')
data=o[i];else if(i=='point')
text+=i+'="('+o[i]+')" ';else if(i=='points'){text+=i+'="';o[i].each(function(p,i){if(i!=0)text+=',';text+='('+p+')';});text+='" ';}else
text+=i+'="'+o[i]+'" ';}
if(data!=null){text+='><cont><![CDATA['+data+']]></cont></o>';}
else text+='/>';});text+='</overlays>';text+='</data>';return text;}
QMap.prototype.data2kml=function(obj){var text='<?xml version="1.0" encoding="UTF-8"?>\n';text+='<kml xmlns="http://earth.google.com/kml/2.0">\n';text+='  <Document>\n';text+='    <!-- Map data placemarks -->\n';obj.overlays.each(function(o){if(o.type=='marker'){text+='    <Placemark>\n';text+='      <description>\n';text+='        <![CDATA['+o.data+']]>\n';text+='      </description>\n';text+='      <Style>\n';text+='        <IconStyle>\n';text+='          <scale>0.75</scale>\n';text+='          <Icon>\n';text+='            <href>'+o.icon+'</href>\n';text+='          </Icon>\n';text+='        </IconStyle>\n';text+='      </Style>\n';text+='      <Point>\n';text+='        <coordinates>'+o.point[1]+','+o.point[0]+',0</coordinates>\n';text+='      </Point>\n';text+='    </Placemark>\n';}else if(o.type=='textmarker'){text+='    <Placemark>\n';text+='      <name>\n';text+='        <![CDATA['+o.data+']]>\n';text+='      </name>\n';text+='      <Style>\n';text+='        <IconStyle>\n';text+='          <Icon>\n';text+='            <href>'+QConfig.imageLocation+'markers/transparent.png</href>\n';text+='          </Icon>\n';text+='        </IconStyle>\n';text+='      </Style>\n';text+='      <Point>\n';text+='        <coordinates>'+o.point[1]+','+o.point[0]+',0</coordinates>\n';text+='      </Point>\n';text+='    </Placemark>\n';}else{text+='    <Placemark>\n';text+='      <Style>\n';text+='        <LineStyle>\n';text+='          <color>FF'+o.colour.substr(5,2)+o.colour.substr(3,2)+o.colour.substr(1,2)+'</color>\n';text+='          <width>'+o.width+'</width>\n';text+='        </LineStyle>\n';text+='      </Style>\n';text+='      <LineString>\n';text+='        <tesselate>1</tesselate>\n';text+='        <coordinates>';o.points.each(function(p,i){if(i!=0)text+='  ';text+=p[1]+','+p[0]+',0';});text+='        </coordinates>\n';text+='      </LineString>\n';text+='    </Placemark>\n';}});text+='  </Document>\n';text+='</kml>\n';return text;}
QMap.prototype.data2gpx=function(obj){var text='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';text+='<gpx xsi:schemaLocation="http://www.topografix.com/GPX/1/0';text+=' http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/Private/TopoGrafix/0/1';text+=' http://www.topografix.com/GPX/Private/TopoGrafix/0/1/topografix.xsd" creator="QMaps: http://quikmaps.com"';text+=' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" xmlns="http://www.topografix.com/GPX/1/0">\n';text+='  <name></name>\n';text+='  <desc></desc>\n';text+='  <author>QMaps</author>\n';text+='  <url>http://quikmaps.com</url>\n';text+='  <urlname>http://quikmaps.com</urlname>\n';obj.overlays.each(function(o){if(o.type=='marker'){text+='  <wpt lon="'+o.point[1]+'" lat="'+o.point[0]+'">\n';text+='    <name></name>\n';text+='    <desc>\n';text+='      <![CDATA['+o.data+']]>\n';text+='    </desc>\n';text+='    <sym>Waypoint</sym>\n';text+='    <type>\n';text+='      <![CDATA[Waypoint]]>\n';text+='    </type>\n';text+='  </wpt>\n';}else if(o.type=='textmarker'){text+='  <wpt lon="'+o.point[1]+'" lat="'+o.point[0]+'">\n';text+='    <name>\n';text+='      <![CDATA['+o.data+']]>\n';text+='    </name>\n';text+='    <desc></desc>\n';text+='  </wpt>\n';}else{text+='  <trk>\n';text+='    <name></name>\n';text+='    <desc></desc>\n';text+='    <trkseg>\n';o.points.each(function(p){text+='      <trkpt lon="'+p[1]+'" lat="'+p[0]+'" />\n';});text+='    </trkseg>\n';text+='  </trk>\n';}});text+='</gpx>\n';return text;}
QMap.prototype.gpx2object=function(gpxText){var xmlDoc=QXml.parse(gpxText);var obj={overlays:[],meta:{x:0,y:0,zoom:8,maptype:0,total_length:0}};if(xmlDoc){var trksegs=xmlDoc.documentElement.getElementsByTagName((QUtils.isIE6)?"TRKSEG":"trkseg");for(var j=0;j<trksegs.length;j++){var trkpts=trksegs[j].getElementsByTagName((QUtils.isIE6)?"TRKPT":"trkpt");var points=[];var first=true;var oldlon=0.0;var oldlat=0.0;var lat,lon;var skipped=0;for(var k=0;k<trkpts.length;k++){lat=parseFloat(trkpts[k].getAttribute("lat"));lon=parseFloat(trkpts[k].getAttribute("lon"));if(first==true){points.push([lat,lon]);first=false;}
else{if((Math.abs(lat-oldlat)>0.0005)||(Math.abs(lon-oldlon)>0.0005)||(skipped==2&&(lat!=oldlat)&&(lon!=oldlon))){points.push([lat,lon]);oldlat=lat;oldlon=lon;skipped=0;}else{skipped++;}}}
if(points.length>1)
{obj.overlays.push({type:'scribble',points:points,colour:QConfig.defaultLineColour,width:QConfig.defaultLineWidth});}}
var wpts=xmlDoc.documentElement.getElementsByTagName((QUtils.isIE6)?"WPT":"wpt");for(var i=0;i<wpts.length;i++){var text=GXml.value(wpts[i]).replace(/^\s+/,'').replace(/\s+$/,'');obj.overlays.push({type:'marker',point:[parseFloat(wpts[i].getAttribute("lat")),parseFloat(wpts[i].getAttribute("lon"))],icon:QConfig.defaultIcon,width:20,height:34,data:text});}
var bounds=null;obj.overlays.each(function(o){if(o.type=='marker'){if(!bounds)bounds=new GLatLngBounds(new GLatLng(o.point[0],o.point[1]),new GLatLng(o.point[0],o.point[1]));else bounds.extend(new GLatLng(o.point[0],o.point[1]));}else if(o.type=='scribble'){o.points.each(function(p){if(!bounds)bounds=new GLatLngBounds(new GLatLng(p[0],p[1]),new GLatLng(p[0],p[1]));else bounds.extend(new GLatLng(p[0],p[1]));});}});if(bounds){obj.meta.x=bounds.getCenter().lng().toFixed(7);obj.meta.y=bounds.getCenter().lat().toFixed(7);obj.meta.zoom=this.getBoundsZoomLevel(bounds);}}
else{alert("Parsing error.  Please upload properly formatted GPX");}
return obj;}
QMap.prototype.kml2object=function(kmlText){var xmlDoc=QXml.parse(kmlText);var obj={overlays:[],meta:{x:0,y:0,zoom:8,maptype:0,total_length:0}};if(xmlDoc){var placemarkers=$A(xmlDoc.documentElement.getElementsByTagName((QUtils.isIE6)?"PLACEMARK":"Placemark"));placemarkers.each(function(placemark){var pts=placemark.getElementsByTagName((QUtils.isIE6)?"POINT":"Point");if(pts.length>0)
{var overlay={type:'marker',point:[],icon:QConfig.defaultIcon,width:0,height:0,data:""};var desc='';var name;$A(placemark.childNodes).select(function(n){return n.nodeType!=3;}).each(function(n)
{if(n.nodeName=='name')
{name=GXml.value(n);}
else if(n.nodeName=='description')
{desc=GXml.value(n);}
else if(n.nodeName=='Point')
{var coords=GXml.value($A(n.childNodes).select(function(n){return n.nodeType!=3;})[0]);var c_array=coords.split(/,/);overlay.point[0]=Number(c_array[1]);overlay.point[1]=Number(c_array[0]);}
else if(n.nodeName=='Style')
{var href=$A(n.getElementsByTagName((QUtils.isIE6)?"HREF":"href"))[0];overlay.icon=GXml.value(href);}});if(name)
{overlay.data='<b>'+name+'</b>\n\n';}
overlay.data+=desc;obj.overlays.push(overlay);}
else
{var overlay={type:'scribble',points:[],colour:QConfig.defaultLineColour,width:QConfig.defaultLineWidth}
$A(placemark.childNodes).select(function(n){return n.nodeType!=3;}).each(function(n)
{if(n.nodeName=='LineString')
{var coords=GXml.value($A(n.getElementsByTagName((QUtils.isIE6)?"COORDINATES":"coordinates"))[0]);var p_array=coords.split(/\s+/);p_array.each(function(c)
{if(c)
{var c_array=c.split(/,/);var p=[Number(c_array[1]),Number(c_array[0])];overlay.points.push(p);}});}
else if(n.nodeName=='Style')
{var colour=$A(n.getElementsByTagName((QUtils.isIE6)?"COLOR":"color"));if(colour.length>0)
{colour=GXml.value(colour[0]);overlay.colour='#'+colour.substr(6,2)+colour.substr(4,2)+colour.substr(2,2);}
var width=$A(n.getElementsByTagName((QUtils.isIE6)?"WIDTH":"width"));if(width.length>0)
{overlay.width=Number(GXml.value(width[0]));}}});if(overlay.points.length>1)
{obj.overlays.push(overlay);}}});var bounds=null;obj.overlays.each(function(o){if(o.type=='marker'){if(!bounds)bounds=new GLatLngBounds(new GLatLng(o.point[0],o.point[1]),new GLatLng(o.point[0],o.point[1]));else bounds.extend(new GLatLng(o.point[0],o.point[1]));}else if(o.type=='scribble'){o.points.each(function(p){if(!bounds)bounds=new GLatLngBounds(new GLatLng(p[0],p[1]),new GLatLng(p[0],p[1]));else bounds.extend(new GLatLng(p[0],p[1]));});}});obj.meta.x=bounds.getCenter().lng().toFixed(7);obj.meta.y=bounds.getCenter().lat().toFixed(7);obj.meta.zoom=this.getBoundsZoomLevel(bounds);}
else{alert("Parsing error.  Please upload properly formatted KML");}
return obj;}
QMap.prototype.xml2object=function(xmlText){var xmlDoc=QXml.parse(xmlText);var obj={overlays:[],meta:QDataUtils.initMapPos(xmlDoc)};$A(xmlDoc.getElementsByTagName('o')).each(function(node){if(node.getAttribute("type")=='marker'){obj.overlays.push({type:"marker",point:QDataUtils.getPoints(node.getAttribute("point")),icon:node.getAttribute("icon"),width:Number(node.getAttribute("width")),height:Number(node.getAttribute("height")),data:QDataUtils.nodeData(node)});}else if(node.getAttribute("type")=='textmarker'){obj.overlays.push({type:"textmarker",point:QDataUtils.getPoints(node.getAttribute("point")),data:QDataUtils.nodeData(node)});}else if((node.getAttribute("type")=='scribble')||(node.getAttribute("type")=='draw')){var mycolour=((node.getAttribute("colour"))&&(node.getAttribute("colour")!='null'))?node.getAttribute("colour"):QConfig.defaultLineColour;var mywidth=((node.getAttribute("width"))&&(node.getAttribute("width")!='null'))?Number(node.getAttribute("width")):QConfig.defaultLineWidth;obj.overlays.push({type:node.getAttribute("type"),points:QDataUtils.getLinePoints(node.getAttribute("points")),colour:mycolour,width:mywidth});}}.bind(this));return obj;}
QMap.prototype.setObject=function(obj){this.clearOverlays();this.importObject(obj);this.changed=false;}
QMap.prototype.importObject=function(obj){this._drawing_controller.setUndoing(true);if(obj.meta.canvas)this.setCanvas(obj.meta.canvas);this.setCenter(new QLatLng(obj.meta.y,obj.meta.x),obj.meta.zoom,QMaps._maptypes[obj.meta.maptype]);obj.overlays.each(function(o){if(o.type=='marker'){var overlay=new QMarker(new QLatLng(o.point[0],o.point[1]),{icon:new QIcon(o.icon,o.width,o.height),html:o.data});if((o.data)&&(!this.editingEnabled())){if(overlay.info.match(/(<embed)|(<iframe)|(<img)|(<div)|(<object)/)){overlay.infoHTML='<div class="embedinfowindow">'+overlay.info+'</div>';}else{overlay.infoHTML='<div class="infowindow">'+overlay.info+'</div>';}
QEvent.addListener(overlay,"click",function(evt){this.openInfoWindowHtml(this.infoHTML);});}
this.addOverlay(overlay);}else if(o.type=='textmarker'){this.addOverlay(new QTextMarker(new QLatLng(o.point[0],o.point[1]),o.data));}else{var latlngs=o.points.collect(function(p){return new QLatLng(p[0],p[1]);});this.addOverlay(new QPolyline(latlngs,o.colour,o.width,QConfig.defaultLineOpacity,o.type));}}.bind(this));this._drawing_controller.setUndoing(false);}
var newGetProjection=function(){return G_NORMAL_MAP.getProjection();}
G_MOON_VISIBLE_MAP.getProjection=newGetProjection;G_MOON_ELEVATION_MAP.getProjection=newGetProjection;G_MARS_ELEVATION_MAP.getProjection=newGetProjection;G_MARS_INFRARED_MAP.getProjection=newGetProjection;G_MARS_VISIBLE_MAP.getProjection=newGetProjection;G_SKY_VISIBLE_MAP.getProjection=newGetProjection;G_SKY_VISIBLE_MAP.getMaximumResolution=function(){return 10;};QPolyLineMarker=function(point,opts)
{var _opts=opts||{};var icon=new QIcon();icon.url=icon.image=QConfig.imageLocation+"route_square.png";icon.shadow="";icon.shadowSize=new QSize(0,0);icon.size=icon.iconSize=new QSize(8,8);icon.iconAnchor=new QPoint(5,5);icon.infoWindowAnchor=new QPoint(4,4);this.inheritFrom=AbstractQMarker;this.inheritFrom(point,icon);if(_opts.unique_id)this.setUniqueId(_opts.unique_id);this.prevline=this.nextline=this.prevmarker=this.nextmarker=null;this.type='poly';}
Object.extend(QPolyLineMarker.prototype,AbstractQMarker.prototype);Object.extend(QPolyLineMarker.prototype,{enableEvents:function(controller)
{try
{this.getImageElement().marker=this;QEvent.addDomListener(this.getImageElement(),"mousedown",controller.markerMouseDown.bind(controller));QEvent.addDomListener(this.getImageElement(),"mouseover",controller.markerMouseOver.bind(controller));}
catch(e)
{alert(e);}}});QMarker=function(point,opts){var icon=(opts)?opts.icon:undefined;this.inheritFrom=AbstractQMarker;this.inheritFrom(point,icon);this.opts=(opts)?opts:{};if(opts.unique_id)this.setUniqueId(opts.unique_id);this.info=(this.opts.html)?this.opts.html:'';this.type='default';this.getIcon().transparent=null;this.getIcon().imageMap=null;}
Object.extend(QMarker.prototype,AbstractQMarker.prototype);Object.extend(QMarker.prototype,{enableEvents:function(controller)
{try
{this.getImageElement().marker=this;QEvent.clearInstanceListeners(this);QEvent.addDomListener(this.getImageElement(),"mousedown",controller.markerMouseDown.bind(controller));QEvent.addDomListener(this.getImageElement(),"mouseover",controller.markerMouseOver.bind(controller));}
catch(e)
{alert(e);}},disableEvents:function()
{QEvent.clearInstanceListeners(this);QEvent.clearInstanceListeners(this.getImageElement());}});QIcon=function(src,width,height){this.inheritFrom=AbstractQIcon;this.inheritFrom();if(src){this.image=src;this.url=src;if((this.image.match(/marker_20/))){this.shadow=QConfig.imageLocation+"markers/mm_20_shadow.png";this.shadowSize=new QSize(22,20);}else if((this.image.match(/marker_34/))||(this.image.match(/\/mapfiles\/marker\.png/))){this.shadow=QConfig.imageLocation+"markers/mm_34_shadow.png";this.shadowSize=new QSize(37,34);}else{this.shadow="";this.shadowSize=new QSize(0,0);}
if(width!=0||height!=0)
{this.iconSize=new QSize(width,height);this.size=this.iconSize;}
this.iconAnchor=new QPoint(width/2,height/2);this.infoWindowAnchor=new QPoint(width/2,height/2);}}
QIcon.prototype=AbstractQIcon.prototype;QUtils=function(){};QUtils.userAgent=navigator.userAgent.toLowerCase();QUtils.appVersion=navigator.appVersion.toLowerCase();QUtils.n4=(document.layers);QUtils.n6=(document.getElementById&&!document.all);QUtils.ie=(document.all);QUtils.o6=(QUtils.userAgent.indexOf("opera")!=-1);QUtils.safari=(QUtils.userAgent.indexOf("safari")!=-1);QUtils.isOpera=(QUtils.userAgent.indexOf("opera")!=-1);QUtils.isIE=(QUtils.userAgent.indexOf("msie")!=-1)&&(QUtils.userAgent.indexOf("opera")==-1);QUtils.isIE6=(QUtils.appVersion.indexOf("msie 6.")!=-1)&&(QUtils.userAgent.indexOf("opera")==-1);QUtils.isIE5=(QUtils.appVersion.indexOf("msie 5.")!=-1)&&(QUtils.userAgent.indexOf("opera")==-1);QUtils.topLeftPixelToLatLng=function(element,map){var pos=Position.cumulativeOffset(element);return QUtils.pixelToLatLng(pos,map);}
QUtils.leftPixelToLatLng=function(element,map){var pos=Position.cumulativeOffset(element);pos[1]+=(element.clientHeight/2);return QUtils.pixelToLatLng(pos,map);}
QUtils.centerPixelToLatLng=function(element,map){var pos=Position.cumulativeOffset(element);pos[0]+=(element.clientWidth/2);pos[1]+=(element.clientHeight/2)
return QUtils.pixelToLatLng(pos,map);}
QUtils.pixelToLatLng=function(pos,map){var map_pos=Position.cumulativeOffset(map.getContainer());return map.fromContainerPixelToLatLng(new QPoint((pos[0]-map_pos[0]),(pos[1]-map_pos[1])));}
QUtils.insideElement=function(pos1,pos2,elem2){return((pos2[0]<=pos1[0])&&(pos1[0]<(pos2[0]+elem2.clientWidth))&&(pos2[1]<=pos1[1])&&(pos1[1]<(pos2[1]+elem2.clientHeight)));}
QUtils.keycode=function(event){var thekeycode;if(window.event)thekeycode=window.event.keyCode;else if(event)thekeycode=event.which;return thekeycode;}
QUtils.shiftKey=function(event){return(QUtils.n4)?e.modifiers&Event.SHIFT_MASK:event.shiftKey;}
QUtils.rightclick=function(event){return((event.button!=null&&event.button==2)||(event.which!=null&&event.which==3));}
QUtils.leftclick=function(event){return((event.button!=null&&event.button==1)||(event.which!=null&&event.which==1));}
QUtils.jsdate2mysql=function(datetime){var month=datetime.getMonth()+1;var year=datetime.getYear();if(!QUtils.isIE){year=Number(year)+1900;}
return year+'-'+
month+'-'+
datetime.getDate()+' '+
datetime.getHours()+':'+
datetime.getMinutes()+':00';}
QUtils.maptype2num=function(type){return QMaps._maptypes.indexOf(type);}
QUtils.correctPNG=function(map){var arVersion=navigator.appVersion.split("MSIE")
var version=parseFloat(arVersion[1])
if((version>=5.5)&&(document.body.filters))
{for(var i=0;i<document.images.length;i++)
{var img=document.images[i];if(!img.src.match(/google\.com/)&&!img.className.match(/nopngfix/i)&&(img.parentNode!=map.getPane(Q_MAP_MARKER_PANE))&&(img.parentNode!=map.getPane(Q_MAP_MARKER_SHADOW_PANE))&&(img.parentNode!=map.getPane(Q_MAP_FLOAT_SHADOW_PANE))&&(img.parentNode!=map.getPane(Q_MAP_FLOAT_PANE))&&(img.width!=0)&&(img.height!=0)){var oldsrc=img.src;var imgName=img.src.toUpperCase()
if(imgName.substring(imgName.length-3,imgName.length)=="PNG")
{var imgID=(img.id)?"id='"+img.id+"' ":""
var imgClass=(img.className)?"class='"+img.className+"' ":""
var imgTitle=(img.title)?"title='"+img.title+"' ":"title='"+img.alt+"' "
var imgStyle="display:inline-block;"+img.style.cssText
if(img.align=="left")imgStyle="float:left;"+imgStyle
if(img.align=="right")imgStyle="float:right;"+imgStyle
if(img.parentElement.href)imgStyle="cursor:hand;"+imgStyle
var strNewHTML="<span "+imgID+imgClass+imgTitle
+" style=\""+"width:"+img.width+"px; height:"+img.height+"px;"+imgStyle+";"
+"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
+"(src=\'"+img.src+"\', sizingMethod='scale');\"></span>"
img.outerHTML=strNewHTML
i=i-1;}}}}}
QUtils.toJsonString=function(o){var UNDEFINED
switch(typeof o){case'string':return'\''+QUtils.encodeJS(o)+'\''
case'number':return String(o)
case'object':if(o){var a=[]
if(o.constructor==Array){for(var i=0;i<o.length;i++){var json=QUtils.toJsonString(o[i])
if(json!=UNDEFINED)a[a.length]=json}
return'['+a.join(',')+']'}else if(o.constructor==Date){return'new Date('+o.getTime()+')'}else{for(var p in o){var json=QUtils.toJsonString(o[p])
if(json!=UNDEFINED)a[a.length]=(/^[A-Za-z_]\w*$/.test(p)?(p+':'):('\''+QUtils.encodeJS(p)+'\':'))+json}
return'{'+a.join(',')+'}'}}
return'null'
case'boolean':return String(o)
case'function':return
case'undefined':return'null'}}
QUtils.encodeJS=function(s){return(!/[\x00-\x19\'\\]/.test(s)) ? s : s.replace(/([\\'])/g,'\\$1').replace(/\r/g,'\\r').replace(/\n/g,'\\n').replace(/\t/g,'\\t').replace(/[\x00-\x19]/g,'')}
QColourPicker=Class.create();Object.extend(QColourPicker.prototype,{initialize:function(){var cssSheet=Builder.node('link',{rel:"stylesheet",type:"text/css",href:QConfig.colourPickerCSS});document.getElementsByTagName("head")[0].appendChild(cssSheet);this._buildPickerDOM();},show:function(elem,colour){var pos=Position.cumulativeOffset(elem);this._pickerContainer.style.top=(pos[1]+elem.offsetHeight+2)+"px";this._pickerContainer.style.left=pos[0]+"px";this._pickerContainer.style.display='block';var z='';for(var i=this.SVHeight;i>=0;i--)
z+="<div style=\"BACKGROUND: #"+this.hsv2hex(Array(Math.round((359/this.SVHeight)*i),100,100))+";\"><br /><\/div>";$('Hmodel').innerHTML=z;colour=colour.replace(/^\#/,'');this.updateH(colour);this.HSVupdate(colour);},hide:function(){Element.hide(this._pickerContainer);},_buildPickerDOM:function(){var sv=Builder.node('div',{id:"SV",title:"Saturation + Value"},[Builder.node('div',{id:"SVslide"})]);var form=Builder.node('form',{id:"H",title:"Hue"},[Builder.node('div',{id:"Hslide"}),Builder.node('div',{id:"Hmodel"})]);sv.onmousedown=function(event){this.HSVslide('SVslide','plugin',event);}.bind(this);form.onmousedown=function(event){this.HSVslide('Hslide','plugin',event);}.bind(this);this._pickerContainer=Builder.node('div',{id:"plugin"},[sv,form,Builder.node('div',{id:"plugPREV"}),Builder.node('div',{id:"plugHEX"},"")]);},mkColor:function(v){},XY:function(e,v){var msie=Math.max(navigator.userAgent.toLowerCase().indexOf('msie'),0);var z=msie?Array(event.clientX+document.body.scrollLeft,event.clientY+document.body.scrollTop):Array(e.pageX,e.pageY);return(z[this.zero(v)]);},zero:function(v){v=parseInt(v);return(!isNaN(v)?v:0);},maxValue:{'h':'359','s':'100','v':'100'},HSV:{0:359,1:100,2:100},SVHeight:165,wSV:162,wH:162,slideHSV:{0:359,1:100,2:100},zINDEX:15,stop:1,HSVslide:function(d,o,e){this.tXY=function(e){tY=this.XY(e,1)-top;tX=this.XY(e)-left;}.bind(this);this.mkHSV=function(a,b,c){return(Math.min(a,Math.max(0,Math.ceil((parseInt(c)/b)*a))));}.bind(this);this.ckHSV=function(a,b){var w=((a>=0&&a<=b)?true:false);if(w)return(a);else if(a>b)return(b);else if(a<0)return('-'+oo);}.bind(this);this.drag=function(e){if(!this.stop){if(d=='SVslide'){this.tXY(e);ds.left=this.ckHSV(tX-oo,this.wSV)+'px';ds.top=this.ckHSV(tY-oo+14,this.wSV)+'px';this.slideHSV[1]=this.mkHSV(100,this.wSV,ds.left);this.slideHSV[2]=100-this.mkHSV(100,this.wSV,ds.top);this.HSVupdate();}else if(d=='Hslide'){this.tXY(e);ds.top=(this.ckHSV(tY-oo,this.wH)-5)+'px';this.slideHSV[0]=this.mkHSV(359,this.wH,ds.top);commit=function(){var r='hsv',z={},j='';for(var i=0;i<=r.length-1;i++){j=r.substr(i,1);z[i]=(j=='h')?this.maxValue[j]-this.mkHSV(this.maxValue[j],this.wH,ds.top):this.HSV[i];}
return(this.HSVupdate(this.hsv2hex(z)));}.bind(this);this.mkColor(commit());$('SV').style.backgroundColor='#'+this.hsv2hex(Array(this.HSV[0],100,100));}
else if(d=='drag'){ds.left=this.XY(e)+oX-eX+'px';ds.top=this.XY(e,1)+oY-eY+'px';}}}.bind(this);if(this.stop){this.stop='';ds=$(d!='drag'?d:o).style;if(d=='drag'){oX=parseInt(ds.left);oY=parseInt(ds.top);eX=this.XY(e);eY=this.XY(e,1);$(o).style.zIndex=this.zINDEX++;}else{left=($(o).offsetLeft+10);top=($(o).offsetTop+22);tX=null;tY=null;oo=(d=='Hslide')?2:4;if(d=='SVslide')this.slideHSV[0]=this.HSV[0];}
document.onmousemove=this.drag;document.onmouseup=function(){if(d=='SVslide')this.hide();this.stop=1;document.onmousemove='';document.onmouseup='';}.bind(this);this.drag(e);}},HSVupdate:function(v){this.HSV=v?this.hex2hsv(v):Array(this.slideHSV[0],this.slideHSV[1],this.slideHSV[2]);if(!v)v=this.hsv2hex(Array(this.slideHSV[0],this.slideHSV[1],this.slideHSV[2]));this.mkColor(v);$('plugHEX').innerHTML="#"+v;$('plugPREV').style.backgroundColor="#"+v;return(v);},updateH:function(v){this.HSV=this.hex2hsv(v);$('SV').style.backgroundColor='#'+this.hsv2hex(Array(this.HSV[0],100,100));$('SVslide').style.top=(parseInt(this.wSV-this.wSV*(this.HSV[2]/100))-4)+'px';$('SVslide').style.left=parseInt(this.wSV*(this.HSV[1]/100))+'px';$('Hslide').style.top=(parseInt(this.wH*((this.maxValue['h']-this.HSV[0])/this.maxValue['h']))-7)+'px';},toHex:function(v){v=Math.round(Math.min(Math.max(0,v),255));return("0123456789ABCDEF".charAt((v-v%16)/16)+"0123456789ABCDEF".charAt(v%16));},hex2rgb:function(r){return({0:parseInt(r.substr(0,2),16),1:parseInt(r.substr(2,2),16),2:parseInt(r.substr(4,2),16)});},rgb2hex:function(r){return(this.toHex(r[0])+this.toHex(r[1])+this.toHex(r[2]));},hsv2hex:function(h){return(this.rgb2hex(this.hsv2rgb(h)));},hex2hsv:function(v){return(this.rgb2hsv(this.hex2rgb(v)));},rgb2hsv:function(r){var max=Math.max(r[0],r[1],r[2]),delta=max-Math.min(r[0],r[1],r[2]),H,S,V;if(max!=0){S=Math.round(delta/max*100);if(r[0]==max)H=(r[1]-r[2])/delta;else if(r[1]==max)H=2+(r[2]-r[0])/delta;else if(r[2]==max)H=4+(r[0]-r[1])/delta;var H=Math.min(Math.round(H*60),360);if(H<0)H+=360;}
return({0:H?H:0,1:S?S:0,2:Math.round((max/255)*100)});},hsv2rgb:function(r){var R,B,G,S=r[1]/100,V=r[2]/100,H=r[0]/360;if(S>0){if(H>=1)H=0;H=6*H;F=H-Math.floor(H);A=Math.round(255*V*(1.0-S));B=Math.round(255*V*(1.0-(S*F)));C=Math.round(255*V*(1.0-(S*(1.0-F))));V=Math.round(255*V);switch(Math.floor(H)){case 0:R=V;G=C;B=A;break;case 1:R=B;G=V;B=A;break;case 2:R=A;G=V;B=C;break;case 3:R=A;G=B;B=V;break;case 4:R=C;G=A;B=V;break;case 5:R=V;G=A;B=B;break;}
return({0:R?R:0,1:G?G:0,2:B?B:0});}
else return({0:(V=Math.round(V*255)),1:V,2:V});}});