// stagetrack.js
// ******************************************************
//
//   StageTrack JS Library
//   written by Digital Propulsion Labs
//   Copyright 2009-2012 Digital Propulsion Labs *unless otherwise specified*
//	 version 0.5.5 - 2012-02-17
//
// ******************************************************
// Input 0 
stagetrack.mode={REALTIME:0,REPLAY:1,START:2,PAUSE:3,RESTART:4,EDIT:5};stagetrack.interfaces={MAP:0,EARTH:1};stagetrack.earthRadius={MILES:3963.19246,FEET:2.09256561888E7,METERS:6371009};stagetrack.options={entrants:{ALL:!0,TRACKED:!1}};stagetrack.userOptions={MILES:3963.19246,FEET:2.09256561888E7,METERS:6371009};stagetrack.icon={marker:{START:"/images/markers/rally/sm/start.png",FINISH:"/images/markers/rally/sm/finish.png",SPLIT:"/images/markers/routesplit.png"}};stagetrack.dataSource="/bin/stmapdata.php"; onReady=function(a){if("object"==typeof a.onReady)a.onReady()}; function stagetrack(a,b,d){this.apiKey="TOBECOMPLETED";this._reqUrl=b||null;this.races=new races(b,!0,this);this.raceid=d||0;this.poimarkers=this.standings=this.cars=this.race=null;this.eventmarkers=[];this.language="en";this.gmHndl=a||null;this.gmMode=stagetrack.mode.REALTIME;this.gmDirSvc=new google.maps.DirectionsService;this.gmDirDisp=new google.maps.DirectionsRenderer({map:this.gmHndl,suppressInfoWindows:!0,suppressMarkers:!0});this.gmKMLParser=this.gmHndl?new geoXML3.parser({map:this.gmHndl}): null;this.geMode=this.geHndl=null;this.highlightColors={"#CC0000":null,"#00CC00":null,"#0000CC":null,"#C0C0C0":null};stagetrack.icons={markers:{START:"/images/markers/rally/sm/start.png",FINISH:"/images/markers/rally/sm/finish.png",SPLIT:new google.maps.MarkerImage({url:"/images/markers/routesplit.png",anchor:new google.maps.Point(10,10)})}};this.replayStateChanged=this.modeChanged=this.onLoad=null;this.debug=this.adminInit=this.standingsInit=!1;this.self=this;this.loadstatus_=0;this.useroptions= {raceControls:1,specFeed:0,autoPan:1,showAllEntrants:stagetrack.options.entrants.TRACKED,routeHighlight:0,routeSnap:!1,routeMarkers:!0,stageOverlay:1,stageMarkers:!0,stagesHighlightAll:!1,updateEvents:5,replaySpeed:1,replaySnapCar:!1,smoothReplay:!0,smoothDetail:2,eventMarkersClustered:!0,offsetOverlappingMarkers:!0,jumpToRecentEvents:!0};this.replayoptions_={stage:0,stageid__:0,speed:1,smooth:!1,time:0,isready:!1,data:{}};this.controls={progress:new progressBar,stage:this.selectStageControl(),playback:this.playbackControls(), status:this.playbackProgressControl()};this.useroptions.eventMarkersClustered&&(this.eventmarkers=new MarkerClusterer(this.gmHndl,[],{gridSize:50,maxZoom:15}));this.onReady=function(a){a&&(this.onLoad=a);if(null!=this.race&&(this.race.race_theme&&$(document).find("head #app-theme").attr("href","/styles/custom/"+this.race.race_theme+"/app.css"),this.cars=this.race.cars,this.gmHndl&&(this.controls.mode=this.selectModeControl(),this.gmHndl.controls[google.maps.ControlPosition.TOP_RIGHT].push(this.controls.mode), this.gmHndl.controls[google.maps.ControlPosition.RIGHT].push(this.controls.progress.getDiv()),this.gmHndl.controls[google.maps.ControlPosition.TOP_RIGHT].push(this.controls.playback),this.gmHndl.controls[google.maps.ControlPosition.TOP_RIGHT].push(this.controls.stage),this.gmHndl.controls[google.maps.ControlPosition.BOTTOM].push(this.controls.status.div()),this.loadStageMarkers(),this.loadStaticMarkers(),this.setMode(stagetrack.mode.REALTIME)),a=new Date-0,this.race&&a>=this.race.dates.start&&a<= this.race.dates.end&&!this.race.inactive?this.setMode(stagetrack.mode.REALTIME):this.setMode(stagetrack.mode.REPLAY),this.onLoad))this.onLoad()}}stagetrack.prototype.isReady=function(a){var b=this;if(a)return setTimeout(function(){if(2<=b.loadstatus_)b.onReady();else b.loadstatus_=b.isReady(!0)},150),this.loadstatus_;0<this.raceid&&!a&&(this.race=this.races.fetch(this.raceid,!0,function(){b.loadstatus_++}),this.isReady(!0))};stagetrack.prototype.mapDiv=function(){return this.gmHndl}; stagetrack.prototype.setRace=function(a){this.race=this.races.fetch(a)};stagetrack.prototype.getRace=function(){return this.race};stagetrack.prototype.setMap=function(a){this.gmHndl=a;this.onReady()};stagetrack.prototype.getMap=function(){return this.gmHndl}; stagetrack.prototype.setMode=function(a){if(this.gmMode==a)return!1;var b=$(this.gmHndl.getDiv());b.data("old-zindex")&&(b.css("z-index",b.data("old-zindex")),b.data("old-zindex",""));if(a==stagetrack.mode.REALTIME){b=new Date-0;if(b<=this.race.dates.start&&b<=this.race.dates.end||this.race.inactive){alert("No Live data is available before the Race begins.");return}if(b>=this.race.dates.end){alert("No Live data is available once the Race ends.");return}this.unloadReplayData();this.enableLiveData(!0); this.toggleMapMenu(this.controls.playback,"hide");this.toggleMapMenu(this.controls.status.div(),"hide");$("#gen_map_control").html("Live")}else a==stagetrack.mode.EDIT?(this.enableLiveData(!1),$(this.controls.playback).hide(),$(this.controls.status.div()).hide(),$(this.controls.stage).show(),stagetrack.showBlanket(),b.data("old-zindex",b.css("z-index")),b.topZIndex({increment:5}),$("#gen_map_control").html("Edit")):a>=stagetrack.mode.REPLAY&&(a==stagetrack.mode.REPLAY&&(this.enableLiveData(!1),this.controls.stage= this.selectStageControl(),this.toggleMapMenu(this.controls.playback,"show"),this.toggleMapMenu(this.controls.stage,"show"),this.toggleMapMenu(this.controls.status.div(),"show")),$("#gen_map_control").html("Replay"));this._lastMode=this.gmMode;this.gmMode=a;this.modeChanged&&this.gmMode<stagetrack.mode.EDIT&&this.modeChanged(this.gmMode,this._lastMode);return!0};stagetrack.prototype.revertMode=function(){return this.setMode(this._lastMode)};stagetrack.prototype.getMode=function(){return this.gmMode}; stagetrack.prototype.isMode=function(a){return this.gmMode==a};stagetrack.prototype.enableLiveData=function(a){var b=this.cars.fetch();for(i=0;i<b.length;i++)if(b[i].marker&&b[i].marker.setVisible(a),b[i].lines)for(var d in b[i].lines)b[i].lines[d].setMap(a?this.gmHndl:null);return!0}; stagetrack.prototype.selectModeControl=function(){var a=this;map=this.gmHndl;var b=new Date-0,d={};null!=this.race?(this.race.settings.replay&&(d.Replay=function(){a.setMode(stagetrack.mode.REPLAY);$("#gen_map_control_menu").toggleClass("show_menu")}),this.race.settings.realtime&&b>=this.race.dates.start&&b<=this.race.dates.end&&(d.Live=function(){a.setMode(stagetrack.mode.REALTIME);$("#gen_map_control_menu").toggleClass("show_menu")})):(d.Replay=function(){a.setMode(stagetrack.mode.REPLAY);$("#gen_map_control_menu").toggleClass("show_menu")}, d.Live=function(){a.setMode(stagetrack.mode.REALTIME);$("#gen_map_control_menu").toggleClass("show_menu")});b=document.createElement("div");b.id="gen_map_control";b.className="gmap_ctrl";b.style.cssText="margin:5px; box-shadow:1px 1px #BBB; -webkit-box-shadow:1px 1px #BBB; -moz-box-shadow:1px 1px #BBB; ";b.innerHTML=this.gmMode==stagetrack.mode.REALTIME?"Live":"Replay";google.maps.event.addDomListener(b,"click",function(){$("#gen_map_control_menu").toggleClass("show_menu");anchorToElement("#gen_map_control_menu", "#gen_map_control","bottom-left")});d=this.buildMapControl({id:"gen_map_control_menu",className:"gmap_ctrl_menu",menuItems:d});document.body.appendChild(d);return b}; stagetrack.prototype.playbackControls=function(){var a=this,b=this.buildMapControl({id:"streplay_ctrl",className:"replayctrls gmap_ctrl",menuItems:{Start:function(){a.setMode(stagetrack.mode.START);a.startReplay()},Pause:function(){a.setMode(stagetrack.mode.PAUSE);a.pauseReplay()},Restart:function(){a.setMode(stagetrack.mode.RESTART);a.restartReplay()}}});b.style.cssText="width:150px; margin:5px; box-shadow: 1px 1px #BBB; -webkit-box-shadow: 1px 1px #BBB; -moz-box-shadow: 1px 1px #BBB;";b.style.display= "none";document.body.appendChild(b);return b}; stagetrack.prototype.selectStageControl=function(){var a=this,b=document.getElementById("stagesel_ctrl");b?$("#stagesel_ctrl").html("Stage: "+(0<this.replayoptions_.stage?this.race.stages.fetch(this.replayoptions_.stage).stage_name:"None")):(b=this.buildMapControl({id:"stagesel_ctrl",className:"gmap_ctrl stage_select",innerHTML:"Stage: "+(0<this.replayoptions_.stage?this.race.stages.fetch(this.replayoptions_.stage).stage_name:"None")}),b.style.cssText="width:160px; margin:5px; box-shadow: 1px 1px #BBB; -webkit-box-shadow: 1px 1px #BBB; -moz-box-shadow: 1px 1px #BBB; ", b.style.display="none",google.maps.event.addDomListener(b,"click",function(){anchorToElement("#stagesel_menu_ctrl","#stagesel_ctrl","bottom-left");$("#stagesel_menu_ctrl").toggleClass("show_menu")}));if(null!=this.race){var d=this.race.stages.fetch(),e={};for(i=0;i<d.length;i++)e[d[i].stage_name]=function(d){return function(){a.setReplayOptions(d);$("#stagesel_menu_ctrl").toggleClass("show_menu");1<=this.gmMode&&this.gmMode<stagetrack.mode.EDIT&&a.restartReplay()}}({stage:d[i].stage_id});d=this.buildMapControl({id:"stagesel_menu_ctrl", className:"gmap_ctrl_menu stage_select",menuItems:e});d.style.cssText="width:160px; box-shadow:1px 1px #BBB; -webkit-box-shadow:1px 1px #BBB; -moz-box-shadow:1px 1px #BBB;";$("#stagesel_menu_ctrl").size()?$("#stagesel_menu_ctrl").html($(d).html()):$(document.body).append(d)}return b}; stagetrack.prototype.mapButton=function(a){a=this.buildMapControl({id:"stdone_btn",className:"gmap_ctrl",menuItems:a});a.style.cssText="width:150px; padding: 2px 0; margin:5px; box-shadow: 1px 1px #BBB; -webkit-box-shadow: 1px 1px #BBB; -moz-box-shadow: 1px 1px #BBB;";a.style.display="none";document.body.appendChild(a);return a}; stagetrack.prototype.mapOptionsControl=function(){var a=this.buildMapControl({id:"_map_options_ctrl",className:"gmap_ctrl map_options_ctrl",innerHTML:"<div id='_map_button'><img src='/images/ctrls/map_options.png' width='' height='' border=0></div><div id='_map_options'><div id='_map_mode'>Mode:<select name='' id='' onchange=''><option>Live</option><option>Replay</option></select></div></div>",onclick:function(){"open"==$("#_map_options_ctrl").data("")?$("#book").slideDown("slow",function(){}):$("#book").slideUp("slow", function(){});$("#map_options_menu").toggleClass("show_menu")}});a.style.cssText="height:20px;";a.style.visibility="hidden";return a}; stagetrack.prototype.playbackProgressControl=function(){var a=this;if(!document.getElementById("stageprogress_ctrl")){$("#map");var b=this.buildMapControl({id:"stageprogress_ctrl",className:"gmap_ctrl stage_select",innerHTML:"<div id='stageprogress_title' style='padding:2px;'><b>Replay Details</b></div><div id='_reply_car_container_' style='padding:2px;'><p align=center><i>No cars selected.</i></p></div><br />"});b.style.cssText="width:96%; padding: 2px 0; margin:5px; box-shadow: 1px 1px #BBB; -webkit-box-shadow: 1px 1px #BBB; -moz-box-shadow: 1px 1px #BBB;"; b.style.display="none";document.body.appendChild(b)}return{addCar:function(d){$(".car_stage_replay_progress").size()||$("#_reply_car_container_").html("");if(!$("#_reply_car_container_").children("#stageprog_car_"+d+"_ctrl").size()){var b=(a.race?a.race.cars.fetch(d):null).car_driver_name,f=a.replayoptions_.data["car_"+d]["stage_"+a.replayoptions_.stage].speeds;$("#_reply_car_container_").append("<div id='stageprog_car_"+d+"_ctrl' class='car_stage_replay_progress' style=''><div class='csrp_car_label'><div id='_carnumber_' class='csrp_car_number'>#"+ d+"</div><div id='_carname_' class='csrp_car_name' style=''>"+b+"</div></div><div id='_progressbar_' class='csrp_progress_bar' style=''></div><div id='_carspeed_' class='csrp_speed'>0 mph</div><div class='clear'></div></div>");d=$("#stageprog_car_"+d+"_ctrl");d.width();d.find(".csrp_car_label:first").width();d=d.find("#_progressbar_");b=d.height();if(f.length>h)var h=d.width(),g=Math.floor(f.length/h);else h=f.length,g=1;for(i=0;i<=h;i++){var j=0;for(p=0;p<g;p++)j+=f[i*g+p];var j=j/g,k=Math.floor(j/ 3);d.append("<div class='speedBar' style='height:"+k+"px;margin-top:"+(b-k)+"px;' title='"+Math.floor(j)+"mph'></div>")}}},updateCar:function(d,b,f,h){b=$("#_reply_car_container_ #stageprog_car_"+d+"_ctrl");b.size()&&(parseFloat(h)==h?b.children("#_carspeed_").html(h+" mph"):b.children("#_carspeed_").html(h),h=$("#stageprog_car_"+d+"_ctrl").find("#_progressbar_"),h.width(),h.children(":eq("+Math.floor(a.replayoptions_.data["car_"+d]["stage_"+a.replayoptions_.stage].position)+")").css("background-color", "black"))},resetCar:function(a){$("#stageprog_car_"+a+"_ctrl").find("#_progressbar_").children().removeAttr("background-color","")},removeCar:function(a){$("#stageprog_car_"+a+"_ctrl").remove();$(".car_stage_replay_progress").size()||$("#_reply_car_container_").html("<p align=center><i>No cars selected.</i></p>")},div:function(){return document.getElementById("stageprogress_ctrl")}}}; stagetrack.prototype.buildMapControl=function(a){var b=document.createElement("div"),d=null,e,f;for(f in a)if("menuItems"==f){null==d&&(d=document.createElement("ul"));for(var h in a[f])e=document.createElement("li"),e.setAttribute("id",h.replace(/\s/g,"_").toLowerCase()),e.innerHTML=h,d.appendChild(e),google.maps.event.addDomListener(e,"click",a[f][h])}else b[f]=a[f];null!=d&&b.appendChild(d);return b}; stagetrack.prototype.toggleMapMenu=function(a,b){a&&"object"==typeof a&&(a.style.display="none"==a.style.display||"show"==b?"block":"none")}; stagetrack.prototype.setReplayOptions=function(a){if("object"==typeof a&&(a.stage||a.car)&&a.stage!=this.replayoptions_.stage)if(a.stage!=this.replayoptions_.stage&&(this.replayoptions_.stage=a.stage,this.replayoptions_.stageid__=a.stage),0<this.replayoptions_.stage){$("#stagesel_ctrl").html("Stage: "+(0<this.replayoptions_.stage?this.race.stages.fetch(this.replayoptions_.stage).stage_name:"None"));this.selectStage("s"+this.replayoptions_.stage,"start");a=this.cars.getSelected();this.controls.progress.start(a.length); for(c=0;c<a.length;c++)this.fetchReplayData(a[c].car_number),this.controls.progress.updateBar(1);this.controls.progress.hide()}}; stagetrack.prototype.fetchReplayData=function(a,b){var d=this;readyCarReplay=function(a){var b=d.replayoptions_.data["car_"+a]["stage_"+d.replayoptions_.stage].coords[0];b&&(d.replayoptions_.data["car_"+a].marker?d.replayoptions_.data["car_"+a].marker.setPosition(b):(d.replayoptions_.data["car_"+a].marker=d.createCarMarker(a,b),d.replayoptions_.data["car_"+a].marker.setMap(d.gmHndl)),d.controls.status.addCar(a))};"object"!=typeof this.replayoptions_.data["car_"+a]||"object"!=typeof this.replayoptions_.data["car_"+ a]["stage_"+this.replayoptions_.stage]?$.ajax({url:this._reqUrl+"?q=car-stage-data&c="+scar.car_id+"&s="+this.replayoptions_.stage+"&d=json&lang=en-us"+(this.apiKey?"&key="+this.apiKey:""),success:function(b){if(0<b.car_stage_data.length){var f=b.car_stage_data[0].coords.split("\n"),b=[],h=[],g=[],j=[],k=[],r=0;d.controls.progress.start(f.length);for(i=0;i<f.length;i++)7<=listLen(f[i],",")&&(b.push(new google.maps.LatLng(listGetAt(f[i],2,","),listGetAt(f[i],1,","))),k.push(listGetAt(f[i],3,",")), j.push(stagetrack.parseMySQLDateTimeToDate(listGetAt(f[i],4,","))),h.push(parseFloat(listGetAt(f[i],5,","))),0<i&&(r+=parseFloat(listGetAt(f[i],7,","))),g.push(r),setTimeout(function(){d.controls.progress.updateBar(1)},100));d.replayoptions_.data["car_"+a]||(d.replayoptions_.data["car_"+a]={staging:!0,timer:null,car_number:a,overall_distance:0});if(0<b.length){f=null;if(d.useroptions.routeHighlight){spdcolors=new stagetrack.util.gradientColor({idxs:h});for(x=0;x<b.length-1;x++)scolor=spdcolors.length> x?spdcolors[x]:spdcolors[spdcolors.length-1],f=f.push(new google.maps.Polyline({path:(b[x],b[x+1]),strokeColor:scolor,strokeOpacity:0.7,strokeWeight:5}))}d.replayoptions_.data["car_"+a]["stage_"+d.replayoptions_.stage]={polyline:null,speedhl:f?f:null,distance:g,time:j,coords:b,speeds:h,frame:null,position:0,posoffset:0,clock:0};readyCarReplay(a);this.debug&&alert("car "+a+" loaded!")}else this.debug&&alert("car "+a+" load failed"),scar.selected=!1;d.controls.progress.hide()}else return alert("No replay data available Car #"+ a+" on Stage "+d.replayoptions_.stage),scar.selected=!1},error:function(){alert("an error occured fetching the replay data for "+a);return!1},dataType:"json",async:!1}):readyCarReplay(a);b&&b()};stagetrack.prototype.unloadReplayData=function(){var a=this.cars.fetch();for(x=0;x<a.length;x++)a[x].selected&&this.selectCar(a[x].car_num)}; stagetrack.prototype.startReplay=function(){if(0==this.replayoptions_.stage)alert("No Stage is selected for replay.");else if(0==this.getSelectedCars().length)alert("You need to select at least one Car to replay the Stage");else{this.replayoptions_.isready=!1;var a,b=this.cars.getSelected();for(a in b)parseInt(a)==a&&this._updateReplay(b[a].car_number);this.replayStateChanged&&this.replayStateChanged(stagetrack.mode.START);return!0}return!1}; stagetrack.prototype._updateReplay=function(a){var b=this,d="car_"+a,e=0,f=null,h=new Date;if(this.gmMode==stagetrack.mode.START&&this.replayoptions_.data[d]&&null!=this.replayoptions_.data[d].marker){var g=this.replayoptions_.data[d]["stage_"+this.replayoptions_.stage];if(g){if(!this.replayoptions_.isready&&this.replayoptions_.data[d].staging){e=this.race.stages.fetch(this.replayoptions_.stage).start;for(n=f=0;35>n;n++)0<parseFloat(g.speeds[g.position+n])&&f++;if(0==g.position&&35==f){ccl=g.coords.length/ 4;fdistfst=stagetrack.distanceFrom(e,g.coords[g.position]);for(n=nspf=0;n<ccl;n++)stagetrack.distanceFrom(e,g.coords[g.position+n])>fdistfst?nspf++:g.speeds[n]<g.speeds[g.position]&&(g.position=n,nspf=ccl);nspf==ccl&&(f=35)}35==f?(0<g.position&&(g.position--,g.posoffset=g.position-1),this.replayoptions_.data[d].staging=!1,this.controls.status.updateCar(a,"00:00.000",0,"Ready!")):(this.controls.status.updateCar(a,"00:00.000",0,"Staging..."),g.position++);this.replayoptions_.data[d].marker.setPosition(g.coords[g.position]); e=100}else if(!this.replayoptions_.isready&&!this.replayoptions_.data[d].staging)if(this.replayStagingReady()){if(e=750,!this.replayoptions_.isready){var j=this.getSelectedCars(),k;for(k in j)this.replayoptions_.data[d].timer=setTimeout(function(){b._updateReplay(j[k].car_number)},e);this.replayoptions_.isready=!0}}else e=250;else if(g.position>=g.coords.length)this.replayoptions_.data[d].timer=null,e=0;else{e=0;if(this.useroptions.smoothReplay&&1<this.useroptions.smoothDetail&&g.position+1<g.coords.length){abspos= g.position-g.position%1;timediff=g.time[abspos+1].getTime()-g.time[abspos].getTime();timeinc=timediff/this.useroptions.smoothDetail;posinc=timeinc/1E3;if(0<(g.position+posinc)%1)if(newpos=g.position+posinc,newpos%1==timediff/2/1E3)f=stagetrack.getMidpoint(g.coords[abspos],g.coords[abspos+1]);else{f=g.coords[abspos+1];for(i=0;i<this.useroptions.smoothDetail/2;i++)f=0.5>newpos%1||0==i?stagetrack.getMidpoint(g.coords[abspos],f):stagetrack.getMidpoint(f,g.coords[abspos+1])}else f=g.coords[Math.round(g.position+ posinc)];e=timeinc;g.position+=posinc}else g.position++,f=g.coords[g.position],e=g.time[g.position+1].getTime()-g.time[g.position].getTime();this.replayoptions_.data[d].marker.setPosition(f);if(0<this.useroptions.routeHighlight||!0==this.useroptions.routeHighlight)null==this.replayoptions_.data[d].polyline&&2<g.position?this.replayoptions_.data[d].polyline=new google.maps.Polyline({map:this.gmHndl,path:Array(f),strokeColor:"#CC00000",strokeOpacity:0.8,strokeWeight:4}):2<g.position&&(updpth=this.replayoptions_.data[d].polyline.getPath(), updpth.push(f),this.replayoptions_.data[d].polyline.setPath(updpth));h=new Date-h;g.clock+=e-h;null!=this.controls.status&&(Math.round(g.position)==g.position?(cdp=Math.round(100*(g.distance[g.position]/g.distance[g.distance.length-1])),spd=g.speeds[g.position]):(abspos=Math.round(g.position),cdp=Math.round(100*(g.distance[abspos]/g.distance[g.distance.length-1])),spd=g.speeds[abspos]),tclock=new Date(g.clock),this.controls.status.updateCar(a,tclock.getMinutes()+":"+tclock.getSeconds()+"."+tclock.getMilliseconds(), cdp,spd))}0<e&&(h="object"==typeof h?new Date-h:h,this.replayoptions_.data[d].timer=this.gmMode!=stagetrack.mode.RESTART?setTimeout(function(){b._updateReplay(a)},(e-h)*this.replayoptions_.speed):null)}}};stagetrack.prototype.pauseReplay=function(){this.setMode(stagetrack.mode.PAUSE)&&this.replayStateChanged&&this.replayStateChanged(stagetrack.mode.PAUSE)}; stagetrack.prototype.restartReplay=function(){this.setMode(stagetrack.mode.RESTART);if(this.gmMode==stagetrack.mode.RESTART){this.replayoptions_.isready=!1;var a="stage_"+this.replayoptions_.stage,b=this.race.cars.getSelected(),d=null,e;for(e in b)if(d=this.replayoptions_.data["car_"+b[e].car_number])d.timer&&(clearTimeout(d.timer),d.timer=null),d.staging=!0,d.overall_distance=0,d[a].clock=0,d[a].position=0,d.marker.setPosition(d[a].coords[d[a].position]),this.controls.status.updateCar(d.car_number, "00:00.000",0,0),this.controls.status.resetCar(b[e].car_number);this.setReplayOptions({stage:this.replayoptions_.stage});this.gmMode=stagetrack.mode.REPLAY;this.replayStateChanged&&this.replayStateChanged(stagetrack.mode.RESTART)}};stagetrack.prototype.getReplayBounds=function(){var a=null,b=new google.maps.LatLngBounds,d;for(d in this.replayoptions_.data)a=this.replayoptions_.data[d],actstg=a["stage_"+this.replayoptions_.stage],b.extend(actstg.coords[Math.round(actstg.position)]);return b}; stagetrack.prototype.replayStagingReady=function(){var a=0,b=this.race.cars.getSelected(),d;for(d in b)parseInt(d)==d&&!this.replayoptions_.data["car_"+b[d].car_number].staging&&a++;return a==b.length?!0:!1}; stagetrack.estimateNextPoint=function(a,b,d){var e=stagetrack.earthRadius.MILES;if("object"==typeof d){with(Math)var f=(a.lng()-d.lng()).toRad(),h=sin(f)*cos(d.lat()),d=cos(a.lat())*sin(d.lat())-sin(a.lat())*cos(d.lat())*cos(f),d=atan2(h,d),d=d.toDeg();alert("estimateNextPoint calc bearing: "+d)}var h=Math.PI/180,f=a.lat()*h,g=a.lng()*h,d=d*h;with(Math)a=asin(sin(f)*cos(b/e)+cos(f)*sin(b/e)*cos(d)),b=g+atan2(sin(d)*sin(b/e)*cos(f),cos(b/e)-sin(f)*sin(a)),b=(b+Math.PI)%(2*Math.PI)-Math.PI;new google.maps.Marker({position:new google.maps.LatLng(a/ h,b/h),map:st.gmHndl,title:"Estimated Point ...",visible:!0})};stagetrack.getMidpoint=function(a,b){var d=Math.PI/180,e=180/Math.PI;lat1=a.lat()*d;lon1=a.lng()*d;lat2=b.lat()*d;var f=(b.lng()-a.lng())*d,d=Math.cos(lat2)*Math.cos(f),f=Math.cos(lat2)*Math.sin(f);lat3=Math.atan2(Math.sin(lat1)+Math.sin(lat2),Math.sqrt((Math.cos(lat1)+d)*(Math.cos(lat1)+d)+f*f));lon3=lon1+Math.atan2(f,Math.cos(lat1)+d);return new google.maps.LatLng(lat3*e,lon3*e)}; stagetrack.distanceFrom=function(a,b){if("object"!=typeof a||"object"!=typeof b)return-1;with(Math){var d=sin(a.lat()/57.2958)*sin(b.lat()/57.2958)+cos(a.lat()/57.2958)*cos(b.lat()/57.2958)*cos(b.lng()/57.2958-a.lng()/57.2958);return stagetrack.earthRadius.MILES*acos(d)}};stagetrack.averageLatLngs=function(a){var b=fd,d=fd;for(x=0;x,a.length;x++)b+=a[x]/2,d+=a[x]/2;return new google.maps.LatLng(b,d)}; stagetrack.getRouteCoords=function(a,b,d){var e=[],f=new google.maps.DirectionsService;f&&f.route({origin:a,destination:b,travelMode:google.maps.DirectionsTravelMode.DRIVING},function(f,g){if(g==google.maps.DirectionsStatus.OK){var j=f.routes[0];for(li=0;li<j.legs.length;li++)for(si=0;si<j.legs[li].steps.length;si++)if(j.legs[li].steps[si].path)for(pi=1;pi<j.legs[li].steps[si].path.length-1;pi++)e.push(j.legs[li].steps[si].path[pi]);e[0].equals(a)||e.splice(0,0,a);e[e.length-1].equals(b)||e.splice(e.length, 0,b);d&&d(e)}})};stagetrack.appendRouteCoords=function(){}; stagetrack.displayPanel=function(a,b){var d="string"==typeof a?$("#"+a+"-panel"):a;b||(b={});d.data("init")||(d.size()||(d=$("<div class='popup-main'><div id='"+a+"-grid' class='panel-content clear'></div></div>").attr("id",a+"-panel").appendTo(document.body)),b.noclose||$("<span class='close'><a href=\"javascript:stagetrack.displayPanel('"+a+'\');"><img src="/images/close-x.png" width="14" height="14" border="0"/></a></span>').insertBefore("#"+d.children(".panel-content").attr("id")),roundCorners(d, "large"),d.css({height:b.height?b.height:"",width:b.width?b.width:"",maxWidth:$(document.body).innerWidth(),maxHeight:$(document).height()-30}),d.children(".panel-content").css({width:d.width()-42+"px",height:b.height?d.height()-(23-(b.noclose?5:0))+"px":"",maxWidth:$(document.body).innerWidth(),maxHeight:$(document).height()-80}),b.draggable&&d.draggable(),d.data("init",!0));this.center=function(){centerOverlay(d)};if(d.hasClass("popup-main-show")){if(d.has(":visible")){d.removeClass("popup-main-show"); $(".popup-main:visible").size()?$(".popup-main:visible").topZIndex({decrease:1}):stagetrack.hideBlanket();if(b.onclose)b.onclose();d.data("onclose")&&(cpfunc=d.data("onclose"),cpfunc())}}else stagetrack.showBlanket(),d.children(".panel-content").html("<div class='loader-lg'><span>Loading....</span></div>"),centerOverlay(d),d.topZIndex({increment:1}).addClass("popup-main-show"),loadComplete=function(a,f,h){if(b.onopen)b.onopen(a,f,h);b.onclose&&d.data("onclose",onclose);loadUIEnhancements&&loadUIEnhancements()}, b.norefresh?loadComplete(d):d.children(".panel-content").load("/include/panels/general.php?ptype="+a+(b.qstring?"&"+b.qstring:""),function(){centerOverlay(d);loadComplete(d)})}; stagetrack.displayForm=function(a,b,d,e){0==$(a).length&&$(document.body).append('<div id="'+a.replace("#","")+'" class="standard-form common-form border-form"></div>');0>a.indexOf("#")&&(a="#"+a);!e&&"object"==typeof d&&(e=d);e||(e={});var f=$(a);!f.hasClass("form-show")||f.has(window.location.hash?window.location.hash+"-panel":"")&&""==f.html().trim()?(f.parent().length&&centerOverlay(a,"#"+f.parent().get(0).id),loadComplete=function(a,b,e){d&&"object"==typeof d&&d(a,b,e);f.data("loaded",!0);1== f.parents(".popup-main-show").size()&&centerOverlay(f.parents(".popup-main-show"))},b?(f.siblings().removeClass("form-show"),f.addClass("form-show").show().append("<div class='loader-lg'><span>Loading...</span></div>"),f.data("content","/include/panels/general.php?ptype="+b+(e.qstring?"&"+e.qstring:"")),f.load("/include/panels/general.php?ptype="+b+(e.qstring?"&"+e.qstring:""),loadComplete)):(f.siblings().removeClass("form-show"),f.addClass("form-show").show(),loadComplete())):f.not(window.location.hash? window.location.hash+"-panel":"").removeClass("form-show").hide();return f};stagetrack.refreshForm=function(a,b){0>a.indexOf("#")&&(a="#"+a);var d=$(a).data("content");return d?($(a).load(d,b),!0):!1};stagetrack.loadgfx=function(){};stagetrack.checkRequiredFields=function(a,b){var d=0,e=[];$(a).each(function(){0==$(this).attr("value").length?($(this).addClass("highlight-field"),d++):$(this).removeClass("highlight-field");e.push($(this).attr("name"))});return 0<d?(b&&b(),!1):e}; stagetrack.showBlanket=function(a){a||(a={});a.show=!0;return stagetrack.blanket(a)};stagetrack.hideBlanket=function(a){a||(a={});a.show=!1;return stagetrack.blanket(a)}; stagetrack.blanket=function(a){if(a){var b=$("#popup-blanket");b.size()||(b=$("body").append('<div id="popup-blanket"></div>'));b.css(a.show?{height:$(document).height()+"px",width:$(document.body).innerWidth()+"px",zIndex:a.zIndex?a.zIndex:b.topZIndex({increment:1})}:{height:0,width:0,zIndex:0});a.show?b.fadeIn("normal"):b.fadeOut("normal");return b}};stagetrack.blanketResize=function(){return stagetrack.blanket({show:!0})}; stagetrack.launchAppWnd=function(a,b){if(a)return window.open(a?"/app/?launch="+(b?b:"normal")+"&rid="+a:"","_blank")};stagetrack.buildOptSet=function(a,b){for(op in a)b[op]||(b[op]=a[op]);return b};stagetrack.parseReversedLatLng=function(a){"string"!=typeof a&&(a=a.toString());return!a.split(",").length?new google.maps.LatLng(0,0):new google.maps.LatLng(listGetAt(a,2,","),listGetAt(a,1,","))}; stagetrack.prototype.setOption=function(a,b){if("object"==typeof a)for(opt in optobj)this.useroptions[opt]=optobj[opt];else this.useroptions[a]=b};stagetrack.prototype.toggleOption=function(a){!0==this.useroptions[a]?this.setOption(a,!1):!1==this.useroptions[a]&&this.setOption(a,!0)};stagetrack.prototype.getOption=function(a){return this.useroptions[a]};stagetrack.prototype.updateOption=function(a){alert("updateOption DEBUG:"+a);this.options[opt];for(opt in a)this.options[opt]=opt}; stagetrack.prototype.saveOptions=function(){};stagetrack.prototype.createMarker=function(a){if(a){var b={title:title,position:latlng,map:this.gmHndl,clickable:!0},d;for(d in a)b[d]&&(b[d]=a[d]);new google.maps.Marker(b)}};stagetrack.prototype.createStaticMarker=function(){this.createMarker({});if("object"!=typeof this.poimarkers)return null;for(x=0;x<this.poimarkers.length;x++)if(smkrid==this.poimarkers[x].id)return this.poimarkers[x]}; stagetrack.prototype.getStaticMarker=function(a){if("object"!=typeof this.poimarkers)return null;for(x=0;x<this.poimarkers.length;x++)if(a==this.poimarkers[x].id)return this.poimarkers[x]}; stagetrack.prototype.addEventMarker=function(a,b,d,e,f){if(!this.eventMarkerExists(a)){var h=this;f||(f=!1);if(d&&0<d.length){latlng="string"==typeof d?stagetrack.parseReversedLatLng(d):d;var b=new google.maps.Marker({title:b,position:latlng,map:this.gmHndl,clickable:!0}),g=null;e&&!e.match(/^http\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?$/)&&(g=new google.maps.InfoWindow({position:latlng,content:"<span class='map-info-box'>"+e+"</span>"}),google.maps.event.addListener(b,"click",function(){g.open(h.gmHndl)}), f&&g.open(this.gmHndl));this.eventmarkers.length?this.eventmarkers.push({id:a,marker:b,info:g}):this.eventmarkers.addMarker(b);return this.eventmarkers[this.eventmarkers.length-1]}}};stagetrack.prototype.eventMarkerExists=function(a){for(x=0;x<this.eventmarkers.length;x++)if(this.eventmarkers[x].id==a)return this.eventmarkers[x].id==a};stagetrack.prototype.setCarData=function(a,b){for(x=0;x<this.cars.length;x++)this.cars[x].car_number==a&&(this.cars[x]=b)}; stagetrack.prototype.panToCar=function(a){if(!this.gmHndl)return!1;if(this.gmMode==stagetrack.mode.REALTIME){var b=this.cars.fetch(a);return b.car_coordinates&&0<b.car_coordinates.length?(cpcoords=b.getPosition().split(","),this.panTo(new google.maps.LatLng(cpcoords[1],cpcoords[0])),stageMarkers[a].info&&stageMarkers[a].info.open(this.gmHndl,stageMarkers[a]),!0):!1}this.gmMode==stagetrack.mode.REPLAY&&(this.cars.fetch(a),this.debug&&alert("To be completed."))}; stagetrack.prototype.reserveHighlightColor=function(a){for(var b in this.highlightColors)if(!this.highlightColors[b])return this.highlightColors[b]=a,b};stagetrack.prototype.releaseHighlightColor=function(a){for(var b in this.highlightColors)if(this.highlightColors[b]&&this.highlightColors[b]==a)return this.highlightColors[b]=null,!0}; stagetrack.prototype.selectCar=function(a,b,d){scar=this.cars.fetch(a);pctrl=$("#entcar-"+a);if(!pctrl.hasClass("ent-car-selected")&&!scar.selected){var e=this.reserveHighlightColor("#entcar-"+a),f={path:null,strokeColor:e,strokeOpacity:0.7,strokeWeight:5};"object"!=typeof scar.markers&&inst.useroptions.routeMarkers&&(scar.markers=[]);if(this.gmMode==stagetrack.mode.REALTIME)b&&$(b).attr("disabled","disabled"),$.getJSON(this._reqUrl+"?q=car-live-data&c="+scar.car_id+"&d=json&lang=en-us&key="+this.apiKey, function(e,g,j){return function(k,r){if("success"==r){for(var o=k.car_live_data,l=0,q=0,m=[];1<o.length&&l<o.length&&"pos"==o[l].dtype;){q!=o[l].stage_id&&null!=o[l].stage_id&&(0<m.length&&(f.path=m,g.setRoute("stage-"+q,new google.maps.Polyline(f)),g.lines["stage-"+q].setMap(e.gmHndl),g.lines["stage-"+q].path=m,g.lines["stage-"+q].path_corrected=[]),q=o[l].stage_id,m=[]);m.push(stagetrack.parseReversedLatLng(o[l].coords));var s=1<m.length&&l<o.length-1?3.2808399*google.maps.geometry.spherical.computeDistanceBetween(m[m.length- 1],stagetrack.parseReversedLatLng(o[l+1].coords)):101;100<s&&0==q&&e.useroptions.routeMarkers&&g.markers.push(new google.maps.Marker({title:"Last Update: "+o[l].edatetime+(e.debug?" "+l:""),position:m[m.length-1],map:e.gmHndl,icon:stagetrack.icon.marker.SPLIT,flat:!0,clickable:!1,visible:!0,zIndex:500+g.markers.length}));l+1<o.length&&e.useroptions.routeSnap&&q==o[l].stage_id&&(s=5280*o[l+1].distprogress,e.debug&&alert(s+" // "+dpmtrs+"=="+3.2808399*dpmtrs));l++}0<m.length&&null!=q&&(f.path=m,g.setRoute("stage-"+ q,new google.maps.Polyline(f)),g.setRouteCoords("stage-"+q,m));e.debug&&alert("debug: "+m.length);e.displayCarRoute(g,0,j);e.cars.setSelected(a);d&&d(!0)}else e.debug&&alert("selectCar (getJSON): "+r);b&&$(b).removeAttr("disabled")}}(this,scar,e,b));else{if(0<this.replayoptions_.stage){b&&$(b).attr("disabled","disabled");if(this.gmMode>stagetrack.mode.REPLAY)if(confirm("The replay will restart in order to load the selected car. Do you want to continue?"))this.setMode(stagetrack.mode.RESTART);else return; this.fetchReplayData(a,function(){b&&$(b).removeAttr("disabled");d&&d(!0)})}d&&d(!0)}pctrl.addClass("ent-car-selected").css("background-color",e);this.cars.setSelected(a)}else{this.gmMode>=stagetrack.mode.REPLAY&&(this.replayoptions_.data["car_"+a]&&this.replayoptions_.data["car_"+a].marker&&(this.replayoptions_.data["car_"+a].marker.setMap(null),this.replayoptions_.data["car_"+a].marker=null),this.controls.status.removeCar(a));this.releaseHighlightColor("#entcar-"+a);pctrl.css("background-color", "");pctrl.removeClass("ent-car-selected");alert(scar.lines.length);for(e in scar.lines)0<=e.indexOf("stage")&&scar.lines[e].setMap(null);for(i=0;i<scar.markers.length;i++)scar.markers[i].setMap(null);this.gmMode>=stagetrack.mode.LIVE&&(scar.markers=[]);scar.selected=!1;d&&d(!1)}}; stagetrack.prototype.displayCarRoute=function(a,b,d){try{var e="stage-"+b,f=a.getRoute(e),h=!1,g=f.getPath();if(g){if(this.useroptions.routeSnap){crc=a.getRouteCoords(e);for(x=b=a=0;x<crc.length-1;x++)if(dpmtrs=google.maps.geometry.spherical.computeDistanceBetween(crc[x],crc[x+1]),b=3.2808399*dpmtrs,1300<b&&!1==h){this.debug&&alert(b+" // "+dpmtrs+"=="+3.2808399*dpmtrs);0<x&&(h=!0);xpos=x;var j=this;stagetrack.util.getRouteCoords(this.gmDirSvc,{origin:crc[x],destination:crc[x+1]},function(a){alert("curr pos:"+ xpos+" // new pos?"+x+" // "+a.length+" // path len:"+g.getLength());for(c=0;c<a.length;c++)g.insertAt(xpos+c+1,a[c]);(new google.maps.Polyline({path:a,strokeColor:"#00CCFF",strokeOpacity:0.7,strokeWeight:2})).setMap(j.gmHndl)});a++}this.debug&&alert("Created "+a+" route adjustments from "+crc.length)}else(crc=a.getRouteCoords("stage-"+b))&&f.setPath(crc);f.setOptions({strokeColor:d,strokeOpacity:0.7,strokeWeight:5});f.setMap(this.gmHndl);return!0}}catch(k){alert("Unable to display car route; "+k)}return!1}; stagetrack.prototype.getSelectedCars=function(){return this.cars.getSelected()};stagetrack.prototype.createCarMarker=function(a,b,d){a=this.cars.fetch(a);return new google.maps.Marker({position:b,clickable:!0,map:this.gmHndl,title:"Car "+a.car_number,icon:"/images/markers/rally/badge-shadow-"+(!d?"38":d)+".png",shadow:"/images/markers/rally/badge-"+a.car_icon+".png"})};stagetrack.prototype.updateCarMarkers=function(){}; stagetrack.prototype.showCarRouteHighlight=function(a){if(inst.replayoptions_.stage&&(selc=this.cars.fetch(a),this.gmMode==stagetrack.mode.REPLAY&&this.replayoptions_.data["car_"+a]["stage_"+inst.replayoptions_.stage].speedhl)){fd=this.replayoptions_.data["car_"+a]["stage_"+inst.replayoptions_.stage].speedhl;for(x=0;x<fd.length;x++)fd[x].setMap(this.gmHndl)}};stagetrack.prototype.hideCarRouteHighlight=function(){}; stagetrack.prototype.loadStaticMarkers=function(){$.ajax({url:this._reqUrl,context:document.body,type:"GET",data:"q=static-markers&d=json&lang=en-us&key="+this.apiKey,success:function(a){return function(b){var b=$.parseJSON(b).static_markers,d;null==a.poimarkers&&(a.poimarkers=[]);for(x=0;x<b.length;x++)d=b[x].rpoi_coords.split(","),smkr=a.getStaticMarker(b[x].rpoi_id),null==smkr||"undefined"==typeof smkr.marker?(a.poimarkers[x]={},a.poimarkers[x].id=b[x].rpoi_id,a.poimarkers[x].title=b[x].rpoi_title, a.poimarkers[x].marker=new google.maps.Marker({position:new google.maps.LatLng(d[1],d[0]),map:a.gmHndl,clickable:!0,title:b[x].rpoi_title,icon:"/images/markers/rally/sm/"+b[x].rpoi_marker_icon+".png",shadow:"/images/markers/rally/sm/40x40shadow.png"}),b[x].rpoi_details&&-1<b[x].rpoi_details.indexOf("|")?(info_detail=b[x].rpoi_details.substr(0,b[x].rpoi_details.indexOf("|")),dcontent=b[x].rpoi_details.substr(b[x].rpoi_details.indexOf("|")+1),dtype=dcontent.substr(0,dcontent.indexOf(":")),dcontent= dcontent.substr(dcontent.indexOf(":")),fd=$('<a href="javascript:;">Launch Content</a>').click(function(){alert(dcontent)})):info_detail=b[x].rpoi_details,a.poimarkers[x].info=new google.maps.InfoWindow({content:"<span id='"+x+"' class='map-info-box'><b>"+a.poimarkers[x].title+"</b></span>"+(info_detail?"<br>"+info_detail:"abc")}),google.maps.event.addListener(a.poimarkers[x].marker,"click",function(a,d){return function(){d.info.open(a.gmHndl,d.marker)}}(a,a.poimarkers[x]))):smkr.marker.setPosition(new google.maps.LatLng(d[1], d[0]))}}(this)})};stagetrack.prototype.getStaticMarkerById=function(a){for(x=0;x<this.poimarkers.length;x++)if(this.poimarkers[x].id==a)return this.poimarkers[x]}; stagetrack.prototype.loadStageMarkers=function(){var a=this.race.stages.fetch();for(x=0;x<a.length;x++)a[x].start&&(esm=this.race.stages.getStageByMakerPos("start",a[x].start),null!=esm&&esm.markers.start?esm.markers.start.getPosition()==a[x].start?esm.markers.start.setTitle(esm.markers.start.getTitle()+"!"+a[x].stage_name+": Start"):esm.markers.end.setTitle(esm.markers.end.getTitle()+"!"+a[x].stage_name+": Start"):(a[x].markers.start=new google.maps.Marker({position:a[x].start,map:this.gmHndl,icon:"/images/markers/rally/sm/start.png", clickable:!0,title:a[x].stage_name+": Start"}),a[x].markers.start.info=new google.maps.InfoWindow({content:"<span id='stage-info-box-"+a[x].stage_id+"' class='map-info-box'><b>"+a[x].stage_name+": Stage Start</b><br />First Car Out: "+a[x].stage_firstcarout+" "+a[x].stage_date+"<br />Body Time: "+a[x].stage_bogytime+"<br />"+(0<a[x].stage_fasttime.length&&a[x].stage_winner?"Stage Winner: "+a[x].stage_winner+" ("+a[x].stage_fasttime+")<br />":"")+(a[x].stage_topspeed?"Top Speed: "+a[x].stage_topspeed+ "<br /></span>":"")}),google.maps.event.addListener(a[x].markers.start,"click",function(a,d){return function(){d.info.open(a.gmHndl,d)}}(this,a[x].markers.start,a[x].stage_id)),google.maps.event.addListener(a[x].markers.start,"mouseover",function(a,d){return function(){a.highlightStageRoute(d)}}(this,a[x].stage_id)),google.maps.event.addListener(a[x].markers.start,"mouseout",function(a,d){return function(){var e=a.race.stages.fetch(d);e.polyline&&!a.useroptions.stagesHighlightAll&&e.polyline.setMap(null)}}(this, a[x].stage_id)))),a[x].end&&(a[x].markers.end=new google.maps.Marker({position:a[x].end,map:this.gmHndl,icon:"/images/markers/rally/sm/finish.png",clickable:!0,title:a[x].stage_name+": Finish"}),a[x].markers.end.info=new google.maps.InfoWindow({content:"<span class='map-info-box'><b>"+a[x].stage_name+": Stage Finish</b><br />Body Time: "+a[x].stage_bogytime+"<br />Stage Winner: "+a[x].stage_winner+" ("+a[x].stage_fasttime+")<br />Top Speed: "+a[x].stage_topspeed+"<br /></span>"}),google.maps.event.addListener(a[x].markers.end, "click",function(a,d){return function(){d.info.open(a.gmHndl,d)}}(this,a[x].markers.end,a[x].stage_id)),google.maps.event.addListener(a[x].markers.end,"mouseover",function(a,d){return function(){a.highlightStageRoute(d)}}(this,a[x].stage_id)),google.maps.event.addListener(a[x].markers.end,"mouseout",function(a,d){return function(){var e=a.race.stages.fetch(d);e.polyline&&!a.useroptions.stagesHighlightAll&&e.polyline.setMap(null)}}(this,a[x].stage_id)))}; stagetrack.prototype.selectStage=function(a,b){if(0==parseInt(a.substr(1))){if(!this.useroptions.stagesHighlightAll){var d=this.race.stages.fetch();for(x=0;x<d.length;x++)"object"==typeof d[x].polyline&&d[x].polyline.setMap(null)}}else if("s"==a.substr(0,1)&&0<a.substr(1)){var d=a.substr(1),e=this.race.stages.fetch(d),f=e.start?e.start:new google.maps.LatLng(parseFloat(listGetAt(e.stage_loc_start,2,",")),parseFloat(listGetAt(e.stage_loc_start,1,","))),h=e.end?e.end:new google.maps.LatLng(parseFloat(listGetAt(e.stage_loc_end, 2,",")),parseFloat(listGetAt(e.stage_loc_end,1,",")));if(b&&"start"==b)this.panTo(f,14);else if(b&&"end"==b)this.panTo(h,14);else{var g=new google.maps.LatLngBounds;(!e.stage_kml_overlay_url||!(0<e.stage_kml_overlay_url.length&&this.debug))&&this.highlightStageRoute(d);g.extend(f);g.extend(h);this.fitBounds(g)}}else 0<a&&this.panTo(st.getStaticMarkerById(a).marker.getPosition(),15)}; stagetrack.prototype.toggleStageHighlight=function(a){if(!this.useroptions.stagesHighlightAll){var b=this.race.stages.fetch(a);"object"==typeof b.polyline?null!=b.polyline.getMap()?b.polyline.setMap(null):b.polyline.setMap(this.gmHndl):this.selectStage("s"+a)}}; stagetrack.prototype.createStageHighlight=function(a){var b=[],d=this.race.stages.fetch(a),e=0;if("object"!=typeof d.polyline||0>=a){if(d.splits.length){stagetrack.getRouteCoords(d.start,d.splits[0]);for(x=1;x<d.splits.length-1;x++)stagetrack.getRouteCoords(d.splits[x],d.splits[x+1],function(a){b.concat(a);e++});b.concat(stagetrack.getRouteCoords(d.splits[d.splits.length-2],d.end))}else stagetrack.getRouteCoords(d.start,d.end,function(a){b.concat(a);e++;alert(e)});this.debug&&setTimeout(function(){alert("createStageHighlight:"+ d.coords.length+"//"+b.length)},3E3);d.polyline=new google.maps.Polyline({path:d.coords,strokeColor:"#0066FF",strokeOpacity:0.7,strokeWeight:5});return!0}return!1}; stagetrack.prototype.highlightStageRoute=function(a){var b=this.race.stages.fetch(a);"object"!=typeof b.polyline&&!b.kmllayer||0>=a?this.gmDirSvc.route({origin:b.start,destination:b.end,travelMode:google.maps.DirectionsTravelMode.DRIVING},function(d){return function(b,f){var h=d.race.stages.fetch(a);if(f==google.maps.DirectionsStatus.OK){var g=b.routes[0];for(li=0;li<g.legs.length;li++)for(si=0;si<g.legs[li].steps.length;si++)if(g.legs[li].steps[si].path)for(pi=1;pi<g.legs[li].steps[si].path.length- 1;pi++)h.coords.push(g.legs[li].steps[si].path[pi]);h.coords.length&&(h.coords[0].equals(h.start)||h.coords.splice(0,0,h.start),h.coords[h.coords.length-1].equals(h.end)||h.coords.splice(h.coords.length,0,h.end),h.polyline=new google.maps.Polyline({path:h.coords,strokeColor:"#0066FF",strokeOpacity:0.7,strokeWeight:5}),h.polyline.setMap(d.gmHndl))}}}(this)):b.polyline&&b.polyline.setMap(this.gmHndl)}; stagetrack.prototype.showStageMarkers=function(){var a=this.race.stages.fetch();for(x=0;x<a.length;x++)for(var b in a[x].markers)a[x].markers[b].setMap&&a[x].markers[b].setMap(this.gmHndl)};stagetrack.prototype.hideStageMarkers=function(){var a=this.race.stages.fetch();for(x=0;x<a.length;x++)for(var b in a[x].markers)a[x].markers[b].setMap&&a[x].markers[b].setMap(null)}; stagetrack.prototype.jumpTo=function(a,b){if("string"==typeof a){cpcoords=a.split(",");var d={center:new google.maps.LatLng(cpcoords[1],cpcoords[0])}}else d={center:a};"undefined"!=typeof b&&null!=b&&(d.zoom=b);this.gmHndl.setOptions(d)};stagetrack.prototype.panTo=function(a,b){"string"==typeof a&&alert(a);this.gmHndl.panTo(a);"undefined"!=typeof b&&this.gmHndl.setZoom(b)};stagetrack.prototype.panToBounds=function(a,b){this.gmHndl.panToBounds(a);"undefined"!=typeof b&&this.gmHndl.setZoom(b)}; stagetrack.prototype.fitBounds=function(a){this.gmHndl.fitBounds(a)};stagetrack.prototype.refreshStandings=function(){$.getJSON(this._reqUrl+"?q=races&d=json&lang=en-us&key="+this.apiKey,function(a){$(selectElem).each(function(){populateList(this,a.races,{text:"race_title",value:"race_id"})})})};stagetrack.prototype.displayForm=function(a,b,d){stagetrack.diplayForm(a,b,d)}; stagetrack.prototype.displayStandings=function(a){var b=$("#"+a);b.data("init")||($("<div style='position:relative;float:right;margin:0 9px;'><a href=\"javascript:st.displayStandings('"+a+'\');"><img src="/images/close-x.png" width="14" height="14" border="0"/></a></div>').insertBefore("#stats-grid"),roundCorners(a,"large"),b.css({height:window.innerHeight-250+"px"}),b.children(".panel-content").css({height:b.height()-38+"px",width:b.width()-38+"px"}),b.data("init",!0));b.hasClass("popup-main-show")? (b.removeClass("popup-main-show"),popBlanket("hide")):(popBlanket(),centerOverlay("#"+a),b.children(".panel-content").load("/include/panels/general.php?ptype=standings"),b.addClass("popup-main-show"))};stagetrack.prototype.refreshStandings=function(){};stagetrack.prototype.loadAllRaces=function(){this.races=new races(this._reqUrl,!0)}; stagetrack.prototype.populateRacesList=function(a){$.getJSON(this._reqUrl+"?q=races&d=json&lang=en-us&key="+this.apiKey,function(b){$(a).each(function(){populateList(this,b.races,{text:"race_title",value:"race_id"})})})};stagetrack.userSettings=function(){};stagetrack.userSettings.prototype.load=function(){};function Route(){this.lines=[];this.markers=[];this.path=[];this.createRouteLines=function(){};!this.path.length&&!this.lines.length&&this.createRouteLines()} function races(a,b,d){this._races=[];this._dates=[];this._reqUrl=a||null;this.autoloadcars=b||!1;this.apiKey="";this.load(d)} races.prototype.load=function(a){$.getJSON(this._reqUrl+"?q=races&d=json&lang=en-us"+(this.apiKey?"&key="+this.apiKey:""),function(a,d){return function(e,f){if("success"==f){a._races=e.races;for(i=0;i<a._races.length;i++)try{var h=(a._races[i].race_start_date.split(" ")[0]).split('-'),g=(a._races[i].race_end_date.split(" ")[0]).split('-');a._races[i].dates={start:(new Date(h[0],parseInt(h[1])-1,h[2])),end:(new Date(g[0],parseInt(g[1])-1,g[2]))};a._races[i].stages=null;a._races[i].cars=null;a._races[i].settings=null;a._races[i].getEvents= function(a,d,b){this._getEvents(d,b)}}catch(j){alert("Error in races.load(): "+j)}d&&d.isReady?d.isReady():d&&d()}else alert("Error in races.load(): "+f)}}(this,a))};races.prototype.length=function(){return this._races.length};races.prototype.fetch=function(a,b,d){b=null;for(x=0;x<this._races.length;x++)if(this._races[x].race_id==a)try{this._preload(x,d),b=this._races[x]}catch(e){alert("Error loading Race data for "+this._races[x].race_title)}a||(b=this._races);d&&d(b);return b}; races.prototype._preload=function(a,b){this._races[a].loading=!0;this._races[a].stages||(this._races[a].stages=new stages(this._reqUrl,this._races[a].race_id,"detail",b));this._races[a].cars||(this._races[a].cars=new cars(this._reqUrl,this._races[a].race_id,"list",b));this._races[a].settings||(this._races[a].settings={replay:!0,realtime:!0});return!0}; races.prototype._getEvents=function(a,b,d){d||(d=b);inst=this;$.getJSON(this._reqUrl+"?q=race-events&d=json&r="+this._races[a].race_id+(b.start_datetime?"&ldt="+b.start_datetime:"")+"&lang=en-us"+(this.apiKey?"&key="+this.apiKey:""),function(a){d(a,inst)})};function stages(a,b,d,e){this._stages=[];this._reqUrl=a||null;this.raceid=b||null;this.type=d||"list";this.apiKey="";this.load(e)}stages.prototype.length=function(){return this._stages.length}; stages.prototype.load=function(a,b){"string"==typeof a&&(this.type=a);"object"==typeof a&&!b&&(b=a);if(0<this.type.length&&"list"!=this.type&&"detail"!=this.type)return!1;$.getJSON(this._reqUrl+"?q=stage-"+this.type+"&r="+this.raceid+"&d=json&lang=en-us&key="+this.apiKey,function(a,b){return function(f,h){if("success"==h){a._stages="list"==a.type?f.stages_list:f.stages;for(i=0;i<a._stages.length;i++)a._stages[i].stage_loc_start&&(a._stages[i].start=new google.maps.LatLng(parseFloat(listGetAt(a._stages[i].stage_loc_start, 2,",")),parseFloat(listGetAt(a._stages[i].stage_loc_start,1,",")))),a._stages[i].stage_loc_end&&(a._stages[i].end=new google.maps.LatLng(parseFloat(listGetAt(a._stages[i].stage_loc_end,2,",")),parseFloat(listGetAt(a._stages[i].stage_loc_end,1,",")))),a._stages[i].stage_kml_overlay_url&&(a._stages[i].kmllayer=new google.maps.KmlLayer(a._stages[i].stage_kml_overlay_url,{suppressInfoWindows:!0})),a._stages[i].coords=[],a._stages[i].markers={},a._stages[i].splits=[],a._stages[i].highlight=function(){}, a._stages[i].save=function(){this.save(a._stages[i].stage_id)}}b&&b.isReady&&b.isReady(a._stages)}}(this,b))};stages.prototype.refresh=function(){this.load()};stages.prototype.add=function(a,b,d,e,f){this._stages.push({stage_id:0,stage_name:a,start:b,end:d,markers:e,coords:[],splits:f?f:[]});return!0};stages.prototype.save=function(a){if(a)fd=this.serialize(a);else for(i=0;i<this._stages.length;i++)this.save(this._stages[i].stage_id);return!1}; stages.prototype.serialize=function(a){if(a){var a=this.fetch(a),b;for(b in a)alert(b+"/"+a[b])}else for(i=0;i<this._stages.length;i++)this.serialize(this._stages[i].stage_id);return""};stages.prototype.getroute=function(){};stages.prototype.fetch=function(a){for(x=0;x<this._stages.length;x++)if(this._stages[x].stage_id==a)return this._stages[x];return!a?this._stages:""};stages.prototype.buildMarkers=function(){for(x=0;x<this._stages.length;x++);}; stages.prototype.getStageByMakerPos=function(a,b){b||(b=a);for(x=0;x<this._stages.length;x++)if(this._stages[x].start==b||this._stages[x].end==b)return this._stages[x]};stages.prototype.getStage=function(a){var b=[];for(x=0;x<this._stages.length;x++)for(i=0;i<a.length;i++)this._stages[x].stage_id==a[i]&&b.push(this._stages[x]);return b}; stagetrack.parseMySQLDateTimeToDate=function(a){a=a.replace(/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/,"$1 $2 $3 $4 $5 $6").split(" ");return new Date(a[0],a[1]-1,a[2],a[3],a[4],a[5])};stagetrack.elapsedTimeDiffMinutes=function(a){var b=new Date,a=mysqlTimeStampToDate(a);return Math.ceil((b.getTime()-a.getTime())/6E4)}; mapControl=function(a){var b=progressBar.combineOptions(opts,{height:"1.3em",width:"150px",top:"30px",right:"5px",colorBar:"#68C",background:"#FFF",fontFamily:"Arial, sans-serif",fontSize:"12px"}),d;for(i=0;i<a.length;i++)d=document.createElement("div"),d.id=a[i].id,d.style.cssText=a[i].style,d.onclick=a[i].onclick,d.innerHTML=a[i].content;d=document.createElement("div");d.id="progressdiv";d.style.cssText="margin: 5px; margin-right: 8px; width: "+b.width+"; height: "+b.height+"; ";var e=document.createElement("div"); e.id="progressbar";e.style.cssText="width: 100%; height: 100%; visibility: hidden; background: white; text-align: center; border: 1px solid #BBB; box-shadow: 1px 1px #888; -webkit-box-shadow: 1px 1px #888; -moz-box-shadow: 1px 1px #888; ";e.style.fontFamily=b.fontFamily;e.style.fontSize=b.fontSize;a=document.createElement("div");a.id="pb_text";a.style.cssText="position: absolute; width: 100%; height: 100%; ";a.style.fontFamily=b.fontFamily;var f=document.createElement("div");f.id="pb_background"; f.style.cssText="position: absolute; width: 0%; height: 100%; background-color: "+b.colorBar+";";e.appendChild(f);e.appendChild(a);d.appendChild(e);return{draw:function(a){d=e;contcontrolDivrol.style.cssText=e.style.cssText+"z-index: 20; position: absolute; top: "+b.top+"; right: "+b.right+"; "+document.getElementById(a).children[0].appendChild(d)},hide:function(){e.style.visibility="hidden"},getDiv:function(){return d}}}; progressBar=function(a){var b=progressBar.combineOptions(a,{height:"1.3em",width:"150px",top:"30px",right:"5px",colorBar:"#68C",background:"#FFF",fontFamily:"Arial, sans-serif",fontSize:"12px"}),d=0,e=0,f=document.createElement("div");f.id="pg_div";a=f.style;f.style.cssText="box-shadow: 1px 1px #888; -webkit-box-shadow: 1px 1px #888; -moz-box-shadow: 1px 1px #888; ";a.display="none";a.width=b.width;a.height=b.height;a.marginRight="6px";a.border="1px solid #BBB";a.background=b.background;a.fontSize= b.fontSize;a.textAlign="left";var h=document.createElement("div");h.id="pg_text";a=h.style;a.position="absolute";a.width="100%";a.border="5px";a.textAlign="center";a.verticalAlign="bottom";var g=document.createElement("div");g.id="pg_bar";g.style.height=b.height;g.style.backgroundColor=b.colorBar;f.appendChild(h);f.appendChild(g);var j=function(a){if(parseInt(a)===a&&e)d+=parseInt(a),d>e?d=e:0>d&&(d=0),g.style.width=Math.round(100*(d/e))+"%",h.innerHTML=d+" / "+e;else if(!e)return e;return d};return{draw:function(a){f.style.cssText= control.style.cssText+"z-index: 20; position: absolute; top: "+b.top+"; right: "+b.right+"; ";document.getElementById(a).children[0].appendChild(f)},start:function(a){parseInt(a)===a&&0<a&&(e=a,d=0,g.style.width="0%",h.innerHTML="Loading...",f.style.display="block");return e},updateBar:j,hide:function(){f.style.display="none"},getDiv:function(){return f},getTotal:function(){return e},setTotal:function(a){e=a},getCurrent:function(){return d},setCurrent:function(a){return j(a-d)}}}; progressBar.combineOptions=function(a,b){var d={};if(a)for(var e in a)a.hasOwnProperty(e)&&(d[e]=a[e]);if(b)for(e in b)b.hasOwnProperty(e)&&void 0===d[e]&&(d[e]=b[e]);return d};"undefined"===typeof String.prototype.toRad&&(Number.prototype.toRad=function(){return this*Math.PI/180});"undefined"===typeof String.prototype.toDeg&&(Number.prototype.toDeg=function(){return 180*this/Math.PI});
function car(){this.carid=0;this.highlight=function(){};this.debug=!1}car.prototype.info=function(){};car.prototype.select=function(){this.selected=!0;this.onselect&&onselect()};car.prototype.unselect=function(){this.selected=!1};function cars(a,b,d,e){this._cars=[];this._raceid=b||null;this._reqUrl=a||null;this.apiKey="";this.type=d||"";this.debug=!1;this._raceid&&this.load("list",e)}cars.prototype.length=function(){return this._cars.length};cars.prototype.setdebug=function(a){this.debug=a}; cars.prototype.getIndex=function(a){if(!a)return null;for(x=0;x<this._cars.length;x++)if(this._cars[x].car_number==a)return x};cars.prototype.getCarByNumber=function(a){if(!a||!this._cars.length)return null;for(x=0;x<this._cars.length;x++)if(this._cars[x].car_number==a)return this._cars[x]};cars.prototype.fetch=function(a){for(x=0;x<this._cars.length;x++)if(this._cars[x].car_number==a)return this._cars[x];if(!a)return this._cars}; cars.prototype.getSelected=function(){var a=[];for(x=0;x<this._cars.length;x++)!0==this._cars[x].selected&&a.push(this._cars[x]);return a};cars.prototype.setSelected=function(a){this.fetch(a).selected=!0};cars.prototype.getHighlightColor=function(){return"something"}; cars.prototype.load=function(a,b){ltype=a||this.type;$.getJSON(this._reqUrl+"?q=cars"+(0<ltype.length?"-"+ltype:"")+(this._raceid?"&rid="+this._raceid:"")+"&d=json&lang=en-us&key="+this.apiKey,function(a,b){return function(f,h){if("success"==h){a._cars=f.cars?f.cars:f["cars_"+ltype];for(var g=null,j=0;j<a._cars.length;j++)g=j,a._cars[j].selected=!1,a._cars[j].markers=[],a._cars[j].lines={},a._cars[j].refreshStageData=function(b,e){return a._refreshStageData(a._cars[g].car_number,b,e)},a._cars[j].getPosition= function(){return a._getPosition(g)},a._cars[j].setRoute=function(b,e){return a._setRoute(g,b,e)},a._cars[j].getRoute=function(b){return a._getRoute(g,b)},a._cars[j].setRouteCoords=function(b,e){return a._setRouteCoords(g,b,e)},a._cars[j].getRouteCoords=function(b){return a._getRouteCoords(g,b)},a._cars[j].stage_data&&(a._cars[j].stagedata=a._cars[j].stage_data.split(","))}else this.debug&&alert("Error in cars.load(): "+h);b&&b()}}(this,b))}; cars.prototype.refresh=function(a,b){0!=this._cars.length&&(cq="cars",refreshCols=["car_status","car_coords_update","car_coordinates","car_coords_desc"],a&&"function"!=typeof a?"list"==a?(cq="cars-list",refreshCols=["car_position","car_drivers_short","dvc_id","car_start_pos"]):"positions"==a?(cq="car-positions",refreshCols=["car_status","car_coords_update","car_coordinates","car_coords_desc"]):"replay-data"==a&&(cq="cars-stage-summary",refreshCols=["stage_data"]):a&&"function"==typeof a&&(b=a),$.getJSON(this._reqUrl+ "?q="+cq+(this._raceid?"&rid="+this._raceid:"")+"&d=json&lang=en-us&key="+this.apiKey,function(d){return function(e,f){if("success"==f){if("undefined"==typeof e.db_error){"list"==a?e.cars=e.cars_list:"positions"==a?e.cars=e.car_positions:"replay-data"==a&&(e.cars=e.cars_stage_sum);for(i=0;i<e.cars.length;i++){carhndl=d._cars[d.getIndex(e.cars[i].car_number)];for(x=0;x<refreshCols.length;x++)coln=refreshCols[x],carhndl[coln]=e.cars[i][coln]}}b&&b()}else alert("cars.refresh Error: "+f)}}(this,b)))}; cars.prototype.loadReplay=function(a,b){$.getJSON(this._reqUrl+"?q=stage-replay&c="+carid+(this._raceid?"&r="+this._raceid:"")+"&s="+b+"&d=json&lang=en-us&key="+this.apiKey,function(a){return function(b,f){"success"==f?(alert("cars.loadReplay DEBUG:"+b.car_stage_data.length),1<=b.car_stage_data.length&&(a._cars.fetch(b.car_stage_data[0].car_number).stage_data=b.car_stage_data)):alert("cars.loadReplay Error:"+f)}}(this))}; cars.prototype._refreshStageData=function(a,b,d){$.getJSON(this._reqUrl+"?q=car-stage-data&c="+a+"&r="+b+(d?"":""+d)+"&d=json&lang=en-us&key="+this.apiKey,function(a){return function(b,d){if("success"==d){noteUpdate("Stage Data for "+scar.car_number+" has "+csd.length+" records.");this.debug&&alert("cars.refreshStageData DEBUG:"+b.car_stage_data.length);1<=b.car_stage_data.length&&(a._cars.fetch(b.car_stage_data[0].car_number).stage_data=b.car_stage_data);var g=0;for(i=x;i<csd.length;i++)try{g=csd[i].stage_id; if(!scar.lines["stage-"+g]&&"dat"==csd[i].dtype.substr(1)&&csd[i].coords){var j=[],k=csd[i].coords.split("\n");for(ci=0;ci<k.length;ci++)j[ci]=new google.maps.LatLng(listGetAt(k[ci].coords,2,","),listGetAt(k[ci].coords,1,","));scar.lines["stage-"+g]=new google.maps.Polyline({path:j,strokeColor:hlcolor,strokeOpacity:0.7,strokeWeight:5});scar.lines["stage-"+g].setMap(a.gmHndl)}alert("Added "+j.length+" point polyline")}catch(r){this.debug&&alert("selectCar (sdat):"+r.message)}}else alert("An error occured loading Car data:"+ d)}}(this))};cars.prototype.loadRoute=function(a,b){return inst._cars[a].lines[b]};cars.prototype.fetchRouteData=function(a,b){return inst._cars[a].lines[b]};cars.prototype.displayRoute=function(a,b,d,e){var f=cars.getRoute(a,b);"object"!=typeof f&&(f=cars.fetchRouteData(a,b));e&&f.setColor(e);f.setMap(d)};cars.prototype.hideRoute=function(a,b){inst._cars[a].lines[b].setMap(null)};cars.prototype._setRoute=function(a,b,d){this._cars[a].lines[b]=d;return!0};cars.prototype._getRoute=function(a,b){return this._cars[a].lines[b]}; cars.prototype._setRouteCoords=function(a,b,d){this._cars[a].lines[b].coords=d;return!0};cars.prototype._getRouteCoords=function(a,b){return this._cars[a].lines[b].coords};cars.prototype._getPosition=function(a){this.debug&&alert("cars._getPosition DEBUG: "+this._cars[a].car_coordinates);return this._cars[a].car_coordinates}; cars.prototype.getList=function(){this.debug&&alert(this._reqUrl+"?q=cars-list"+(this._raceid?"&r="+this._raceid:"")+"&d=json&lang=en-us&key="+this.apiKey);$.getJSON(this._reqUrl+"?q=cars-list"+(this._raceid?"&r="+this._raceid:"")+"&d=json&lang=en-us&key="+this.apiKey,function(){return function(a,b){"success"==b?alert("cars.getList DEBUG:"+a.cars_list.length):alert("cars.getList Error: "+b)}}(this))};
stagetrack.ui={urlEncodeCharacter:function(a){return"%"+a.charCodeAt(0).toString(16)},urlDecodeCharacter:function(a,b){return String.fromCharCode(parseInt(b,16))},anchorToElement:function(a,b,d){var e={left:0,top:0};if("undefined"!=typeof b){var d=d||"top-left",f=$(b).offset(),h=$(b).width(),b=$(b).outerHeight();"top-right"==d?$(a).css({left:f.left-($(a).width()-h)+"px",top:f.top-$(a).height()+"px"}):"top-left"==d?$(a).css({left:f.left+h+"px",top:f.top-$(a).height()+"px"}):"bottom-right"==d?$(a).css({left:f.left- ($(a).width()-h)+"px",top:f.top+b+"px"}):"bottom-left"==d&&$(a).css({left:f.left+"px",top:f.top+b+"px"});e.left=parseInt($(a).css("left"));e.top=parseInt($(a).css("top"))}return e},infup:function(a,b){return String.fromCharCode(parseInt(b,16))},progress:function(){return""},shadow:function(a){alert(typeof $(a));"object"==typeof $(a)&&(elmtHndl=document.getElementById(div),"undefined"==typeof size&&(size="large"),"undefined"==typeof tb&&(tb="both"),sh1=createDOMLayer(document.body,"","","","shadow-one", "padding:1px;background-color:#000000;float:left;"),sh1.appendChild(elmtHndl))}}; stagetrack.ui.popup=function(a){this.content="";this.url="/bin/";this.prebuild=!0;this.content_tag="title";this.maxWidth="default";this.anchorto=null;for(var b in a)this[b]=a[b];this.__rurl=this.$popobj=null;var d=this;b=$(this.anchorto);a.content||(this.content=b.attr(this.content_tag),b.attr(this.content_tag,""));if(this.content)this.content&&"show"==this.content.substr(0,4)&&(this.__rurl=this.url+(this.url.indexOf("?")?"&":"?")+this.content.substr(5),this.content="<div class='loader-lg'><span>Loading....</span></div>"); else return!1;if(this.events)for(var e in events)$(this.anchorto).bind(e,function(){eval("that."+events[e]+"('normal')")});else $(this.anchorto).mouseover(function(){d.show("normal")}),$(this.anchorto).mouseout(function(){d.hide("normal")});this.__fixwidth=function(){if(d.width)b=d.width;else{var a=$("<div></div>").css({left:"-1000px",position:"absolute"}).html(this.content).appendTo("body"),b=a.width();a.remove()}a=this.$popobj.width()-b;a>window.innerWidth&&(a=window.innerWidth-this.$popobj.position().left- 70);this.$popobj.find('[class~="-mid"]').width(a)};this.__build=function(){this.$popobj=$("<div class='popview'><div class='top'><div class='point'></div><div class='top-right'></div><div class='top-left'></div><div class='top-mid'></div></div><div class='clear'></div><div class='content'>"+this.content+"</div><div class='bottom'><div class='bottom-right'></div><div class='bottom-left'></div><div class='bottom-mid'></div></div></div>").hide();this.$fds__=$("body").append(this.$popobj);navigator.userAgent.match(/MSIE ([0-9]{1,}[.0-9]{0,})/)&& ($tr=this.$popobj.find(".top-right"),$trc=$tr.clone().appendTo($tr.parent()),$br=this.$popobj.find(".bottom-right"),$brc=$br.clone().appendTo($br.parent()),$tr.remove(),$br.remove());return this.$popobj};this.prebuild&&this.__build();this.$popobj.mouseover(function(){d.hideout?clearTimeout(d.hideout):d.showout&&clearTimeout(d.showout)});this.$popobj.mouseout(function(){d.hide()});this.hideout=this.showout=null;this.__size=function(){};this.show=function(){d.hideout&&clearTimeout(d.hideout);d.prebuild|| d.__build();var a=stagetrack.ui.anchorToElement(d.$popobj.get(0),d.anchorto,"bottom-left");$.get(this.__rurl,function(a){d.content=a;d.$popobj.find(".content").html(d.content);d.__fixwidth()});d.showout=setTimeout(function(){$tobj=d.$popobj;if(d.onshow)d.onshow();d.width&&$tobj.width(d.width);$tobj.width()+a.left>window.innerWidth-$(window).scrollLeft()&&(offset=window.innerWidth-$(window).scrollLeft()-($tobj.width()+a.left+20),$tobj.css("left",a.left+offset+"px").find(".point").css("margin-left", -1*offset+"px"));d.$popobj.show("normal");d.showout=null},400)};this.hide=function(){d.showout&&clearTimeout(d.showout);d.hideout=setTimeout(function(){if(d.onhide)d.onhide();d.$popobj.hide("normal");d.hideout=null},650)};this.destroy=function(){this.$popobj.remove()};this.get=function(){return this.$popobj}}; stagetrack.ui.gFusionDialog=function(a){this.dname="";this.datasource=null;this.valuecol=0;this.query=this.onsave=null;this.fieldmap={};for(var b in a)this[b]=a[b];this.gfdiagname="ext-fusiondata";this.__url="https://fusiontables.googleusercontent.com/fusiontables/api/query?sql={query}&jsonCallback=?";this.__plnext=!1;this.__psfunc=null;this.pSaveBtn_click=function(a,b){this.__psfunc&&this.__psfunc(a,b);this.__hidepanel()};this.__showpanel=function(a){stagetrack.displayPanel("ext-fusiondata",{onopen:a, width:"auto",norefresh:!0,draggable:!0})};this.__hidepanel=function(){stagetrack.displayPanel("ext-fusiondata")};this.getDatasource=function(){that=this;this.__showpanel(function(a){ftobj=that;$p=$("#ext-fusiondata-grid").html("");$("<p/>").append('<label for="ftid">Fusion Table ID </label>').append('<input type="text" id="ftid" name="ftid" value="'+(ftobj.datasource?parseInt(ftobj.datasource):"")+'" />').append('<div id="status" />').appendTo($p);sav=$('<input type="button" name="save_btn" value=" Load Data ">').click(function(){$p.find("#status").addClass("loader-sm"); ftobj.load($p.find("#ftid").val())});can=$('<input type="button" name="cancel_btn" value="Cancel">').click(ftobj.__hidepanel);$("<div/>").append(sav).append(can).appendTo($p);centerOverlay(a)})};this.load=function(a){!this.query&&!a?this.getDatasource():(a&&(this.query=parseInt(a)==a?"SELECT * FROM "+a:a),that=this,$.getJSON(this.__getUrl(),function(a){$p=$("#ext-fusiondata-grid");$p.find("#status").removeClass("loader-sm");that.datasource=a;that.__hidepanel();that.__plnext&&that.getData()}))};this.hasData= function(){return this.datasource?!0:!1};this.__getUrl=function(){return this.__url.replace(/(\{query\})/,this.query)};this.getData=function(a){a&&(this.__psfunc=a);this.datasource?(ftobj=this,this.__showpanel(function(a){table=ftobj.datasource.table;$p=$("#ext-fusiondata-grid");if($p.size()){$p.html("<p>Select a data point to use from the table </p>");var b=$("<select><option></option></select>");for(x=0;x<table.rows.length;x++)trec=table.rows[x],tr_name=trec[0],tr_desc=trec[1],tr_geo=trec[2],tr_mkr= trec[3],b.append('<option value="'+tr_geo.coordinates.join(",")+'">'+tr_name+" ("+tr_geo.type+")</option>");$fd=$("<div></div>").html("<label>Select Data</label>").append(b);$fd.appendTo($p);sav=$('<input type="button" name="save_btn" value=" Select ">').click(function(){var a=$p.find("option:selected").val();ftobj.pSaveBtn_click(a,$p)});can=$('<input type="button" name="cancel_btn" value="Cancel">').click(ftobj.__hidepanel);$("<div/>").append(sav).append(can).appendTo($p);centerOverlay(a)}else alert("Unable to display Fusion Table data, please try again.")}), this.__plnext=!1):(this.__plnext=!0,this.load())}};
stagetrack.util={urlEncodeCharacter:function(a){return"%"+a.charCodeAt(0).toString(16)},urlDecodeCharacter:function(a,b){return String.fromCharCode(parseInt(b,16))},urlEncode:function(a){return encodeURIComponent(a).replace(/\%20/g,"+").replace(/[!'()*~]/g,stagetrack.util.urlEncodeCharacter)},urlDecode:function(a){return decodeURIComponent(a.replace(/\+/g,"%20")).replace(/\%([0-9a-f]{2})/g,stagetrack.util.urlDecodeCharacter)},toggleDisable:function(a){$(a).is(":disabled")?$(a).removeAttr("disabled"): $(a).attr("disabled","disabled")},distanceFrom:function(a,b){if("object"!=typeof a||"object"!=typeof b)return-1;with(Math){var d=sin(a.lat()/57.2958)*sin(b.lat()/57.2958)+cos(a.lat()/57.2958)*cos(b.lat()/57.2958)*cos(b.lng()/57.2958-a.lng()/57.2958);return stagetrack.earthRadius.MILES*acos(d)}},getLengthFromCoords:function(a){var b=0;units||(units=stagetrack.earthRadius.MILES);for(x=0;x<a.length-1;x++)a.lat||(dist=stagetrack.util.distanceFrom(a[x],a[x+1])),b+=dist;return b},getLocLatLngFromLoc:function(a, b){var d;latlngFromAddress=function(a){try{if(0==a.trim().length)return!1;d=new google.maps.Geocoder;d.geocode({address:a},function(a,d){d==google.maps.GeocoderStatus.OK&&$(b).val(a[0].geometry.location.lat()+","+a[0].geometry.location.lng())})}catch(f){return alert("getLocLatLngFromLoc: Unable to retrieve the Location Latitude/Longitude\n"+f),!1}};!google.maps&&a?$.getJSON("/bin/stmapdata.php",{q:"geocode",addr:a,sensor:"false"},function(a,d){"success"==d&&"OK"==a.status?(results=a.results,$(b).val(results[0].geometry.location.lat+ ","+results[0].geometry.location.lng)):alert("getLocLatLngFromLoc: Unable to retrieve the Location Latitude/Longitude\n"+a.status)}):a&&latlngFromAddress(a)},getRouteCoords:function(a,b,d){this.destination=this.origin=this.gmDirSvc=null;for(var e in b)this[e]=b[e];this._rcoords=[];_inst=this;a.route({origin:this.origin,destination:this.destination,travelMode:google.maps.DirectionsTravelMode.DRIVING},function(a,b){if(b==google.maps.DirectionsStatus.OK){var e=a.routes[0];for(li=0;li<e.legs.length;li++)if(e.legs[li]&& 3>=e.legs[li].steps.length)for(si=0;si<e.legs[li].steps.length;si++)for(pi=1;pi<e.legs[li].steps[si].path.length-1;pi++)_inst._rcoords.push(e.legs[li].steps[si].path[pi]);d&&d(_inst._rcoords)}});return this._rcoords},gradientColor:function(a){this.idxs=[];this.center=128;this.width=127;this.styles={heat:{freq:[0.02,0.02,0.02],phase1:[0,1.5,255]},blue:{freq:[0.02,0.02,0.02],phase1:[2,2,0]},navy:{freq:[0.02,0.02,0],phase1:[2,2,0]}};this.style=styles.heat;for(var b in a)this[b]=a[b];this.__next=this.__last= null;this.__idx=0;this.__arry=[];this.setStyle=function(a){this.style=styles[a]};this.bytetoHex=function(a){return""+"0123456789ABCDEF".substr(a>>4&15,1)+"0123456789ABCDEF".substr(a&15,1)};this.RGB2Color=function(a,b,f){return"#"+this.bytetoHex(a)+this.bytetoHex(b)+this.bytetoHex(f)};this.makeGradColor=function(a){var b=Math.sin(a*this.style.freq[0]+this.style.phase[0])*this.width+this.center,f=Math.sin(a*this.style.freq[1]+this.style.phase[1])*this.width+this.center,a=Math.sin(a*this.style.freq[2]+ this.style.phase[2])*this.width+this.center;return this.RGB2Color(b,f,a)};this.__buildall=function(){this.__idx=0;if(this.idxs.length)for(var a=0;a<this.idxs.length;a++)this.__arry.push(this.makeGradColor(this.idxs[a]))};this.getNextColor=function(){return this.__arry.length==this.fds?this.__arry[++this.__idx]:""};this.__buildall()},xml2Json:function(a){var b={};if(1==a.nodeType){if(0<a.attributes.length){b["@attributes"]={};for(var d=0;d<a.attributes.length;d++)b["@attributes"][a.attributes[d].nodeName]= a.attributes[d].nodeValue}}else 3==a.nodeType&&(b=a.nodeValue);if(a.hasChildNodes())for(d=0;d<a.childNodes.length;d++)if("undefined"==typeof b[a.childNodes[d].nodeName])b[a.childNodes[d].nodeName]=xml2Json(a.childNodes[d]);else{if("undefined"==typeof b[a.childNodes[d].nodeName].length){var e=b[a.childNodes[d].nodeName];b[a.childNodes[d].nodeName]=[];b[a.childNodes[d].nodeName].push(e)}b[a.childNodes[d].nodeName].push(xml2Json(a.childNodes[d]))}return b}};

