var _RM_IMG_PATH_="../../img/site/RouteManager/";var _BB_IMG_PATH_=_RM_IMG_PATH_;var _MAXPOINTS=7;var _DEBUG=true;function RouteManager(uid){this.userId=uid;this.width=585;this.height=375;this.element=DIV();this.miniPoints=[];this.pointBoxes=[];this.mapCanvas=DIV();this.resize();}
RouteManager.prototype=update(new Notifier(),{useClientLocation:false,map:false,avoidHighways:false,firstPointBox:false,lastPointBox:false,mouseLatLng:false,polylines:false,helper:false,boxList:false,buttonBar:false,geocoder:false,origin:false,gDir2:false,clientLocation:false,initialized:false,render:function(parentElement,init){if(typeof(init)=="undefined")
init=true;parentElement.appendChild(this.element);var self=this;this.pointList=DIV();this.polylines=[];this.pointList.className="PointList";this.mapCanvas.className="routeManagerMapCanvas";this.createButtonBar();this.element.appendChild(this.buttonBar.element);this.element.appendChild(this.mapCanvas);this.element.appendChild(this.pointList);if(init)
this.init();this.resetFirstLastBoxes();this.refreshPointList();this.resize();},init:function(){if(this.initialized)
return;this.initialized=true;this.geocoder=new GClientGeocoder();this.origin=new GLatLng(-33.46,-70.64);this.gDir2=new GDirections();this.clientLocation=google.loader.ClientLocation;this.renderGMap();this.loadHelper();this.helper.openInfoWindow();if(this.boxList)
this.clear();this.resetFirstLastBoxes();this.refreshPointList();this.resize();},createButtonBar:function(){var self=this;this.buttonBar=new ButtonBar();this.buttonBar.addButton(new BarButton("toolbar/new.png",function(){MiniPoint.prototype._firstCreated=true;self.clear();},"Nuevo Mapa."));this.buttonBar.addButton(new BarButton("toolbar/helper.png",function(){if(self.helper.isVisible)
self.helper.hide();else
self.helper.show();},function(){return(self.helper.isVisible?"Ocultar":"Mostrar")+" el asistente.";}));this.buttonBar.addButton(new BarButton("toolbar/zoom.png",function(){self.setBestZoom();},"Restablecer Zoom."));this.buttonBar.addButton(new BarButton("toolbar/delete.png",function(){var point=self.selectedPoint;if(point)
point.destroy();},function(){var point=self.selectedPoint;if(point&&point.isValid){return"Eliminar el punto: <br><br><strong>"+point.input.value+"</strong>.";}
if(point)
return"Eliminar el punto.";return"Eliminar punto (debes seleccionarlo primero).";}));this.buttonBar.addButton(new BarButton("toolbar/accept.png",function(){if(_DEBUG){var data=self.getRouteData();var rs=self.resetPoints(data.waypoints,data.length,30);self.drawPoly(rs);for(var i in rs){if(rs[i].user)
self.map.addOverlay(new GMarker(rs[i]));}}
self.notifyAll("accept");},"Aceptar"));this.buttonBar.createElement();},renderGMap:function(){var self=this;this.map=new GMap2(this.mapCanvas);if(this.clientLocation&&this.useClientLocation)
this.origin=new GLatLng(this.clientLocation.latitude,this.clientLocation.longitude);this.resetMapView();var customUI=this.map.getDefaultUI();customUI.controls.largemapcontrol3d=false;customUI.controls.maptypecontrol=false;customUI.controls.smallzoomcontrol3d=true;customUI.zoom.scrollwhell=true;customUI.zoom.doubleclick=true;this.map.setUI(customUI);GEvent.addListener(this.map,"click",function(a,b,c){self.mapClick(a,b,c);});GEvent.addListener(this.map,"dragend",function(a,b,c){self.mapDragEnd(a,b,c);});GEvent.addListener(this.map,"mousemove",function(ll){self.mouseMove(ll);});},loadHelper:function(){this.helper=new Helper(this,this.origin);this.addListener(this.helper);var self=this;GEvent.addListener(this.map,"dragstart",function(){self.helper.mapDragStart();});GEvent.addListener(this.map,"dragend",function(){self.helper.mapDragEnd();});GEvent.addListener(this.map,"drag",function(){self.helper.mapDrag();});GEvent.addListener(this.map,"zoomend",function(){self.onZoomEnd();});GEvent.addListener(this.map,"moveend",function(){self.helper.refreshPosition();});},onZoomEnd:function(){this.helper.refreshPosition();this.boxList.callFunction("updateMiniPointVisibility");},refreshPointList:function(){var pb=this.boxList;while(this.pointList.childNodes.length>0)
this.pointList.removeChild(this.pointList.firstChild);while(pb){this.pointList.appendChild(pb.element);if(pb.next){var self=this;var button=new BarButton("addMiddlePoint.png",function(b){self.addMiddlePointAfter(b.point,false,true);},"Agregar punto intermedio.",15);button.point=pb;this.pointList.appendChild(button.element);this.pointList.appendChild(button.hint);button.element.style.position="absolute";var pos=findPos(pb.element);button.element.style.left=pos[0]+this.width/2-55+"px";var t=pos[1]+(pb.middlePoint?15:32);if(!pb.middlePoint&&pb.next.middlePoint)
t-=2;if(pb.middlePoint&&!pb.next.middlePoint)
t+=4;button.element.style.top=t+"px";button.hintOffsetTop=27;button.hintOffsetLeft=40;button.loadHint();}
pb=pb.next;}},resetFirstLastBoxes:function(){while(this.getPointBoxesCount()<2){this.appendPointBox(new PointBox("",this));}
this.firstPointBox=this.getFirstPointBox();this.lastPointBox=this.getLastPointBox();this.firstPointBox.name="Desde:";this.firstPointBox.middlePoint=false;this.firstPointBox.refreshElement();this.lastPointBox.name="Hasta:";this.lastPointBox.middlePoint=false;this.lastPointBox.refreshElement();var self=this;this.lastPointBox.addListener(this.helper);this.firstPointBox.addListener(this.helper);this.helper.fromBox=this.firstPointBox;this.helper.toBox=this.lastPointBox;},removePointBox:function(box){if(box==this.selectedPoint){this.selectedPoint=false;if(box.next)
this.selectPoint(box.next,false);else if(box.prev)
this.selectPoint(box.prev,false);}
box.remove();this.resetFirstLastBoxes();this.refreshPointList();},getPointBoxesCount:function(){var i=0;var pb=this.boxList;while(pb){pb=pb.next;i++;}
return i;},appendPointBox:function(b){if(this.boxList){this.boxList.appendPointBox(b);}else{this.boxList=b;b.prev=false;}},getFirstPointBox:function(){return this.boxList;},getLastPointBox:function(){var pb=this.boxList;while(pb){if(!pb.next)
break;pb=pb.next;}
return pb;},addMiddlePointAfter:function(prevBox,ll,force){if(typeof force=="undefined")
force=false;var self=this;var box;if(prevBox.next&&!prevBox.next.isValid&&!force)
box=prevBox.next;else{box=new PointBox("Por:",this,true);prevBox.insertAfter(box);}
this.selectPoint(box);this.refreshPointList();if(ll)
this.geocoder.getLocations(ll,function(r){self.reverseGLHandler(r);});},mapClick:function(overlay,latlng,overlaylatlng){if(overlay===null){this.notifyAll("mapClicked");if(this.selectedPoint){this.selectedPoint.input.focus();if(!this.selectedPoint.isValid)
this.selectLatLng(latlng);}}},selectLatLng:function(latlng){var self=this;this.geocoder.getLocations(latlng,function(r){self.reverseGLHandler(r);});},mapDragEnd:function(){if(this.selectedPoint)
this.selectedPoint.input.focus();},reverseGLHandler:function(response){if(typeof(response)=="undefined"||response.Status.code!=200){log("Could not reverse geolocate, response: "+response);log("Could not reverse geolocate, error code: "+response.Status.code);}else{var place=response.Placemark[0];var latlng=new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);this.setLocation(latlng,place.address);}},setLocation:function(latlng,addr){var s=0;this.selectedPoint.setIsValid(true);this.selectedPoint.setLocation(latlng,addr);},closeInfoWindow:function(){this.map.closeInfoWindow();},getPolylineMiddlePoint:function(pl){var n=pl.getVertexCount();var length=pl.getLength();var d=0;var i=0;var j=1;while(j<=n){inc=pl.getVertex(i++).distanceFrom(pl.getVertex(j++));if(d+inc>=length/2)
break;d+=inc;}
var c=(length/2-d)/pl.getVertex(--i).distanceFrom(pl.getVertex(--j));return this.getConvexCombination(pl.getVertex(j),pl.getVertex(i),c);},getConvexCombination:function(ll1,ll2,c){var proj=this.map.getCurrentMapType().getProjection();ll1=proj.fromLatLngToPixel(ll1,this.map.getZoom());ll2=proj.fromLatLngToPixel(ll2,this.map.getZoom());var ll3=new GPoint(ll1.x*c+ll2.x*(1-c),ll1.y*c+ll2.y*(1-c));ll3=proj.fromPixelToLatLng(ll3,this.map.getZoom());return ll3;},getSquaredPixelDistance:function(ll1,ll2){var proj=this.map.getCurrentMapType().getProjection();ll1=proj.fromLatLngToPixel(ll1,this.map.getZoom());ll2=proj.fromLatLngToPixel(ll2,this.map.getZoom());return Math.pow(ll1.x-ll2.x,2)+Math.pow(ll1.y-ll2.y,2);},setBestZoom:function(){if(!this.boxList.validPoly)
return 13;var bounds=new GLatLngBounds();var bs=this.boxList;while(bs){if(bs.isValid)
bounds.extend(bs.marker.getLatLng());bs=bs.next;}
this.map.setZoom(this.map.getBoundsZoomLevel(bounds));this.map.setCenter(bounds.getCenter());},resetMapView:function(){this.map.setCenter(this.origin,13);},mouseMove:function(ll){this.mouseLatLng=ll;},selectPoint:function(p,center){this.closeInfoWindow();if(typeof(center)=="undefined")
center=true;if(this.selectedPoint){this.selectedPoint.setSelected(false);}
this.selectedPoint=p;p.setSelected(true);if(p.isValid&&center){this.centerPoint(p);this.notifyAll("mapMoved");}},centerPoint:function(p){this.map.setCenter(p.marker.getLatLng());},resize:function(w){if(typeof(w)!="undefined")
this.width=w;this.mapCanvas.style.width=this.width+"px";this.mapCanvas.style.height=this.height+"px";if(this.boxList)
this.boxList.callFunction("resize");if(this.buttonBar){this.buttonBar.resize(this.width+2);this.buttonBar.loadHints();}
if(this.pointList)
this.pointList.style.width=this.width+"px";},autoResize:function(){var divMRoute=this.mapCanvas;var clientH=document.documentElement.clientHeight;var clientW=document.documentElement.clientWidth;alert("Implement me. RouterManager::autoResize()");},getRouteData:function(){var out={"waypoints":[],"length":0};var f=function(self,arg){var arr=arg.waypoints;if(!self.validPoly){log("got an invalid poly :"+self);if(self.isValid)
arr.push(self.marker.getLatLng());return;}
var polyCount=self.poly.getVertexCount();for(var i=0;i<polyCount;i++){var p2=self.poly.getVertex(i);if(i<polyCount-1||!self.next)
arr.push(p2);p2.user=(i===0||!self.next);}
arg.length+=self.poly.getLength();};this.boxList.callFunction(f,false,out);out.waypoints[out.waypoints.length-1].user=true;return out;},clear:function(){this.boxList.callFunction("destroy",true);},resetPoints:function(stepPoint,dr,mp){var Ps=0;var Ms=0;var nr=stepPoint.length;var maxdistance=(dr/mp);var Ds=0;var jump=Math.round(nr/mp);jump=jump===0?1:jump;var jumpPoint=[];var i,j;for(i=0,j=0;j<stepPoint.length;j+=1){if(j%jump==0||stepPoint[j].user){var jS=stepPoint[j];if(typeof(jS)=='object'){jumpPoint.push(jS);}
if(stepPoint[j].user)
if(j%jump==0)
Ds=i++;}}
var Ns=0;googleStep=[];newstepPoint=[];for(r=0;r<jumpPoint.length;r++){var tS=jumpPoint[r];var sS=jumpPoint[(r+1)];newstepPoint[Ns]=tS;googleStep[Ns]='google';if((r+1)!=jumpPoint.length&&!sS.user){var nextSP=sS;var dPoints=distancePoints(tS,nextSP).toFixed(4);if(dPoints>maxdistance){var hmPoints=Math.round(dPoints/maxdistance);var dp=(dPoints/hmPoints).toFixed(4);if(isNaN(dp)){dp=1;}
var grd=anguloPoints(tS,nextSP);var last_point=tS;if(dp>maxdistance){var hmP=hmPoints;hmP+=Math.round(dp/maxdistance);dp=(dp*hmPoints)/hmP;hmPoints=hmP;}
for(rm=0;rm<hmPoints;rm++){var middlepoint=pointToDistance(dp,last_point,grd);var distMpoint=Math.round(distancePoints(middlepoint,nextSP));Ns++;newstepPoint[Ns]=middlepoint;googleStep[Ns]='line';last_point=middlepoint;}}}
Ns++;}
return newstepPoint;},drawPoly:function(wp){var pl=new GPolyline(wp,"#ff0000",4);this.map.addOverlay(pl);},getJSON:function(){var routeData=this.getRouteData();var resetPoints=this.resetPoints(routeData.waypoints,routeData.length,20);var data={};data.Trip={start_lat:this.firstPointBox.marker.getLatLng().lat(),start_lng:this.firstPointBox.marker.getLatLng().lng(),end_lat:this.lastPointBox.marker.getLatLng().lat(),end_lng:this.lastPointBox.marker.getLatLng().lng(),start_address:this.firstPointBox.input.value,end_address:this.lastPointBox.input.value,distance:routeData.length,create:1,user_id:this.userId};data.Route=[];for(var i in resetPoints){data.Route[i]={lat:resetPoints[i].lat(),lng:resetPoints[i].lng(),position:i,type:resetPoints[i].user?"user":"search"};}
return toJSON(data);},createMenuInfoWindow:function(div,text,icons){div.style.width="250px";div.innerHTML=text;div.appendChild(HR());for(var i in icons){var p2=P();p2.appendChild(IMG({className:"inlineImage clickable",src:icons[i].img_path,onclick:icons[i].action,width:20,height:20}));p2.appendChild(createTextNode(" : "+icons[i].text));div.appendChild(p2);}
return div;}});function Point(manager,latlng,iconURL){if(typeof(manager)!="undefined")
this._init(self,manager,latlng,iconURL);}
Point.prototype=update(new Notifier(),{blueIconURL:_RM_IMG_PATH_+"/map_icon_square.png",redIconURL:_RM_IMG_PATH_+"/map_icon_square_red.PNG",redIconSelectedURL:_RM_IMG_PATH_+"/map_icon_square_red_selected.PNG",helperIconURL:_RM_IMG_PATH_+"/adedo_helper.gif",redMarkerIconURL:_RM_IMG_PATH_+"/redMarker.png",redDotMarkerIconURL:_RM_IMG_PATH_+"/redDotMarker.png",marker:false,isVisible:false,dragging:false,alive:true,infoContents:null,_init:function(self,manager,latlng,icon){self.listeners=[];self.manager=manager;var marker=new GMarker(latlng,{icon:icon,draggable:true});self.setMarker(marker);self.infoContents=DIV();self.infoContents.className="infoWindow";self.createInfoWindow();},setMarker:function(marker){var self=this;if(this.marker&&this.isVisible)
this.manager.map.removeOverlay(this.marker);this.marker=marker;GEvent.addListener(self.marker,"mouseover",function(){self.mouseover();});GEvent.addListener(self.marker,"mouseout",function(){self.mouseout();});GEvent.addListener(self.marker,"dragstart",function(){self.dragstart();});GEvent.addListener(self.marker,"dragend",function(){self.dragend();});GEvent.addListener(self.marker,"drag",function(){self.drag();});GEvent.addListener(self.marker,"click",function(){self.click(null,self);});GEvent.addListener(self.marker,"infowindowopen",function(){self.infoWindowIsOpen=true;});GEvent.addListener(self.marker,"infowindowclose",function(){self.infoWindowIsOpen=false;});if(this.isVisible)
this.manager.map.addOverlay(this.marker);},mouseover:function(){},mouseout:function(){},dragstart:function(){},drag:function(){},dragend:function(){},show:function(){if(!this.isVisible)
this.manager.map.addOverlay(this.marker);this.isVisible=true;},hide:function(){if(this.isVisible)
this.manager.map.removeOverlay(this.marker);this.isVisible=false;},getMarkerIcon:function(type,color,selected){if(typeof(color)=="undefined")
color="Red";if(typeof(selected)=="undefined")
selected=false;var icon=new GIcon();if(type=="google"){icon.iconSize=new GSize(32,32);icon.infoWindowAnchor=new GPoint(16,0);icon.iconAnchor=new GPoint(16,32);}else if(type=="square"){icon.iconSize=new GSize(10,10);icon.iconAnchor=new GPoint(5,5);icon.infoWindowAnchor=new GPoint(5,0);}
icon.image=this.getMarkerImage(type,color,selected);return icon;},getMarkerImage:function(type,color,selected){var out=_RM_IMG_PATH_+"/"+type+color+(selected?"Selected":"")+"Marker.png";log(out);return out;},openInfoWindow:function(){if(!this.infoWindowisOpen&&this.alive&&this.isVisible)
this.marker.openInfoWindow(this.infoContents);},closeInfoWindow:function(){this.marker.closeInfoWindow();},toggleInfoWindow:function(){if(this.infoWindowIsOpen)
this.closeInfoWindow();else
this.openInfoWindow();},destroy:function(){this.hide();this.alive=false;},createInfoWindow:function(){return null;},click:function(n,e){if(e==this)
this.toggleInfoWindow();},displayOneTimeMessage:function(msg){var self=this;while(this.infoContents.childNodes.length>0)
this.infoContents.removeChild(this.infoContents.firstChild);if(typeof(msg)!="undefined"){this.infoContents.innerHTML=msg;}
this.iwList=GEvent.addListener(this.manager.map,"infowindowclose",function(){self.restoreInfoWindowContents();GEvent.removeListener(self.iwList);});this.openInfoWindow();},restoreInfoWindowContents:function(){this.createInfoWindow();if(this.infoWindowIsOpen){this.closeInfoWindow();this.openInfoWindow();}}});function PointBox(name,manager,middlePoint){if(typeof(name)!="undefined")
this._init(this,name,manager,middlePoint);}
PointBox.prototype=update(new Point(),{isValid:false,allowMinipoints:true,selected:false,writting:false,validPoly:false,polyType:null,poly:false,mp:false,useArrows:false,_init:function(self,name,manager,middlePoint){if(typeof(middlePoint)=="undefined")
middlePoint=false;self.middlePoint=middlePoint;self.name=name;if(manager.initialized){self.gDir=new GDirections();GEvent.addListener(this.gDir,"load",function(){self.drawDirectionsRoute();});GEvent.addListener(this.gDir,"error",function(){self.directionsLoadError(self.gDir.getStatus());});Point.prototype._init(self,manager,new GLatLng(0,0),this.getMarkerIcon("google","Red"));}else{this.manager=manager;this.middlePoint=middlePoint;}
self.createElement();},createElement:function(){var self=this;this.element=DIV();this.label=LABEL();this.input=INPUT();this.input.onkeyup=function(){self.onkeyup();};this.input.onfocus=function(){this.focused=true;if(!self.selected){self.manager.selectPoint(self,true);}};this.input.onblur=function(){this.focused=false;};this.name=this.name;this.element.appendChild(this.label);this.element.appendChild(this.input);this.element.onclick=function(){self.onclick();};this.refreshElement();this.lastParsedAddress=this.input.value;},createInfoWindow:function(){var div=this.infoContents;var self=this;this.manager.createMenuInfoWindow(div,"<p>Arrastrame para cambiar la posicion de este punto.</p>",[{"img_path":_RM_IMG_PATH_+"/20x20/eliminar.png","action":function(){self.destroy();},"text":"Eliminar este punto."}]);return div;},directionsLoadError:function(st){log("directionsLoadError, code: "+st.code);this.notifyAll("directionsLoadError",st);if(st.code==604)
this.drawStraightRoute();},drawDirectionsRoute:function(){this.validPoly=true;this.updatePolyline(this.gDir.getPolyline());this.polyType="google";},drawStraightRoute:function(){if(this.isValid&&this.next&&this.next.isValid){this.validPoly=true;this.updatePolyline(new GPolyline([this.marker.getLatLng(),this.next.marker.getLatLng()]));this.polyType="line";}else{log(this+" : could not draw straight polyline");}},addArrows:function(poly){var points=[];for(var i=0;i<poly.getVertexCount();i++){points.push(poly.getVertex(i));}
var arrowedPoly=new BDCCArrowedPolyline(points,"#0000FF",3,0.7,null,40,8,"#FF0000",2,0.7);return arrowedPoly;},updatePolyline:function(pl,updateMp){if(typeof(updateMp)=="undefined")
updateMp=true;this.erasePolyline();if(this.useArrows)
pl=this.addArrows(pl);this.poly=pl;if(this.validPoly&&typeof(pl)=="object"){if(this.useArrows){this.poly.initialize(this.manager.map);}else{this.manager.map.addOverlay(this.poly);}}
if(updateMp)
this.updateMiniPoint();},erasePolyline:function(){if(this.validPoly&&this.poly){if(this.useArrows)
this.poly.remove();else
this.manager.map.removeOverlay(this.poly);}},updateMiniPointVisibility:function(){if(this.mp){var d=this.manager.getSquaredPixelDistance(this.marker.getLatLng(),this.mp.marker.getLatLng());var d1=this.manager.getSquaredPixelDistance(this.mp.marker.getLatLng(),this.next.marker.getLatLng());if(Math.min(d,d1)<500)
this.mp.hide();else
this.mp.show();}},updateMiniPoint:function(){if(this.next){if(this.mp)
this.mp.destroy();this.mp=new MiniPoint(this);if(this.mp.firstCreated){this.mp.openInfoWindow();this.manager.setBestZoom();}}
this.updateMiniPointVisibility();},refreshElement:function(){this.resize();this.label.innerHTML=this.name;this.refreshClassName();},refreshClassName:function(){this.element.className="pointBox";if(this.middlePoint){this.element.className+=" middlePoint";}
if(this.selected){this.element.className+=" selectedPoint";}},destroy:function(){this.manager.removePointBox(this);},onkeyup:function(e){var self=this;this.w=true;if(this.lastParsedAddress==this.input.value)
return;this.lastParsedAddress=this.input.value;if(!this.writting){this.writting=true;jQuery.whileAsync({delay:1000,bulk:0,test:function(){return self.w},loop:function(){self.w=false;},end:function(){self.writting=false;self.parseAddress();}});}},parseAddress:function(){if(this.input.value==""){this.setIsValid(false);return;}
var self=this;this.manager.closeInfoWindow();this.manager.geocoder.getLocations(this.input.value+", Chile",function(ll){self.GLHandler(ll);});},confirmAddressMessage:function(places){this.infoContents.innerHTML="<H3>"+places[0].address+"</H3><p>Si esta no es la ubicacion que buscabas, se mas preciso, incluye el nombre de la comuna y ciudad.</p>";},GLHandler:function(response){var self=this;if(typeof(response)=="undefined"||response.Status.code!=200){this.setIsValid(false);this.manager.resetMapView();this.notifyAll("enteredInvalidAdress");}else{var places=[];for(var i in response.Placemark){var place=response.Placemark[i];places[i]={'place':place,'latlng':new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]),'address':place.address};}
var cfunc=function(p1,p2,desc){var d1=p1["latlng"].distanceFrom(self.manager.origin);var d2=p2["latlng"].distanceFrom(self.manager.origin);return desc?d1<d2:d2<d1;}
quicksort(places,0,places.length-1,true,cfunc);this.marker.setLatLng(places[0]["latlng"]);this.setIsValid(true);if(this.prev)
this.prev.updateRoute();this.updateRoute();this.manager.centerPoint(this);this.displayOneTimeMessage();this.confirmAddressMessage(places);this.manager.setBestZoom();this.notifyAll("enteredValidAddress",this);this.notifyAll("changeLocation","address");}},setIsValid:function(v){if(v){if(!this.isValid)
this.show();this.isValid=v;this.refreshImage();}else{this.erasePolyline();this.hide();this.isValid=v;if(this.mp){this.mp.destroy();this.mp=false;}
if(this.prev)
this.prev.updateRoute();}},resize:function(){this.element.style.width=(this.manager.width-20)+"px";this.input.style.width=(this.manager.width-110)+"px";},toString:function(){return"PointBox("+this.name+") : "+this.input.value;},click:function(){if(!this.selected)
this.manager.selectPoint(this,false);this.toggleInfoWindow();this.notifyAll("click");},dragstart:function(){this.notifyAll("dragstart");this.manager.selectPoint(this,false);this.manager.closeInfoWindow();this.dragging=true;var self=this;jQuery.whileAsync({delay:1000,bulk:0,test:function(){return self.dragging;},loop:function(){self.manager.selectLatLng(self.marker.getLatLng());},end:function(){}});},drag:function(){},dragend:function(){this.dragging=false;this.manager.selectLatLng(this.marker.getLatLng());this.notifyAll("dragend");},setLocation:function(latlng,addr){this.lastParsedAddress=addr;if(!this.dragging)
this.marker.setLatLng(latlng);this.input.value=addr;this.notifyAll("changeLocation","click");if(this.prev)
this.prev.updateRoute();this.updateRoute();},onclick:function(){if(this.selected)
return;this.manager.selectPoint(this);this.notifyAll("click");},setSelected:function(b){this.selected=b;if(!this.input.focused&&b)
this.input.focus();this.refreshClassName();this.refreshImage();if(b)
this.notifyAll("select");},refreshImage:function(){if(this.isValid){if(this.selected){this.marker.setImage(this.getMarkerImage("google","Red",true));}else{this.marker.setImage(this.getMarkerImage("google","Red",false));}}},getNextValidPoint:function(){var next=this;while(next=next.next){if(next.isValid)
return next;}
return false;},updateRoute:function(){var next=this.getNextValidPoint();if(!this.isValid&&this.prev){this.prev.updateRoute();return;}
if(this.isValid&&next){var waypoints=[this.marker.getLatLng(),next.marker.getLatLng()];this.gDir.loadFromWaypoints(waypoints,{preserveViewport:false,avoidHighways:this.avoidHighWays,getSteps:false,getPolyline:true});}else{this.erasePolyline();if(this.mp){this.mp.destroy();this.mp=false;}}},callFunction:function(fnName,inv,args){if(typeof inv=="undefined")
inv=false;if(this.next&&inv)
this.next.callFunction(fnName,inv,args);if(typeof fnName=="function"){fnName(this,args);}if(typeof this[fnName]=="function")
this[fnName](args);if(this.next&&!inv)
this.next.callFunction(fnName,inv,args);},remove:function(b){if(typeof(b)=="undefined")
b=this;if(b!=this&&this.next)
return this.next.remove(b);else if(b==this){this.erasePolyline();if(this.next)
this.next.prev=this.prev;if(this.prev){this.prev.next=this.next;this.prev.updateRoute();}else{this.manager.boxList=this.next;}
this.next=false;this.prev=false;this.hide();if(this.mp)
this.mp.destroy();return this;}
return false;},appendPointBox:function(b){if(this.next)
this.next.appendPointBox(b);else
this.insertAfter(b);},insertAfter:function(b){if(this.next){this.next.prev=b;b.next=this.next;}
this.next=b;b.prev=this;}});function Helper(manager,latlng){if(typeof(manager)!="undefined")
this._init(this,manager,latlng);}
Helper.prototype=update(new Point(),{boxSelected:false,firstTimeBoxIsSelected:true,fromBoxIsSelected:false,toBoxIsSelected:false,firstPointPlaced:false,routeIsTraced:false,dragging:false,toString:function(){return"RouteManager.Helper";},_init:function(self,manager,latlng){var icon=new GIcon();iconSize=new GSize(75,51);icon.infoWindowAnchor=new GPoint(50,0);icon.iconAnchor=new GPoint(37,51);icon.image=Point.prototype.helperIconURL;Point.prototype._init(self,manager,latlng,icon);this.marker.disableDragging();this.refreshInfoContents();this.refreshPosition();this.show();},dragstart:function(n,e){this.dragging=true;this.infoWindowWasOpen=this.infoWindowIsOpen;this.closeInfoWindow();},drag:function(n,e){},dragend:function(n,e){this.dragging=false;if(this.infoWindowWasOpen)
this.openInfoWindow();},mapDragStart:function(){this.dragstart();},mapDrag:function(){this.drag();this.refreshPosition();},mapDragEnd:function(){this.mapMoved();this.dragend();},mapMoved:function(){this.refreshPosition();},refreshPosition:function(){var map=this.manager.map;var proj=map.getCurrentMapType().getProjection();var p=proj.fromLatLngToPixel(map.getCenter(),map.getZoom());p.y+=Math.floor(this.manager.height/2)-42;p.x-=Math.floor(this.manager.width/2)-110;var newLatLng=proj.fromPixelToLatLng(p,this.manager.map.getZoom());if(this.marker.getLatLng().distanceFrom(newLatLng)<1)
return;this.marker.setLatLng(newLatLng);if(this.infoWindowIsOpen){p.y-=110;newLatLng=proj.fromPixelToLatLng(p,this.manager.map.getZoom());this.closeInfoWindow();this.openInfoWindow();}},refreshInfoContents:function(){if(this.infoWindowIsOpen){this.closeInfoWindow();this.openInfoWindow();}
switch(true){case!this.boxSelected:var self=this;this.manager.createMenuInfoWindow(this.infoContents,"<p><strong>Hola</strong>, selecciona un campo de abajo para indicar tu punto de origen (<strong>Desde</strong>) o destino (<strong>Hasta</strong>).</p>",[{"img_path":_RM_IMG_PATH_+"20x20/helper.png","action":function(){self.destroy();},"text":"Ocultar el asistente."}]);this.firstTime=false;return;case!this.firstPointPlaced:log("No point has been placed.");var t1="<p>";if(this.firstTimeBoxIsSelected){t1+="Bien, ahora h";this.firstTimeBoxIsSelected=false;}else{t1+="H";}
t1+="az <strong>click</strong> en el mapa para establecer el punto de<strong>";if(this.fromBoxIsSelected)
t1+=" origen";else
t1+=" destino";t1+="</strong>.</p><p>Tambi&eacute;n puedes escribir la direcci&oacute;n en el cuadro de texto.</p>";this.infoContents.innerHTML=t1;return;case!this.routeIsTraced&&!this.fromBox.isValid:log("missing from address")
this.infoContents.innerHTML="<p>Ahora tienes que establecer tu punto de origen, hazlo tal como lo hiciste con el punto de destino.</p><p>Recuerda seleccionar abajo el campo \"<strong>Desde</strong>\" primero.</p>";return;case!this.routeIsTraced&&!this.toBox.isValid:log("missing to address")
this.infoContents.innerHTML="<p>Ahora tienes que establecer tu punto de destino, hazlo tal como lo hiciste con el punto de origen.</p><p>Recuerda seleccionar el abajo campo \"<strong>Hasta</strong>\" primero.</p>";return;default:log("default");this.closeInfoWindow();this.infoContents.innerHTML="Nada que decir...";return;}},refresh:function(){this.refreshPosition();this.refreshInfoContents();},openInfoWindow:function(){if(this.alive&&this.isVisible)
this.marker.openInfoWindow(this.infoContents);},createInfoWindow:function(){this.infoContents.style.width="240px";},select:function(n,e){if(e==this){this.toggleInfoWindow();return;}
this.boxSelected=true;this.fromBoxIsSelected=e==this.fromBox;this.toBoxIsSelected=e==this.fromBox;if(!this.toBox.isValid&&!this.fromBox.isValid)
this.openInfoWindow();if(e==this.fromBox&&this.toBox.isValid){this.closeInfoWindow();}else if(e==this.toBox&&this.fromBox.isValid){this.closeInfoWindow();}
this.refresh();},changeLocation:function(n,e){this.firstPointPlaced=true;this.refresh();if(this.fromBox.isValid&&this.toBox.isValid)
this.closeInfoWindow();else if(n!="address"&&!this.dragging){this.openInfoWindow();}},enteredInvalidAdress:function(){this.displayOneTimeMessage("Lo siento, pero no pudimos encontrar la ubicaci&oacute;n ingresada. Intenta haciendo click en el mapa.");},directionsLoadError:function(){this.refresh();},directionsLoaded:function(){this.routeIsTraced=true;this.refresh();},mapClicked:function(){}});function MiniPoint(box){if(typeof(box)!="undefined")
this._init(this,box);}
MiniPoint.prototype=update(new Point(),{_firstCreated:true,geoLocatedLatLng:false,mouseIsOver:false,_init:function(self,box){var manager=box.manager;var latlng=manager.getPolylineMiddlePoint(box.poly);self.box=box;self.lastTime=new Date();Point.prototype._init(self,box.manager,latlng,this.getMarkerIcon("google","Blue"));self.firstCreated=self._firstCreated;MiniPoint.prototype._firstCreated=false;this.show();},createInfoWindow:function(){var div=this.infoContents;var self=this;this.manager.createMenuInfoWindow(div,"<p>Arrastrame para ajustar la ruta y <strong>aproximarla</strong> a tu trayecto.</p>",[{"img_path":_RM_IMG_PATH_+"20x20/accept.png","action":function(){self.manager.notifyAll("accept");},"text":"Aceptar la ruta sugerida."}]);return div;},directionsLoaded:function(){this.box.updatePolyline(this.manager.gDir2.getPolyline(),false);this.geoLocatedLatLng=false;},directionsLoadError:function(st){this.notifyAll("directionsLoadError",st);if(st.code==604){this.drawStraightRoute();}},drawStraightRoute:function(){var pl=new GPolyline(this.getWayPoints());this.box.updatePolyline(pl,false);this.geoLocatedLatLng=false;},mouseover:function(){},mouseout:function(){},dragstart:function(){var self=this;this.notifyAll("dragstart");this.dragging=true;this.manager.closeInfoWindow();this.marker.closeInfoWindow();this.list1=GEvent.addListener(this.manager.gDir2,"load",function(){self.directionsLoaded();});this.list2=GEvent.addListener(this.manager.gDir2,"error",function(){self.directionsLoadError(self.manager.gDir2.getStatus());});jQuery.whileAsync({delay:1000,bulk:0,test:function(){return self.dragging;},loop:function(){self.manager.geocoder.getLocations(self.marker.getLatLng(),function(r){self.reverseGLHandler(r);});},end:function(){}});},dragend:function(){this.dragging=false;GEvent.removeListener(this.list1);GEvent.removeListener(this.list2);this.manager.addMiddlePointAfter(this.box,this.marker.getLatLng());this.notifyAll("dragend");},drag:function(){},getWayPoints:function(){var points=new Array();points.push(this.box.marker.getLatLng());points.push(this.geoLocatedLatLng?this.geoLocatedLatLng:this.marker.getLatLng());points.push(this.box.next.marker.getLatLng());return points;},drawRoute:function(latlng){this.geoLocatedLatLng=latlng;var points=this.getWayPoints();this.manager.gDir2.loadFromWaypoints(points,{preserveViewport:true,avoidHighways:this.manager.avoidHighWays,getSteps:false,getPolyline:true});},reverseGLHandler:function(response){if(typeof(response)=="undefined"||response.Status.code!=200){}else{var place=response.Placemark[0];var latlng=new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);this.drawRoute(latlng);}}});function ButtonBar(){this.buttons=[];this.width=false;}
ButtonBar.prototype=update(new Notifier(),{createElement:function(){this.element=DIV();this.element.className="buttonbar";var span=SPAN();span.className="buttonPanel";this.element.appendChild(span);for(var i in this.buttons){span.appendChild(this.buttons[i].element);span.appendChild(this.buttons[i].hint);}
return this.element;},addButton:function(b){this.buttons.push(b);return b;},resize:function(w){this.width=w;this.element.style.width=w+"px";},loadHints:function(){for(var i in this.buttons){this.buttons[i].loadHint();}}});function BarButton(imgURL,action,description,height){if(typeof(height)=="undefined")
height=40;var self=this;this.hint=SPAN({"className":"v-hint"});var hintPointer=SPAN({"className":"hintPointer"});this.hintText=P({"className":"hintText"})
this.hint.appendChild(hintPointer);this.hint.appendChild(this.hintText);this.action=action;this.description=function(){return"";};this.baseClassName="inlineImage barbutton clickable"
if(typeof description=="string")
this.description=function(){return description;};else if(typeof description=="function")
this.description=description;this.hintOffsetTop=45;this.hintOffsetLeft=3;this.element=IMG({className:"inlineImage clickable barbutton",src:_BB_IMG_PATH_+"/"+imgURL,onclick:function(){self.action(self)},onmouseover:function(){self.hintText.innerHTML=self.description();self.hint.style.display="block";self.element.className="inlineImage clickable barbutton hover";},onmouseout:function(){self.hint.style.display="none";log(self.hint.style.display);self.element.className="inlineImage clickable barbutton";},onload:function(){self.loadHint();},height:height});}
BarButton.prototype=update(new Notifier(),{loadHint:function(){var pos=findPos(this.element);this.hint.style.top=pos[1]+this.hintOffsetTop+"px";this.hint.style.left=pos[0]+this.hintOffsetLeft+"px";}});
