function Realtime(map,map_info){this.engine=new RealtimeEngine();this.georss_client=new GeoRSSClient(map,this.engine,map_info);this.renderer=new RealtimeRenderer(map,this.engine);this.start=function(){this.engine.start();this.georss_client.start();this.renderer.start();}
this.startShowcase=function(){this.renderer.showcase=true;this.renderer.startShowcase();}
this.toggleDisplayFilter=function(type){this.renderer.toggleDisplayFilter(type);}}
function GeoRSSClient(map,realtimeEngine,map_info){this.map=map;this.map_info=map_info;this.realtimeEngine=realtimeEngine;this.INTERVAL=60000;this.server_url='/rtserver/web/GeoRSS';this.base_params={};this.move_event_timeout=null;this.MOVE_EVENT_UPDATE_DELAY=5000;this.start=function(){this.updateFromServer()();window.setInterval(this.updateFromServer(true),this.INTERVAL);this.map.events.register("moveend",this,function(evt){window.clearTimeout(this.move_event_timeout);var gc=this;this.move_event_timeout=window.setTimeout(function(){gc.updateFromServer(false)();},this.MOVE_EVENT_UPDATE_DELAY);});};this.updateFromServer=function(on_interval){var grclient=this;var f=function(){$.getJSON(url=grclient.server_url,data=grclient._getURLParams(on_interval),callback=function(json){var output=GeoRSSParser.parse(json,data.sf);var newEntities=output.entities;grclient.realtimeEngine.entities=grclient._mergeEntities(grclient.realtimeEngine.entities,newEntities);grclient.realtimeEngine.aux_data=output.aux_data;});}
return f;};this._mergeEntities=function(oldEntities,newEntites){var bounds=null;if(this.map_info.base_layer_type=="OSM"){bounds=new OpenLayers.Bounds();bounds.left=20037508;bounds.bottom=-19929239;bounds.right=20037508;bounds.top=19929239;}
else
bounds=this.map.maxExtent;for(var id in oldEntities){var old=oldEntities[id];if(!old||old.type!="user")
delete oldEntities[id];}
for(var id in newEntites){if(!bounds.contains(newEntites[id].location.x,newEntites[id].location.y))
continue;var old=oldEntities[id];if(!old)
continue;var new_entity=newEntites[id];new_entity.location.x=old.location.x;new_entity.location.y=old.location.y;new_entity.time=old.time;new_entity.delta_x=old.delta_x;new_entity.delta_y=old.delta_y;new_entity.phantom=old.phantom;if(new_entity.phantom)
new_entity.wait=old.wait;if(!old.path||old.path.length==0)
continue;var cut_point=0;var lastTime=old.path[old.path.length-1].time;for(vertex in new_entity.path){var next=new_entity.path[vertex];if(next.time<=lastTime)
cut_point++;}
new_entity.path.splice(0,cut_point);new_entity.path=old.path.concat(new_entity.path);}
return newEntites;};this._getExtent=function(){var extent=null;if(this.map.baseLayer&&this.map.baseLayer.getTilesBounds)
extent=this.map.baseLayer.getTilesBounds();else
extent=this.map.getExtent();return extent;}
this._getURLParams=function(on_interval){var extent=this._getExtent();var params={os:60,left:extent.left,right:extent.right,bottom:extent.bottom,top:extent.top,format:'JSON',ma:200,mu:10,sc:parseInt(this.map.getScale()),types:"alerts,users"}
if(this.map_info.base_layer_type=="OSM")
params["pr"]="Mercator";for(var i in this.base_params){if(i=="sf"&&this.base_params[i]!="false")
if(params.mu)
delete params.mu;params[i]=this.base_params[i];}
if(this.realtimeEngine.aux_data)
if(on_interval&&this.realtimeEngine.aux_data.next)
params.st=this.realtimeEngine.aux_data.next_str;else if(!on_interval&&this.realtimeEngine.aux_data.now)
params.st=this.realtimeEngine.aux_data.now_str;return params;}}
var GeoRSSParser={mood_map:{0:"happy",1:"happy",2:"sad",3:"mad",4:"bored",5:"speedy",6:"starving",7:"sleepy",8:"cool",9:"inlove",10:"lol",11:"peacful",12:"singing",13:"wondering",14:"happy_female",15:"sad_female",16:"mad_female",17:"bored_female",18:"speedy_female",19:"starving_female",20:"sleepy_female",21:"cool_female",22:"inlove_female",23:"lol_female",24:"peaceful_female",25:"singing_female",26:"wondering_female",27:"bronze",28:"silver",29:"gold",30:"busy",31:"busy_Female",32:"in_a_Hurry",33:"in_a_Hurry_Female"},parseDate:function(s){var arr=s.split(/[\-\s\:]/);var year=parseInt(arr[0]);var month=parseInt(arr[1])-1;var day=parseInt(arr[2]);var hour=parseInt(arr[3]);var minute=parseInt(arr[4]);var second=parseInt(arr[5]);var ms=parseInt(arr[6]);;var d=new Date(year,month,day,hour,minute,second,ms);return d.getTime();},parse:function(json,ignore_zoom){var entities={};var aux_data={}
aux_data.now=new Date(json.startTimeMillis);aux_data.now_str=json.startTime;aux_data.next_str=json.endTime;var thisParser=this;var alerts=[];if(json.alerts&&typeof(json.alerts.length)!="undefined")
alerts=json.alerts;else
if(json.alerts)
alerts.push(json.alerts);var provider=extractParam("provider");$.each(alerts,function(){if(provider.length>0&&this.provider!=provider){return;}
var next=thisParser.parseEntity(this);entities[next.id]=next;});if(g_map&&g_map.zoom>4&&!ignore_zoom)
return{entities:entities,aux_data:aux_data};var users=[];if(json.users&&typeof(json.users.length)!="undefined")
users=json.users;else
if(json.users)
users.push(json.users);$.each(users,function(){var next=thisParser.parseUser(this);entities[next.id]=next;});return{entities:entities,aux_data:aux_data};},parseEntity:function(entity){entity.reportBy=entity.reportBy?entity.reportBy:"";if(entity.pubMillis)
entity.creation_date=new Date(entity.pubMillis);entity.reportDescription=entity.reportDescription?entity.reportDescription:"";entity.comments=entity.comments?entity.comments:[];entity.reportMood=this.mood_map[entity.reportMood]?this.mood_map[entity.reportMood]:"happy";if(entity.comments.length==0)
return entity;$.each(entity.comments,function(){this.creation_date=new Date(this.reportMillis);});return entity;},parseUser:function(entity){var entity=this.parseEntity(entity);mood_map=this.mood_map;fleet_map={"dw":"speedy_female","gpsi":"starving_female","webtech":"sleepy_female","telogis":"cool_female","actsoft":"inlove_female","navtrak":"lol_female","fleetmatics":"peaceful_female","trimble":"singing_female","network":"wondering_female","pointer":"happy","monitex":"happy"}
entity.delta_x=0;entity.delta_y=0;entity.time=0;entity.phantom=false;entity.server_error=false;entity.type="user";entity.mood=mood_map[entity.mood]?mood_map[entity.mood]:"happy";if(entity.fleet&&entity.fleet!="none")
entity.mood=fleet_map[entity.fleet];entity.path=[];var gps_path=entity.gpstrack;if(!gps_path||gps_path.length==0)
return entity;var lastTime=0;$.each(gps_path,function(){if(this.t>=lastTime){var next={};next["time"]=this.t;next["angle"]=this.a;next["speed"]=this.s;next["x"]=this.x;next["y"]=this.y;entity.path.push(next);lastTime=next.time;}
else
entity.server_error=true;});var mod=entity.path[0].time%60000;if(mod>0){entity.phantom=true;entity.wait=mod;}
entity.location.x=entity.path[0].x;entity.location.y=entity.path[0].y;entity.time=entity.path[0].time;return entity;}}
function RealtimeEngine(){this.entities={};this.INTERVAL=100.0;this.start=function(){window.setInterval(this._realtimeStep(),this.INTERVAL);};this._realtimeStep=function(){var rt=this;f=function(){for(var id in rt.entities){rt._updateEntity(rt.entities[id]);}}
return f;};this._updateEntity=function(entity){if(entity.type!="user")
return;if(entity.phantom){if(entity.wait>0)
entity.wait-=this.INTERVAL;if(entity.wait<=0)
entity.phantom=false;return;}
var path=entity.path;if(path.length<2)
return;if(entity.time>=path[0].time||entity.time>=path[1].time){while(path.length>1&&entity.time>=path[1].time)
path.shift();if(path.length<2)
return;entity.delta_x=((path[1].x-path[0].x)/(path[1].time-path[0].time))*this.INTERVAL;entity.delta_y=((path[1].y-path[0].y)/(path[1].time-path[0].time))*this.INTERVAL;}
entity.location.x+=entity.delta_x;entity.location.y+=entity.delta_y;entity.time+=this.INTERVAL;};}
var g_strings=$("#strings");var getStr=function(string_id){return $("#"+string_id,g_strings).text();}
var formatTime=function(time_in_minutes){if(time_in_minutes<60)
return time_in_minutes;var time_in_hours=(time_in_minutes/60);prec=time_in_hours.toFixed(1);if(prec==Math.floor(prec))
return Math.floor(prec);else
return prec;}
function extend(father,son){var from_proto=father.prototype;var to_proto=son.prototype;for(m in from_proto){if(typeof from_proto[m]!='function')
continue;to_proto[m]=from_proto[m];}
son.prototype.superClass=father;}
function CssCache(){this.map={};}
CssCache.prototype.get=function(element,property){var map=this.map;var key=element.id+'-'+property;if(map[key])
return map[key];var str=this.getNotCached(element,property);map[key]=str;return map[key];}
CssCache.prototype.getNotCached=function(element,property){var str='';if(element['style']&&element.style[property])
str=element.style[property];else
str=$(element).css(property);return str;}
CssCache.prototype.getNotCachedInt=function(element,property){return parseInt(this.getNotCached(element,property).replace('px',''));}
CssCache.prototype.getAsInt=function(element,property){return parseInt(this.get(element,property).replace('px',''));}
CssCache.prototype.getWidth=function(element){var map=this.map;var key=element.id+'-jquery-width';if(map[key])
return map[key];var str=$(element).width();map[key]=str;return map[key];}
function Avatar(container,entity_id,cssClass,entity_provider){this.cache=new CssCache();this.entity_id=entity_id;this.entity={};this.container=container;this.cssClass=cssClass;this.entity_provider=entity_provider;this.tooltipElement=null;this.element=this._createElement();}
Avatar.prototype.panTooltipIntoView=function(left,top,width,height){if(!g_map)
return;var tt=this.tooltipElement;var mapSize=g_map.getSize();var origTL=g_map.getViewPortPxFromLayerPx(new OpenLayers.Pixel(x=left,y=top));var newTL=origTL.clone();if(origTL.x<g_map.paddingForPopups.left){newTL.x=g_map.paddingForPopups.left;}else
if((origTL.x+width)>(mapSize.w-g_map.paddingForPopups.right)){newTL.x=mapSize.w-g_map.paddingForPopups.right-width;}
if(origTL.y<g_map.paddingForPopups.top){newTL.y=g_map.paddingForPopups.top;}else
if((origTL.y+height)>(mapSize.h-g_map.paddingForPopups.bottom)){newTL.y=mapSize.h-g_map.paddingForPopups.bottom-height;}
var dx=origTL.x-newTL.x;var dy=origTL.y-newTL.y;g_map.pan(dx,dy);}
Avatar.prototype.update=function(now,entity){this.entity=entity;this.entity.inscale=false;this.now=new Date(now);}
Avatar.prototype.destroy=function(){if(this.tooltipElement){$(this.tooltipElement).unbind();this.container.removeChild(this.tooltipElement);}
$(this.element).unbind();this.container.removeChild(this.element);}
Avatar.prototype._createTooltipElement=function(mold_id){var avatar=this;var tt=document.createElement('div');tt.id=this.entity_id+"_tooltip";$(tt).css("zIndex","751");$(tt).addClass('tooltip');this._setOpacity(tt,0.9);if(mold_id)
$(tt).html($(mold_id).html());else
$(tt).html($("#report_mold").html());$(".user_details",tt).show();$(".title",tt).text($("#"+this.entity.type+" .title").text());if(this.entity.comments&&this.entity.comments.length>1)
$(".comments_counter a.toggle_view",tt).show();$(".comments_counter a.toggle_view",tt).click(function(e){$(".comments .comment:gt(0)",tt).slideToggle("fast");if($(this).text()==">>"){$(this).text("<<");$(tt).css("zIndex","753");}
else{$(this).text(">>");$(tt).css("zIndex","751");}
return false;});$(tt).hover(over=function(){this.is_over=true;},out=function(){if(avatar.entity.inscale||!avatar.tooltipElement)
return;$(avatar.element).css("zIndex","750");avatar.container.removeChild(avatar.tooltipElement);avatar.tooltipElement=null;return true;});if(this.entity.imageId!=null&&this.entity.imageId.length>0){$(".photo_wrapper",tt).html("<a class='photo'><a>");$('.photo',tt).attr("href","http://waze.photos.s3.amazonaws.com/"+this.entity.imageId);$('.photo ',tt).css("background-image","url(http://waze.photos.s3.amazonaws.com/thumbs/thumb100_"+this.entity.imageId+")");$('.photo ',tt).attr("title",this.entity.reportDescription);$(".photo_wrapper",tt).show();var direction=$("body").css("direction");$('.photo',tt).colorbox({photo:true});}
this.container.appendChild(tt);return tt;}
Avatar.prototype._createElement=function(){var avatar=this;var container=this.container;var e=document.createElement('div');e.id=this.entity_id;var tt_id=this.entity_id+'_tooltip';$(e).addClass(this.cssClass);if(this.entity_provider&&this.entity_provider=="Twitter")
{$(e).html("<div class='fromTwitter'></div>");}
$(e).hover(over=function(){if(avatar.entity.inscale)
return;$(".tooltip:not(.user-tooltip)").hide();if(!avatar.tooltipElement)
avatar.tooltipElement=avatar._createTooltipElement();avatar.updateTooltipContents();avatar._renderTooltip();},out=function(){if(avatar.entity.inscale||!avatar.tooltipElement)
return;window.setTimeout(function(){if(!avatar.tooltipElement)
return;if(avatar.tooltipElement&&!avatar.tooltipElement.is_over){$(avatar.element).css("zIndex","750");avatar.container.removeChild(avatar.tooltipElement);avatar.tooltipElement=null;}},500);return true;});$(e).click(function(){if(typeof createPingAwazer=="function")
createPingAwazer(avatar.entity);return false;});$(e).dblclick(function(){return false;});$(e).css("zIndex","750");this.container.appendChild(e);return e;}
Avatar.prototype._setPosition=function(x,y){var old_left=this.element.style.left;var old_top=this.element.style.top;this.element.style.left=(x-13)+"px";this.element.style.top=(y-this.element.clientHeight)+"px";}
Avatar.prototype.render=function(map){if(this.entity.imageId!=null&&this.entity.imageId.length>0&&$(".attachment",this.element).length==0)
$(this.element).append($("<div class='attachment'></div>"));var lonlat=new OpenLayers.LonLat(lon=this.entity.location.x,lat=this.entity.location.y);var pixel=map.getLayerPxFromLonLat(lonlat);this._setPosition(pixel.x,pixel.y);if(this.entity.inscale)
this._renderTooltip();}
Avatar.prototype._renderTooltip=function(map){if(this.tooltipElement==null){this.tooltipElement=this._createTooltipElement();this.updateTooltipContents();}
var e=this.element;$(e).css("zIndex","752");var tt=this.tooltipElement;var e_left=this.cache.getNotCachedInt(e,'left');var e_top=this.cache.getNotCachedInt(e,'top');var width=$(tt).outerWidth();var height=$(tt).outerHeight()
var left=e_left-(width-$(e).outerWidth())/2;var top=e_top-height+10;tt.style.left=left+'px';tt.style.top=top+'px';this.panTooltipIntoView(left,top,width,height);}
Avatar.prototype.updateTooltipContents=function(){var tt=this.tooltipElement;if(!tt)
return;var millisecs_ago=this.now.getTime()-this.entity.creation_date.getTime();var minutes_ago=Math.ceil(millisecs_ago/(1000*60))+2;if(this.entity.reportBy.length>0){if($('.user_details .name',tt).text()!=this.entity.reportBy)
$('.user_details .name',tt).text(this.entity.reportBy);}
if($('.report .description',tt).text()!=this.entity.reportDescription&&this.entity.reportDescription.length>0)
$('.report .description',tt).text(this.entity.reportDescription);if(parseInt($('.last_updated .number',tt).text().replace(/[^0-9]/g,""))!=minutes_ago)
$('.last_updated .number',tt).text(minutes_ago);if(this.entity.reportMood)
$(".user_details",tt).addClass(this.entity.reportMood+"_small");if(!this.entity.comments)
return;var comments_num=0;$.each(this.entity.comments,function(){if(this.text)
comments_num++;});var prev_num_comments=$(".comment",tt).length;if(comments_num==prev_num_comments)
return;$.each(this.entity.comments,function(){if(this.text)
{var comment=$("<div class='comment'></div>");$(comment).html($("#comment_mold").html());$(".comments",tt).append(comment);$(".name",comment).text(this.reportBy);$(".description",comment).text('\"'+this.text+'\"');}});if(prev_num_comments<2)
$(".comments .comment:gt(0)",tt).hide();$(".comments_counter .number",tt).text(comments_num);$(".comments_counter",tt).show();$(".comments",tt).show();}
Avatar.prototype._setOpacity=function(obj,value){obj.style.opacity=value;obj.style.filter='alpha(opacity='+value*100+')';}
function Policeman(container,entity,entity_provider){this.superClass(container,entity,'policeman',entity_provider);}
extend(Avatar,Policeman);function Accident(container,entity,entity_provider){this.superClass(container,entity,'accident',entity_provider);}
extend(Avatar,Accident);function Hazard(container,entity,entity_provider){this.superClass(container,entity,'hazard',entity_provider);}
extend(Avatar,Hazard);function Construction(container,entity,entity_provider){this.superClass(container,entity,'construction',entity_provider);}
extend(Avatar,Construction);function Misc(container,entity,entity_provider){this.superClass(container,entity,'misc',entity_provider);}
extend(Avatar,Misc);function TrafficJam(container,entity,entity_provider){this.superClass(container,entity,'trafficjam',entity_provider);}
extend(Avatar,TrafficJam);function Other(container,entity,entity_provider){this.superClass(container,entity,'other',entity_provider);$(this.tooltipElement).addClass('other-tooltip');}
extend(Avatar,Other);function User(container,entity_id,entity_provider){this.superClass(container,entity_id,'user',entity_provider);}
extend(Avatar,User);User.prototype._createTooltipElement=function(){var tt=this.superClass.prototype._createTooltipElement.apply(this,["#user_tooltip_mold"]);$(tt).addClass('user_tooltip');return tt;}
User.prototype.update=function(now,entity){this.superClass.prototype.update.apply(this,[now,entity]);this.entity.inscale=entity.inscale;}
User.prototype.render=function(map){var user=this.entity;var e=this.element;if(user.time==0||user.phantom){$(e).hide();return;}
$(e).show();var id=user.id;var lonlat=new OpenLayers.LonLat(lon=user.location.x,lat=user.location.y);var pixel=map.getLayerPxFromLonLat(lonlat);this._setPosition(pixel.x,pixel.y);if(user.inscale||this.tooltipElement)
this._renderTooltip();var imageClass=user.mood;if(!$(e).hasClass(imageClass)){$(e).removeClass();$(e).addClass('user');$(e).addClass(imageClass);if(user.mood!=0&&user.ping==1){if(user.addon==0)
$(e).html("<div class='pingable'></div>");else if(user.addon==1)
$(e).html("<div class='crown_pingable'></div>");else if(user.addon==2)
$(e).html("<div class='sword_pingable'></div>");else if(user.addon==3)
$(e).html("<div class='shield_pingable'></div>");}else{if(user.addon==1)
$(e).html("<div class='crown'></div>");else if(user.addon==2)
$(e).html("<div class='sword'></div>");else if(user.addon==3)
$(e).html("<div class='shield'></div>");}}}
User.prototype.updateTooltipContents=function(){var tt=this.tooltipElement;if(!tt)
return;var user=this.entity;if(user.userName.length>0&&user.userName!="guest"&&$('.user_details .name',tt).text()!=user.userName)
$('.user_details .name',tt).text(user.userName);var speed_in_meters_per_sec=0;if(user.path&&user.path.length>1)
speed_in_meters_per_sec=user.path[0].speed;var speed=0;var measurement_system=$(".measurement_system").text();if(measurement_system=="metric")
{speed=Math.round(speed_in_meters_per_sec*3.6);if(speed>90)speed=90;}
else
{speed=Math.round(speed_in_meters_per_sec*(3600/1609.344));if(speed>55)speed=55;}
$(".speed .number",tt).text(speed);$(".speed .unit",tt).text($("."+measurement_system+"_speed").text());$(".speed",tt).show();}
User.prototype._formatTime=function(date){function _zeroComplement(integer,len){str=integer.toString();while(str.length<len)
str='0'+str;return str;}
return _zeroComplement(date.getHours(),2)+":"+_zeroComplement(date.getMinutes(),2);}
function RealtimeRenderer(map,realtimeEngine){this.map=map;this.type_filter_map={};this.realtimeEngine=realtimeEngine;this.RENDER_INTERVAL=1000;this.UPDATE_TOOLTIP_CONTENTS_INTERVAL=60000;this.SHOWCASE_USER_INTERVAL=20000;this.SHOWCASE_ALERT_INTERVAL=15000;this.SHOWCASE_ZOOM=8;this.avatars={};this.start=function(){window.setInterval(this._render(),this.RENDER_INTERVAL);window.setInterval(this._updateTooltipsContents(),this.UPDATE_TOOLTIP_CONTENTS_INTERVAL);};this.startShowcase=function(){this._showcaseNext()();};this._showcaseNext=function(){var renderer=this;var f=function(){var entities_arr=[];for(var id in renderer.realtimeEngine.entities)
entities_arr.push(renderer.realtimeEngine.entities[id]);if(entities_arr.length>0){var index=Math.floor(Math.random()*entities_arr.length);var selected=entities_arr[index];renderer.map.setCenter(new OpenLayers.LonLat(lon=selected.location.x,lat=selected.location.y),renderer.SHOWCASE_ZOOM);var interval=(selected.type=='user'?renderer.SHOWCASE_USER_INTERVAL:renderer.SHOWCASE_ALERT_INTERVAL);for(var next in renderer.avatars){if(!next.tooltipElement)
continue;next.container.removeChild(avatar.tooltipElement);next.tooltipElement=null;}
var avatar=renderer.avatars[selected.id];if(avatar){avatar._renderTooltip();}}
window.setTimeout(renderer._showcaseNext(),interval);}
return f;};this._makeAvatar=function(entity){switch(entity.type){case"user":return new User(this.map.layerContainerDiv,entity.id,entity.provider);break;case"POLICEMAN":return new Policeman(this.map.layerContainerDiv,entity.id,entity.provider);break;case"ACCIDENT":return new Accident(this.map.layerContainerDiv,entity.id,entity.provider);break;case"JAM":return new TrafficJam(this.map.layerContainerDiv,entity.id,entity.provider);break;case"OTHER":return new Other(this.map.layerContainerDiv,entity.id,entity.provider);break;case"MISC":return new Misc(this.map.layerContainerDiv,entity.id,entity.provider);break;case"WEATHERHAZARD":return new Hazard(this.map.layerContainerDiv,entity.id,entity.provider);break;case"CONSTRUCTION":return new Construction(this.map.layerContainerDiv,entity.id,entity.provider);break;default:return null;}}
this.toggleDisplayFilter=function(types){for(var i in types){var type=types[i];if(!this.type_filter_map[type])
this.type_filter_map[type]=true;else
this.type_filter_map[type]=false;}}
this.setFilter=function(type_filter_map){this.type_filter_map=type_filter_map;}
this.filterEntities=function(entities){var filteredEntities={};for(var id in entities)
if(!this.type_filter_map[entities[id].type])
filteredEntities[id]=entities[id];return filteredEntities;}
this._recalibrate=function(){var filtered=this.filterEntities(this.realtimeEngine.entities);for(var id in filtered)
if(!this.avatars[id]){var avatar=this._makeAvatar(filtered[id]);if(avatar)
this.avatars[id]=avatar;}
var removeList=[];for(var id in this.avatars)
if(!filtered[id])
removeList.push(id);for(var i=0;i<removeList.length;i++){var nextId=removeList[i];this.avatars[nextId].destroy();delete this.avatars[nextId];}}
this._render=function(){var renderer=this;f=function(){renderer._recalibrate();if(renderer.realtimeEngine.aux_data)
renderer.now=renderer.realtimeEngine.aux_data.now;var filtered=renderer.filterEntities(renderer.realtimeEngine.entities);for(var id in filtered){var next=renderer.avatars[id]
if(next){next.update(renderer.now,filtered[id]);if(renderer.showcase)
next.entity.inscale=filtered[id].inscale;next.render(renderer.map);}}}
return f;};this._updateTooltipsContents=function(){var renderer=this;f=function(){var filtered=renderer.filterEntities(renderer.realtimeEngine.entities);for(var id in filtered){var next=renderer.avatars[id]
if(next)
next.updateTooltipContents();}}
return f;};}
var g_show_alerts=true;var g_show_light_traffic=true;OpenLayers.Layer.TrafficLayer=OpenLayers.Class(OpenLayers.Layer.Vector,{mood_map:{0:"happy",1:"happy",2:"sad",3:"mad",4:"bored",5:"speedy",6:"starving",7:"sleepy",8:"cool",9:"inlove",10:"lol",11:"peacful",12:"singing",13:"wondering",14:"happy_female",15:"sad_female",16:"mad_female",17:"bored_female",18:"speedy_female",19:"starving_female",20:"sleepy_female",21:"cool_female",22:"inlove_female",23:"lol_female",24:"peaceful_female",25:"singing_female",26:"wondering_female",27:"bronze",28:"silver",29:"gold",30:"busy",31:"busy_Female",32:"in_a_Hurry",33:"in_a_Hurry_Female"},initialize:function(name,map_info,options){OpenLayers.Layer.Vector.prototype.initialize.apply(this,arguments);this.INTERVAL=2*60000;this.SERVER_URL='/rtserver/web/GeoRSS';this.MOVE_EVENT_UPDATE_DELAY=3000;this.CHECK_INIT_MAP_INTERVAL=3000;this.map_info=map_info;var tl=this;this.init_map_interval=window.setInterval(function(){if(!tl.map||!tl.map.getExtent())
return;window.clearInterval(tl.init_map_interval);tl.map.events.register("moveend",tl,function(evt){window.clearTimeout(this.move_event_timeout);this.move_event_timeout=window.setTimeout(function(){tl._getUpdateTraffic()();},this.MOVE_EVENT_UPDATE_DELAY);});tl._getUpdateTraffic()();window.setInterval(tl._getUpdateTraffic(),tl.INTERVAL);},this.CHECK_INIT_MAP_INTERVAL);},addReportToTicker:function(report){var report_li=$("<li style='white-space:normal;'></li>");$(".marquee_wrapper ul").append(report_li);$(report_li).html($("#report_mold").html());var congestion_title="";switch(report.level){case 0:congestion_title=$("#light_traffic").text();break;case 1:congestion_title=$("#light_traffic").text();break;case 2:congestion_title=$("#moderate_traffic").text();break;case 3:congestion_title=$("#heavy_traffic").text();break;case 4:congestion_title=$("#complete_standstill").text();break;}
$(".title",report_li).text(congestion_title);$(".icon",report_li).addClass("traffic_icon");if(report.from.length>0)
if(report.from==report.to)
$(".description",report_li).text($("#congestion_on_around").text().replace(/xxx/,report.street).replace(/xxx/,report.from));else
$(".description",report_li).text($("#congestion_from_to_on").text().replace(/xxx/,report.from).replace(/xxx/,report.to).replace(/xxx/,report.street));else
if(report.street==report.city)
$(".description",report_li).text($("#congestion_on").text().replace(/xxx/,report.city));else
$(".description",report_li).text($("#congestion_on_in").text().replace(/xxx/,report.street).replace(/xxx/,report.city));var map=this.map;$("a",report_li).attr("href","#").click(function(){map.panTo(report.center);return false;});$(".duration .number",report_li).text(report.duration);$(".duration",report_li).show();$(".speed .number",report_li).text(report.speed);$(".speed",report_li).show();var measurement_system=$(".measurement_system").text();$(".speed .unit",report_li).text($("."+measurement_system+"_speed").text());$(".last_updated .number",report_li).text(report.last_updated);},addEmptyReportToTicker:function(){if($("#reports").length==0)
return;var report_li=document.createElement("li");$("#reports").append(report_li);$(report_li).html(this.prepareMold(".live_reports .traffic_empty"));},_getUpdateTraffic:function(){var tl=this;return function(){var onTrafficUpdate=function(json){tl.removeFeatures(tl.features);for(i in tl.features)
tl.features[i].destroy();var new_features=[];$(".marquee_wrapper li").remove();var jams=null;if(!json.jams)
json.jams=[];if(!(json.jams instanceof Array)){jams=[];jams.unshift(json.jams);}
else
jams=json.jams;jams.sort(function(a,b){if(a.severity>b.severity)
return-1;if(a.severity<b.severity)
return 1;return 0;});$(jams).each(function(){var geometry=new OpenLayers.Geometry.LineString();for(var i in this.line)
geometry.addPoint(new OpenLayers.Geometry.Point(x=this.line[i].x,y=this.line[i].y));var vec=new OpenLayers.Feature.Vector(geometry=geometry);new_features.push(vec);vec.description={};vec.description.center=geometry.getBounds().getCenterLonLat();vec.description.from=this.startNode?this.startNode:"";vec.description.to=this.endNode?this.endNode:"";vec.description.street=this.street;vec.description.city=this.city;vec.description.level=this.level;vec.description.severity=this.severity;var measurement_system=$(".measurement_system").text();if(measurement_system=="metric")
vec.description.speed=Math.round(this.speed*3.6);else
vec.description.speed=Math.round(this.speed*(3600/1609.344));var now=new Date();var last_updated_time=new Date(this.updateMillis);var last_updated_minutes_ago=Math.round((now.getTime()-last_updated_time.getTime())/(1000*60));vec.description.last_updated=last_updated_minutes_ago>=0?last_updated_minutes_ago:0;vec.description.duration=(this.speed=="NaN")?5+Math.round((Math.random()*2)):parseInt((this.length/this.speed)/60);var color=null;if(!g_show_light_traffic&&(vec.description.level==0||vec.description.level==1))
return;switch(vec.description.level){case 0:color="#ffea00";break;case 1:color="#ffea00";break;case 2:color="#ff7200";break;case 3:color="#db0707";break;case 4:color="#000000";break;}
var opacity=0.6;var divisor=tl.map.zoom<4?1:tl.map.numZoomLevels/(tl.map.zoom+1);vec.style={strokeWidth:Math.round(7.0/divisor),strokeColor:color,strokeOpacity:opacity};tl.addReportToTicker(vec.description);});tl.addFeatures(new_features);var alerts=null;if(!json.alerts)
json.alerts=[];if(!(json.alerts instanceof Array)){alerts=[];alerts.unshift(json.alerts);}
else
alerts=json.alerts;$(alerts).each(function(){var report_li=$("<li style='white-space:normal;'></li>");$(".marquee_wrapper ul").append(report_li);$(report_li).html($("#report_mold").html());$(".icon",report_li).addClass($("#"+this.type+" .icon_class").text());$(".title",report_li).text($("#"+this.type+" .title").text());if(this.reportDescription)
$(".description",report_li).text(this.reportDescription);if(this.street)
if(this.city)
$(".description",report_li).append($("#congestion_on_in").text().replace(/xxx/,this.street).replace(/xxx/,this.city));else
$(".description",report_li).append($("#congestion_on_around").text().replace(/xxx/,this.street).replace(/xxx/,this.nearBy));if(tl.map.getProjection()=="EPSG:900913"){var lonlat=new OpenLayers.LonLat(lon=this.location.x,lat=this.location.y);lonlat.transform(tl.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));$(".report",report_li).attr("href","/livemap/?zoom=6&lon="+lonlat.lon+"&lat="+lonlat.lat);}
else
$(".report",report_li).attr("href","/livemap/?zoom=6&lon="+this.location.x+"&lat="+this.location.y);var millisecs_ago=(new Date()).getTime()-this.pubMillis;var minutes_ago=Math.ceil(millisecs_ago/(1000*60))+2;$(".last_updated .number",report_li).text(minutes_ago);if(this.reportBy)
$(".user_details .name",report_li).text(this.reportBy);var mood=tl.mood_map[this.mood];if(!mood)
$(".user_details",report_li).addClass(mood+"_small");$(".user_details",report_li).show();if(this.imageId!=null&&this.imageId.length>0){$('.photo_wrapper',report_li).html("<a class='photo'></a>");$('.photo',report_li).attr("href","http://waze.photos.s3.amazonaws.com/"+this.imageId);$('.photo ',report_li).css("background-image","url(http://waze.photos.s3.amazonaws.com/thumbs/thumb100_"+this.imageId+")");if(this.reportDescription)
$('.photo ',report_li).attr("title",this.reportDescription);$('.photo_wrapper',report_li).show();var direction=$("body").css("direction");$('.photo',report_li).colorbox({photo:true});}});if(alerts.length==0&&new_features.length==0){tl.addEmptyReportToTicker();}}
$(".marquee_wrapper ul").empty()
var extent=tl.map.getExtent().clone();var params={"format":"JSON","types":g_show_alerts?"traffic,alerts":"traffic",mj:10,ma:10,jmds:120,jmu:1,left:extent.left,right:extent.right,bottom:extent.bottom,top:extent.top,sc:parseInt(tl.map.getScale())};if(tl.map_info.base_layer_type=="OSM")
params["pr"]="Mercator";$.getJSON(url=tl.SERVER_URL,data=params,callback=onTrafficUpdate);}}});
OpenLayers.Control.TrafficControl=OpenLayers.Class(OpenLayers.Control.SelectFeature,{hover:true,box:false,clickout:false,multiple:false,initialize:function(layers,options){OpenLayers.Control.SelectFeature.prototype.initialize.apply(this,[layers,options]);},prepareMold:function(mold_expr){var mold=$(mold_expr).html();return mold.split("xxx ").join("<span></span>&nbsp;").split("xxx").join("<span></span>");},insertDescriptionText:function(content_div,report){$(content_div).html($("#report_mold").html());var congestion_title="";switch(report.level){case 0:congestion_title=$("#light_traffic").text();break;case 1:congestion_title=$("#light_traffic").text();break;case 2:congestion_title=$("#moderate_traffic").text();break;case 3:congestion_title=$("#heavy_traffic").text();break;case 4:congestion_title=$("#complete_standstill").text();break;}
$(".title",content_div).text(congestion_title);$(".photo_wrapper",content_div).remove();$(".icon",content_div).addClass("traffic_icon");if(report.from.length>0)
if(report.from==report.to||!report.to||report.to.length==0)
$(".description",content_div).text($("#congestion_on_around").text().replace(/xxx/,report.street).replace(/xxx/,report.from));else
$(".description",content_div).text($("#congestion_from_to_on").text().replace(/xxx/,report.from).replace(/xxx/,report.to).replace(/xxx/,report.street));else
if(report.street==report.city)
$(".description",content_div).text($("#congestion_on").text().replace(/xxx/,report.city));else
$(".description",content_div).text($("#congestion_on_in").text().replace(/xxx/,report.street).replace(/xxx/,report.city));$(".duration .number",content_div).text(report.duration);$(".duration",content_div).show();$(".speed .number",content_div).text(report.speed);$(".speed",content_div).show();var measurement_system=$(".measurement_system").text();$(".speed .unit",content_div).text($("."+measurement_system+"_speed").text());$(".last_updated .number",content_div).text(report.last_updated);},select:function(feature){if(feature.layer.name!="traffic")
return;if(feature.popup)
return;var lonlat=this.map.lastMouseLonlat;var tooltip=$("<div></div>");this.insertDescriptionText($(tooltip).eq(0),feature.description);feature.popup=new OpenLayers.Popup(null,lonlat,new OpenLayers.Size(200,100),tooltip.html(),false);feature.popup.panMapIfOutOfView=true;this.map.addPopup(feature.popup);$(feature.popup.contentDiv).addClass("trafficTooltip");$(feature.popup.contentDiv).css("border-color",feature.style.strokeColor);$(feature.popup.contentDiv).css("padding","10px");$(feature.popup.contentDiv).css("-moz-border-radius","5px");$("a",feature.popup.contentDiv).removeAttr("href");$(feature.popup.div).css("-moz-border-radius","5px");$(feature.popup.div).css("width",$(feature.popup.contentDiv).outerWidth()).css("height","auto");feature.popup.panMapIfOutOfView=true;feature.popup.setOpacity(0.9);feature.popup.setBorder("1px solid #858686");var ctrl=this;$(feature.popup.div).hover(over=function(){feature.popup.is_over=true;},out=function(){feature.popup.is_over=false;if(feature.unselected)
ctrl.unselect(feature);});},unselect:function(feature){if(!feature.popup)
return;if(feature.popup.is_over){feature.unselected=true;return;}
var ctrl=this;window.setTimeout(function(){if(!feature.popup)
return;ctrl.map.removePopup(feature.popup);feature.popup.destroy();feature.popup=null;},1000);return;},CLASS_NAME:"OpenLayers.Control.TrafficControl"});