
DynamicWMS=OpenLayers.Class(OpenLayers.Layer.WMS,{urls_to_skip:[],skipCurrentURL:function(){this.urls_to_skip.push(this.url);this.redraw();},getURL:function(bounds){var areas=this.params._M_C;for(var i in areas.area){var area=areas.area[i];var bbox=area["bounding-box"];if(bounds.left>=bbox.left&&bounds.right<=bbox.right&&bounds.top<=bbox.top&&bounds.bottom>=bbox.bottom){var is_skip=false;for(var j in this.urls_to_skip){if(this.urls_to_skip[j]==area.url)
is_skip=true;}
if(is_skip)
continue;this.url=area.url;return OpenLayers.Layer.WMS.prototype.getURL.apply(this,arguments);}}
if(this.urls_to_skip.length>0){this.urls_to_skip=[];return this.getURL(bounds);}
return null;},CLASS_NAME:"DynamicWMS"});var Layers={grid_settings:{alpha:true,visibility:false,buffer:2,singleTile:true},grid_settings_visible:{alpha:true,visibility:true,buffer:2,singleTile:true},grid_settings_landmarks:{alpha:true,visibility:false,buffer:2,singleTile:true,opacity:0.5},grid_settings_area_managers:{alpha:true,visibility:false,buffer:2,singleTile:true,opacity:0.6},gpsPointsLayer:"kkkkk",gpsRoadsLayer:"rrrr",mapProblemsLayer:"lll",make:function(bounds,wms_servers,edit_servers,gps_points_servers,map_capabilities){var mappingQ=$(".layersContainer");return[new OpenLayers.Layer.WMS($("#shade",mappingQ).text(),edit_servers,{layers:'shade',format:'image/png',transparent:"true"},{isBaseLayer:true,alpha:true,buffer:2,singleTile:true}),map_capabilities!=null?new DynamicWMS($("#aerial",mappingQ).text(),wms_servers,{'_m_c':map_capabilities["map-capabilities"].layers.Aerial,layers:'aerial',format:'image/png'},{isBaseLayer:false,visibility:true,tileSize:new OpenLayers.Size(256,256),buffer:0}):new OpenLayers.Layer.ArcGISCache({name:$("#aerial",mappingQ).text(),url:["/get_datadoors_tile/1/","/get_datadoors_tile/2/","/get_datadoors_tile/3/"],upperCase:false,type:"jpg",tileOrigin:new OpenLayers.LonLat(-20037508.34,20037508.34),visibility:true,isBaseLayer:false,alpha:true,buffer:2,zoomOffset:12}),new OpenLayers.Layer.WMS($("#managers",mappingQ).text(),edit_servers,{layers:'managers',format:'image/png',transparent:"true"},this.grid_settings_area_managers),Layers.roadsLayer=new OpenLayers.Layer.WMS($("#roads",mappingQ).text(),edit_servers,{layers:'roads',format:'image/png',transparent:"true"},this.grid_settings_visible),new OpenLayers.Layer.WMS($("#line_roads",mappingQ).text(),edit_servers,{layers:'line_roads',format:'image/png',transparent:"true"},this.grid_settings),new OpenLayers.Layer.WMS($("#unknown_roads",mappingQ).text(),edit_servers,{layers:'unknown_roads',format:'image/png',transparent:"true"},this.grid_settings),new OpenLayers.Layer.WMS($("#no_name_roads",mappingQ).text(),edit_servers,{layers:'no_name_roads',format:'image/png',transparent:"true"},this.grid_settings),Layers.gpsPointsLayer=new OpenLayers.Layer.WMS($("#gps_points",mappingQ).text(),gps_points_servers,{layers:'gps_points',format:'image/png',transparent:"true",_gps_points_arrows:document.gps_points_form.gps_points_arrows.checked,_gps_points_colors:document.gps_points_form.gps_points_colors.value,_mark_session_id:document.gps_points_form.marked_session_id.value,_gps_points_filter_user_tracks:document.gps_points_form.filter_user_tracks.checked,_gps_points_low_weight:document.gps_points_form.filter_low_weight.checked,_gps_points_user_id:logged_in_user_id},this.grid_settings),Layers.landmarksLayer=new OpenLayers.Layer.WMS($("#landmarks",mappingQ).text(),edit_servers,{layers:'landmarks',format:'image/png',transparent:"true"},this.grid_settings_landmarks),Layers.lassoLayer=new OpenLayers.Layer.WMS($("#lasso",mappingQ).text(),edit_servers,{layers:'lasso',format:'image/png',transparent:"true"},this.grid_settings_landmarks),Layers.mapProblemsLayer=new OpenLayers.Layer.WMS($("#map_problems",mappingQ).text(),edit_servers,{layers:'map_problems',format:'image/png',transparent:"true",_map_problems_city_name:document.map_problems_filter_form.city_name.value,_map_problems_street_name:document.map_problems_filter_form.street_name.value,_map_problems_filter_managed_area:document.map_problems_filter_form.filter_managed_area.checked,_map_problems_filter_next_to_user_segments:document.map_problems_filter_form.filter_next_to_user_segments.checked,_map_problems_filter_by_days:document.map_problems_filter_form.map_problems_filter_by_days.value,_map_problems_user_id:logged_in_user_id,_map_problems_type_filter:document.map_problems_legend_form.problem_type_filter.value,_map_problems_colors:document.map_problems_legend_form.map_problems_colors.value,_map_problems_show_resolved:document.map_problems_legend_form.map_problems_show_resolved.checked,_map_problems_show_low_priority:document.map_problems_legend_form.map_problems_show_low_priority.checked,_force_map_problems_id:''},this.grid_settings),new OpenLayers.Layer.WMS($("#users_notes",mappingQ).text(),edit_servers,{layers:'users_notes',format:'image/png',transparent:"true"},this.grid_settings),new OpenLayers.Layer.WMS($("#street_ranges",mappingQ).text(),edit_servers,{layers:'street_ranges',format:'image/png',transparent:"true"},this.grid_settings),new OpenLayers.Layer.WMS($("#update_requests",mappingQ).text(),edit_servers,{layers:'update_requests',format:'image/png',transparent:"true"},this.grid_settings),new OpenLayers.Layer.WMS($("#restrictions",mappingQ).text(),edit_servers,{layers:'restrictions',format:'image/png',transparent:"true"},this.grid_settings),new OpenLayers.Layer.WMS($("#speed_cams",mappingQ).text(),edit_servers,{layers:'speed_cams',format:'image/png',transparent:"true"},this.grid_settings),new OpenLayers.Layer.WMS($("#fleet",mappingQ).text(),edit_servers,{layers:'fleet',format:'image/png',transparent:"true"},this.grid_settings),]}}
function FeatureFactory(){var ff=this;var concat=this._concatenate;var add=this._additive;var identical=this._identical;this.FEATURE_TYPES={"roads":{vector_parser:ff._parsePolyline,style:{strokeWidth:5,strokeColor:"#de0ced",strokeOpacity:0.8},detail_names:{"id":concat,"street_id":concat,"city_name":identical,"road_type":identical,"direction":identical,"province_name":identical,"street_name":identical,"english_name":identical,"eng_name":identical,"txt2speech":identical,"street_type":identical,"separator":identical,"locked":identical,"road_length":add,"from_cross_time":add,"to_cross_time":add,"road_speed":function(){return""},"update_user":identical,"user_name":identical,"update_time_as_text":identical,"user_rank":identical,"level":identical,"anchor_hint_x":identical,"anchor_hint_y":identical,"azimuth":identical,"country_name":identical},noun_id:"road_noun",onMergeEnd:function(merged_details){merged_details["road_speed"]=parseInt(merged_details["road_length"])/parseInt(merged_details["from_cross_time"]);}},"nodes":{vector_parser:ff._parsePoint,style:{strokeWidth:4,strokeColor:"blue",strokeOpacity:0.8,pointRadius:10,fillColor:"transparent",fillOpacity:0.3},detail_names:{"id":concat,"user_name":identical,"user_rank":identical},noun_id:"node_noun",onMergeEnd:function(merged_details){}},"map_problems":{vector_parser:ff._parseMultiPoint,style:{strokeWidth:3,strokeColor:"black",strokeOpacity:0.8,pointRadius:18,fillColor:"transparent",fillOpacity:0.3},detail_names:{"id":concat,"user_name":identical,"user_rank":identical,"anchor_hint_x":identical,"anchor_hint_y":identical},noun_id:"node_noun",onMergeEnd:function(merged_details){}},"gps_points":{vector_parser:ff._parseMultiPoint,style:{strokeWidth:4,strokeColor:"black",strokeOpacity:0.8,pointRadius:14,fillColor:"transparent",fillOpacity:0.3},detail_names:{"id":concat,"user_name":identical,"user_rank":identical},noun_id:"node_noun",onMergeEnd:function(merged_details){}},"users_notes":{vector_parser:ff._parsePoint,style:{strokeWidth:4,strokeColor:"yellow",strokeOpacity:0.8,pointRadius:10,fillColor:"transparent",fillOpacity:0.3},detail_names:{"id":concat,"description":identical,"user_name":identical,"user_rank":identical},noun_id:"node_noun",onMergeEnd:function(merged_details){}},"speed_cams":{vector_parser:ff._parsePoint,style:{strokeWidth:4,strokeColor:"yellow",strokeOpacity:0.8,pointRadius:10,fillColor:"transparent",fillOpacity:0.3},detail_names:{"id":concat,"cam_speed":identical,"cam_type":identical,"user_name":identical,"user_rank":identical},noun_id:"speed_cam_noun",onMergeEnd:function(merged_details){var measurement_system=$(".measurement_system").text();if(measurement_system=="imperial"){merged_details.cam_speed=Math.round(parseInt(merged_details.cam_speed)/1.609);}}},"street_ranges":{vector_parser:ff._parsePoint,style:{strokeWidth:4,strokeColor:"yellow",strokeOpacity:0.8,pointRadius:10,fillColor:"transparent",fillOpacity:0.3},detail_names:{"id":concat,"street_name":identical,"suggested_street_name":identical,"city_name":identical,"left_addr":identical,"right_addr":identical,"magvar":identical,"user_name":identical,"user_rank":identical},noun_id:"house_number_noun",onMergeEnd:function(merged_details){}},"landmarks":{vector_parser:ff._parsePolyline,style:{strokeWidth:3,strokeColor:"black",strokeOpacity:0.8,pointRadius:18,fillColor:"transparent",fillOpacity:0.3},detail_names:{"id":concat,"name":identical,"city_name":identical,"mtfcc":identical,"area":identical,"english_name":identical,"txt2speech":identical,"area_in_meters":identical,"user_name":identical,"update_user":identical,"description":identical,"anchor_hint_x":identical,"anchor_hint_y":identical},noun_id:"landmark_noun",onMergeEnd:function(merged_details){}},"landmark_points":{vector_parser:ff._parsePoint,style:{strokeWidth:3,strokeColor:"black",strokeOpacity:0.8,pointRadius:8,fillColor:"transparent",fillOpacity:0.3},detail_names:{"id":concat,"name":identical,"type":identical,"user_name":identical,"update_user":identical},noun_id:"landmark_point_noun",onMergeEnd:function(merged_details){}},"update_requests":{vector_parser:ff._parsePoint,style:{strokeWidth:4,strokeColor:"yellow",strokeOpacity:0.8,pointRadius:10,fillColor:"transparent",fillOpacity:0.3},detail_names:{"id":concat,"update_text":identical,"updater_note":identical,"age":identical,"update_type":identical,"update_state":identical,"name":identical},noun_id:"update_request_noun",onMergeEnd:function(merged_details){}}}
this.FEATURE_TYPES["line_roads"]=this.FEATURE_TYPES["roads"];this.FEATURE_TYPES["unknown_roads"]=this.FEATURE_TYPES["roads"];}
FeatureFactory.prototype._identical=function(merged_details,next_details,detail_name){if(merged_details[detail_name]==""||merged_details[detail_name]!=next_details[detail_name])
return"";return merged_details[detail_name];}
FeatureFactory.prototype._additive=function(merged_details,next_details,detail_name){return parseInt(merged_details[detail_name])+parseInt(next_details[detail_name]);}
FeatureFactory.prototype._concatenate=function(merged_details,next_details,detail_name){return merged_details[detail_name]+","+next_details[detail_name];}
FeatureFactory.prototype._parseDetails=function(element,type){var getKeysArray=function(map){var arr=[];for(var key in map)
arr.push(key);return arr;}
var dnames=getKeysArray(this.FEATURE_TYPES[type].detail_names);var details={};for(var i=0;i<dnames.length;i++)
if(dnames[i]=="province_name")
details[dnames[i]]=$(":ns(http://www.ttt.org/myns,state_name)",element).text();else
details[dnames[i]]=$(":ns(http://www.ttt.org/myns,"+dnames[i]+")",element).text();return details;}
FeatureFactory.prototype._parsePoint=function(element){var point=null;var coordinatesStr=$(":ns(http://www.opengis.net/gml,Point) :ns(http://www.opengis.net/gml,coordinates)",element).text();var coordinates=$.trim(coordinatesStr).split(",");point=new OpenLayers.Feature.Vector(geometry=new OpenLayers.Geometry.Point(x=coordinates[0],y=coordinates[1]));return point;}
FeatureFactory.prototype._parseMultiPoint=function(element){var polyline_vector=null;var points=$(":ns(http://www.opengis.net/gml,Point)",element);var pline=new OpenLayers.Geometry.MultiPoint();for(var p=0;p<points.length;p++){var coordinatesStr=$(":ns(http://www.opengis.net/gml,coordinates)",points[p]).text();var point=$.trim(coordinatesStr).split(",");pline.addPoint(new OpenLayers.Geometry.Point(x=point[0],y=point[1]));}
polyline_vector=new OpenLayers.Feature.Vector(geometry=pline);return polyline_vector;}
FeatureFactory.prototype._parsePolyline=function(element){var polyline_vector=null;var coordinatesStr=$(":ns(http://www.opengis.net/gml,LineString) :ns(http://www.opengis.net/gml,coordinates)",element).text();if(coordinatesStr.length==0){coordinatesStr=$(":ns(http://www.opengis.net/gml,LinearRing) :ns(http://www.opengis.net/gml,coordinates)",element).text();}
var coordinates=$.trim(coordinatesStr).split(" ");var pline=new OpenLayers.Geometry.LineString();for(var i in coordinates){var point=coordinates[i].split(",");pline.addPoint(new OpenLayers.Geometry.Point(x=point[0],y=point[1]));}
polyline_vector=new OpenLayers.Feature.Vector(geometry=pline);return polyline_vector;}
FeatureFactory.prototype._parseVector=function(element,type){var vp=this.FEATURE_TYPES[type].vector_parser;var vector=vp(element);vector.style=this.FEATURE_TYPES[type].style;return vector;}
FeatureFactory.prototype.make=function(element){var type=$(element).attr("fid").split(".")[0];var vector=this._parseVector(element,type);var details=this._parseDetails(element,type);return{"vector":vector,"details":details};}
FeatureFactory.prototype.makeRoadFromJSON=function(json){var pline=new OpenLayers.Geometry.LineString();var anchor_x,anchor_y;for(var i in json.theGeom){var next=json.theGeom[i];pline.addPoint(new OpenLayers.Geometry.Point(x=next.lon,y=next.lat));if(i==Math.floor(json.theGeom.length/2)){anchor_x=next.lon;anchor_y=next.lat;}}
vector=new OpenLayers.Feature.Vector(geometry=pline);vector.style={strokeWidth:5,strokeColor:"#de0ced",strokeOpacity:0.8};var getKeysArray=function(map){var arr=[];for(var key in map)
arr.push(key);return arr;}
var dnames=getKeysArray(this.FEATURE_TYPES["roads"].detail_names);var details={};for(var i=0;i<dnames.length;i++)
details[dnames[i]]=json[dnames[i]];details.anchor_hint_x=anchor_x;details.anchor_hint_y=anchor_y;return{"vector":vector,"details":details};}
FeatureFactory.prototype.mergeDetails=function(feature_map,features_type){var merged_details={};var detail_names=this.FEATURE_TYPES[features_type].detail_names;for(var name in detail_names)
merged_details[name]=null;for(var id in feature_map){var next_feature_details=feature_map[id].details;for(var next_detail in merged_details){if(merged_details[next_detail]==null)
merged_details[next_detail]=next_feature_details[next_detail];else
merged_details[next_detail]=detail_names[next_detail](merged_details,next_feature_details,next_detail);}}
this.FEATURE_TYPES[features_type].onMergeEnd(merged_details);return merged_details;}
var CurveHelper={n:0,n1:0,dx:[],dy:[],Ax:[],Ay:[],Bi:[],B0:[],B1:[],B2:[],B3:[],P:[],PPP:10,findCPoints:function(){CurveHelper.Bi[1]=-.25;CurveHelper.Ax[1]=(CurveHelper.P[2].x-CurveHelper.P[0].x-CurveHelper.dx[0])/4;CurveHelper.Ay[1]=(CurveHelper.P[2].y-CurveHelper.P[0].y-CurveHelper.dy[0])/4;for(var i=2;i<n-1;i++){CurveHelper.Bi[i]=-1/(4+CurveHelper.Bi[i-1]);CurveHelper.Ax[i]=-(CurveHelper.P[i+1].x-CurveHelper.P[i-1].x-CurveHelper.Ax[i-1])*CurveHelper.Bi[i];CurveHelper.Ay[i]=-(CurveHelper.P[i+1].y-CurveHelper.P[i-1].y-CurveHelper.Ay[i-1])*CurveHelper.Bi[i];}
for(var i=n-2;i>0;i--){CurveHelper.dx[i]=CurveHelper.Ax[i]+CurveHelper.dx[i+1]*CurveHelper.Bi[i];CurveHelper.dy[i]=CurveHelper.Ay[i]+CurveHelper.dy[i+1]*CurveHelper.Bi[i];}},make:function(_P){n=_P.length;n1=n+1;var cur=0;CurveHelper.P=_P;var t=0;for(var i=0;i<CurveHelper.P.length;i++){CurveHelper.dx[i]=0;CurveHelper.dy[i]=0;}
for(var i=0;i<CurveHelper.PPP;i++){var t1=1-t;var t12=t1*t1;var t2=t*t;CurveHelper.B0[i]=t1*t12;CurveHelper.B1[i]=3*t*t12;CurveHelper.B2[i]=3*t2*t1;CurveHelper.B3[i]=t*t2;t+=.04;}},getSplinePoints:function(){var points=[];CurveHelper.findCPoints();var X,Y;var loc=0;for(var i=0;i<n-1;i++){for(var k=0;k<CurveHelper.PPP;k++){X=(CurveHelper.P[i].x*CurveHelper.B0[k]+(CurveHelper.P[i].x+CurveHelper.dx[i])*CurveHelper.B1[k]+
(CurveHelper.P[i+1].x-CurveHelper.dx[i+1])*CurveHelper.B2[k]+CurveHelper.P[i+1].x*CurveHelper.B3[k]);Y=(CurveHelper.P[i].y*CurveHelper.B0[k]+(CurveHelper.P[i].y+CurveHelper.dy[i])*CurveHelper.B1[k]+
(CurveHelper.P[i+1].y-CurveHelper.dy[i+1])*CurveHelper.B2[k]+CurveHelper.P[i+1].y*CurveHelper.B3[k]);points[loc]={x:X,y:Y};loc++;}}
return points;}};
HotKeys={'all_shortcuts':{},'add':function(shortcut_combination,callback,opt){var default_options={'type':'keydown','propagate':false,'disable_in_input':false,'target':document,'keycode':false}
if(!opt)opt=default_options;else{for(var dfo in default_options){if(typeof opt[dfo]=='undefined')opt[dfo]=default_options[dfo];}}
var ele=opt.target;if(typeof opt.target=='string')ele=document.getElementById(opt.target);var ths=this;shortcut_combination=shortcut_combination.toLowerCase();var func=function(e){e=e||window.event;if(opt['disable_in_input']){var element;if(e.target)element=e.target;else if(e.srcElement)element=e.srcElement;if(element.nodeType==3)element=element.parentNode;if(element.tagName=='INPUT'||element.tagName=='TEXTAREA')return;}
if(e.keyCode)code=e.keyCode;else if(e.which)code=e.which;var character=String.fromCharCode(code).toLowerCase();if(code==188)character=",";if(code==190)character=".";var keys=shortcut_combination.split("+");var kp=0;var shift_nums={"`":"~","1":"!","2":"@","3":"#","4":"$","5":"%","6":"^","7":"&","8":"*","9":"(","0":")","-":"_","=":"+",";":":","'":"\"",",":"<",".":">","/":"?","\\":"|"}
var special_keys={'esc':27,'escape':27,'tab':9,'space':32,'return':13,'enter':13,'backspace':8,'scrolllock':145,'scroll_lock':145,'scroll':145,'capslock':20,'caps_lock':20,'caps':20,'numlock':144,'num_lock':144,'num':144,'pause':19,'break':19,'insert':45,'home':36,'delete':46,'end':35,'pageup':33,'page_up':33,'pu':33,'pagedown':34,'page_down':34,'pd':34,'left':37,'up':38,'right':39,'down':40,'f1':112,'f2':113,'f3':114,'f4':115,'f5':116,'f6':117,'f7':118,'f8':119,'f9':120,'f10':121,'f11':122,'f12':123}
var modifiers={shift:{wanted:false,pressed:false},ctrl:{wanted:false,pressed:false},alt:{wanted:false,pressed:false},meta:{wanted:false,pressed:false}};if(e.ctrlKey)modifiers.ctrl.pressed=true;if(e.shiftKey)modifiers.shift.pressed=true;if(e.altKey)modifiers.alt.pressed=true;if(e.metaKey)modifiers.meta.pressed=true;for(var i=0;k=keys[i],i<keys.length;i++){if(k=='ctrl'||k=='control'){kp++;modifiers.ctrl.wanted=true;}else if(k=='shift'){kp++;modifiers.shift.wanted=true;}else if(k=='alt'){kp++;modifiers.alt.wanted=true;}else if(k=='meta'){kp++;modifiers.meta.wanted=true;}else if(k.length>1){if(special_keys[k]==code)kp++;}else if(opt['keycode']){if(opt['keycode']==code)kp++;}else{if(character==k)kp++;else{if(shift_nums[character]&&e.shiftKey){character=shift_nums[character];if(character==k)kp++;}}}}
if(kp==keys.length&&modifiers.ctrl.pressed==modifiers.ctrl.wanted&&modifiers.shift.pressed==modifiers.shift.wanted&&modifiers.alt.pressed==modifiers.alt.wanted&&modifiers.meta.pressed==modifiers.meta.wanted){callback(e);if(!opt['propagate']){e.cancelBubble=true;e.returnValue=false;if(e.stopPropagation){e.stopPropagation();e.preventDefault();}
return false;}}}
this.all_shortcuts[shortcut_combination]={'callback':func,'target':ele,'event':opt['type']};if(ele.addEventListener)ele.addEventListener(opt['type'],func,false);else if(ele.attachEvent)ele.attachEvent('on'+opt['type'],func);else ele['on'+opt['type']]=func;},'remove':function(shortcut_combination){shortcut_combination=shortcut_combination.toLowerCase();var binding=this.all_shortcuts[shortcut_combination];delete(this.all_shortcuts[shortcut_combination])
if(!binding)return;var type=binding['event'];var ele=binding['target'];var callback=binding['callback'];if(ele.detachEvent)ele.detachEvent('on'+type,callback);else if(ele.removeEventListener)ele.removeEventListener(type,callback,false);else ele['on'+type]=false;}};
(function($)
{$.fn.qtip=function(options,blanket)
{var i,id,interfaces,opts,obj,command,config,api;if(typeof options=='string')
{if(typeof $(this).data('qtip')!=='object')
return;if(options=='api')
return $(this).data('qtip').interfaces[$(this).data('qtip').current];else if(options=='interfaces')
return $(this).data('qtip').interfaces;}
else
{if(!options)options={};if(typeof options.content!=='object'||(options.content.jquery&&options.content.length>0))options.content={text:options.content};if(typeof options.content.title!=='object')options.content.title={text:options.content.title};if(typeof options.position!=='object')options.position={corner:options.position};if(typeof options.position.corner!=='object')options.position.corner={target:options.position.corner,tooltip:options.position.corner};if(typeof options.show!=='object')options.show={when:options.show};if(typeof options.show.when!=='object')options.show.when={event:options.show.when};if(typeof options.show.effect!=='object')options.show.effect={type:options.show.effect};if(typeof options.hide!=='object')options.hide={when:options.hide};if(typeof options.hide.when!=='object')options.hide.when={event:options.hide.when};if(typeof options.hide.effect!=='object')options.hide.effect={type:options.hide.effect};if(typeof options.style!=='object')options.style={name:options.style};options.style=sanitizeStyle(options.style);opts=$.extend(true,{},$.fn.qtip.defaults,options);opts.style=buildStyle.call({options:opts},opts.style);opts.user=$.extend(true,{},options);};return $(this).each(function()
{if(typeof options=='string')
{command=options.toLowerCase();interfaces=$(this).qtip('interfaces');if(typeof interfaces=='object')
{if(blanket===true&&command=='destroy')
while(interfaces.length>0)interfaces[interfaces.length-1].destroy();else
{if(blanket!==true)interfaces=[$(this).qtip('api')];for(i=0;i<interfaces.length;i++)
{if(command=='destroy')interfaces[i].destroy();else if(interfaces[i].status.rendered===true)
{if(command=='show')interfaces[i].show();else if(command=='hide')interfaces[i].hide();else if(command=='focus')interfaces[i].focus();else if(command=='disable')interfaces[i].disable(true);else if(command=='enable')interfaces[i].disable(false);};};};};}
else
{config=$.extend(true,{},opts);config.hide.effect.length=opts.hide.effect.length;config.show.effect.length=opts.show.effect.length;if(config.position.container===false)config.position.container=$(document.body);if(config.position.target===false)config.position.target=$(this);if(config.show.when.target===false)config.show.when.target=$(this);if(config.hide.when.target===false)config.hide.when.target=$(this);id=$.fn.qtip.interfaces.length;for(i=0;i<id;i++)
{if(typeof $.fn.qtip.interfaces[i]=='undefined'){id=i;break;};};obj=new qTip($(this),config,id);$.fn.qtip.interfaces[id]=obj;if(typeof $(this).data('qtip')=='object')
{if(typeof $(this).attr('qtip')==='undefined')
$(this).data('qtip').current=$(this).data('qtip').interfaces.length;$(this).data('qtip').interfaces.push(obj);}
else $(this).data('qtip',{current:0,interfaces:[obj]});if(config.content.prerender===false&&config.show.when.event!==false&&config.show.ready!==true)
{config.show.when.target.bind(config.show.when.event+'.qtip-'+id+'-create',{qtip:id},function(event)
{api=$.fn.qtip.interfaces[event.data.qtip];api.options.show.when.target.unbind(api.options.show.when.event+'.qtip-'+event.data.qtip+'-create');api.cache.mouse={x:event.pageX,y:event.pageY};construct.call(api);api.options.show.when.target.trigger(api.options.show.when.event);});}
else
{obj.cache.mouse={x:config.show.when.target.offset().left,y:config.show.when.target.offset().top};construct.call(obj);}};});};function qTip(target,options,id)
{var self=this;self.id=id;self.options=options;self.status={animated:false,rendered:false,disabled:false,focused:false};self.elements={target:target.addClass(self.options.style.classes.target),tooltip:null,wrapper:null,content:null,contentWrapper:null,title:null,button:null,tip:null,bgiframe:null};self.cache={mouse:{},position:{},toggle:0};self.timers={};$.extend(self,self.options.api,{show:function(event)
{var returned,solo;if(!self.status.rendered)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.TOOLTIP_NOT_RENDERED,'show');if(self.elements.tooltip.css('display')!=='none')return self;self.elements.tooltip.stop(true,false);returned=self.beforeShow.call(self,event);if(returned===false)return self;function afterShow()
{if(self.options.position.type!=='static')self.focus();self.onShow.call(self,event);if($.browser.msie)self.elements.tooltip.get(0).style.removeAttribute('filter');};self.cache.toggle=1;if(self.options.position.type!=='static')
self.updatePosition(event,(self.options.show.effect.length>0));if(typeof self.options.show.solo=='object')solo=$(self.options.show.solo);else if(self.options.show.solo===true)solo=$('div.qtip').not(self.elements.tooltip);if(solo)solo.each(function(){if($(this).qtip('api').status.rendered===true)$(this).qtip('api').hide();});if(typeof self.options.show.effect.type=='function')
{self.options.show.effect.type.call(self.elements.tooltip,self.options.show.effect.length);self.elements.tooltip.queue(function(){afterShow();$(this).dequeue();});}
else
{switch(self.options.show.effect.type.toLowerCase())
{case'fade':self.elements.tooltip.fadeIn(self.options.show.effect.length,afterShow);break;case'slide':self.elements.tooltip.slideDown(self.options.show.effect.length,function()
{afterShow();if(self.options.position.type!=='static')self.updatePosition(event,true);});break;case'grow':self.elements.tooltip.show(self.options.show.effect.length,afterShow);break;default:self.elements.tooltip.show(null,afterShow);break;};self.elements.tooltip.addClass(self.options.style.classes.active);};return $.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.EVENT_SHOWN,'show');},hide:function(event)
{var returned;if(!self.status.rendered)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.TOOLTIP_NOT_RENDERED,'hide');else if(self.elements.tooltip.css('display')==='none')return self;clearTimeout(self.timers.show);self.elements.tooltip.stop(true,false);returned=self.beforeHide.call(self,event);if(returned===false)return self;function afterHide(){self.onHide.call(self,event);};self.cache.toggle=0;if(typeof self.options.hide.effect.type=='function')
{self.options.hide.effect.type.call(self.elements.tooltip,self.options.hide.effect.length);self.elements.tooltip.queue(function(){afterHide();$(this).dequeue();});}
else
{switch(self.options.hide.effect.type.toLowerCase())
{case'fade':self.elements.tooltip.fadeOut(self.options.hide.effect.length,afterHide);break;case'slide':self.elements.tooltip.slideUp(self.options.hide.effect.length,afterHide);break;case'grow':self.elements.tooltip.hide(self.options.hide.effect.length,afterHide);break;default:self.elements.tooltip.hide(null,afterHide);break;};self.elements.tooltip.removeClass(self.options.style.classes.active);};return $.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.EVENT_HIDDEN,'hide');},updatePosition:function(event,animate)
{var i,target,tooltip,coords,mapName,imagePos,newPosition,ieAdjust,ie6Adjust,borderAdjust,mouseAdjust,offset,curPosition,returned
if(!self.status.rendered)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.TOOLTIP_NOT_RENDERED,'updatePosition');else if(self.options.position.type=='static')
return $.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.CANNOT_POSITION_STATIC,'updatePosition');target={position:{left:0,top:0},dimensions:{height:0,width:0},corner:self.options.position.corner.target};tooltip={position:self.getPosition(),dimensions:self.getDimensions(),corner:self.options.position.corner.tooltip};if(self.options.position.target!=='mouse')
{if(self.options.position.target.get(0).nodeName.toLowerCase()=='area')
{coords=self.options.position.target.attr('coords').split(',');for(i=0;i<coords.length;i++)coords[i]=parseInt(coords[i]);mapName=self.options.position.target.parent('map').attr('name');imagePos=$('img[usemap="#'+mapName+'"]:first').offset();target.position={left:Math.floor(imagePos.left+coords[0]),top:Math.floor(imagePos.top+coords[1])};switch(self.options.position.target.attr('shape').toLowerCase())
{case'rect':target.dimensions={width:Math.ceil(Math.abs(coords[2]-coords[0])),height:Math.ceil(Math.abs(coords[3]-coords[1]))};break;case'circle':target.dimensions={width:coords[2]+1,height:coords[2]+1};break;case'poly':target.dimensions={width:coords[0],height:coords[1]};for(i=0;i<coords.length;i++)
{if(i%2==0)
{if(coords[i]>target.dimensions.width)
target.dimensions.width=coords[i];if(coords[i]<coords[0])
target.position.left=Math.floor(imagePos.left+coords[i]);}
else
{if(coords[i]>target.dimensions.height)
target.dimensions.height=coords[i];if(coords[i]<coords[1])
target.position.top=Math.floor(imagePos.top+coords[i]);};};target.dimensions.width=target.dimensions.width-(target.position.left-imagePos.left);target.dimensions.height=target.dimensions.height-(target.position.top-imagePos.top);break;default:return $.fn.qtip.log.error.call(self,4,$.fn.qtip.constants.INVALID_AREA_SHAPE,'updatePosition');break;};target.dimensions.width-=2;target.dimensions.height-=2;}
else if(self.options.position.target.add(document.body).length===1)
{target.position={left:$(document).scrollLeft(),top:$(document).scrollTop()};target.dimensions={height:$(window).height(),width:$(window).width()};}
else
{if(typeof self.options.position.target.attr('qtip')!=='undefined')
target.position=self.options.position.target.qtip('api').cache.position;else
target.position=self.options.position.target.offset();target.dimensions={height:self.options.position.target.outerHeight(),width:self.options.position.target.outerWidth()};};newPosition=$.extend({},target.position);if(target.corner.search(/right/i)!==-1)
newPosition.left+=target.dimensions.width;if(target.corner.search(/bottom/i)!==-1)
newPosition.top+=target.dimensions.height;if(target.corner.search(/((top|bottom)Middle)|center/)!==-1)
newPosition.left+=(target.dimensions.width/2);if(target.corner.search(/((left|right)Middle)|center/)!==-1)
newPosition.top+=(target.dimensions.height/2);}
else
{target.position=newPosition={left:self.cache.mouse.x,top:self.cache.mouse.y};target.dimensions={height:1,width:1};};if(tooltip.corner.search(/right/i)!==-1)
newPosition.left-=tooltip.dimensions.width;if(tooltip.corner.search(/bottom/i)!==-1)
newPosition.top-=tooltip.dimensions.height;if(tooltip.corner.search(/((top|bottom)Middle)|center/)!==-1)
newPosition.left-=(tooltip.dimensions.width/2);if(tooltip.corner.search(/((left|right)Middle)|center/)!==-1)
newPosition.top-=(tooltip.dimensions.height/2);ieAdjust=($.browser.msie)?1:0;ie6Adjust=($.browser.msie&&parseInt($.browser.version.charAt(0))===6)?1:0;if(self.options.style.border.radius>0)
{if(tooltip.corner.search(/Left/)!==-1)
newPosition.left-=self.options.style.border.radius;else if(tooltip.corner.search(/Right/)!==-1)
newPosition.left+=self.options.style.border.radius;if(tooltip.corner.search(/Top/)!==-1)
newPosition.top-=self.options.style.border.radius;else if(tooltip.corner.search(/Bottom/)!==-1)
newPosition.top+=self.options.style.border.radius;};if(ieAdjust)
{if(tooltip.corner.search(/top/)!==-1)
newPosition.top-=ieAdjust
else if(tooltip.corner.search(/bottom/)!==-1)
newPosition.top+=ieAdjust
if(tooltip.corner.search(/left/)!==-1)
newPosition.left-=ieAdjust
else if(tooltip.corner.search(/right/)!==-1)
newPosition.left+=ieAdjust
if(tooltip.corner.search(/leftMiddle|rightMiddle/)!==-1)
newPosition.top-=1};if(self.options.position.adjust.screen===true)
newPosition=screenAdjust.call(self,newPosition,target,tooltip);if(self.options.position.target==='mouse'&&self.options.position.adjust.mouse===true)
{if(self.options.position.adjust.screen===true&&self.elements.tip)
mouseAdjust=self.elements.tip.attr('rel');else
mouseAdjust=self.options.position.corner.tooltip;newPosition.left+=(mouseAdjust.search(/right/i)!==-1)?-6:6;newPosition.top+=(mouseAdjust.search(/bottom/i)!==-1)?-6:6;}
if(!self.elements.bgiframe&&$.browser.msie&&parseInt($.browser.version.charAt(0))==6)
{$('select, object').each(function()
{offset=$(this).offset();offset.bottom=offset.top+$(this).height();offset.right=offset.left+$(this).width();if(newPosition.top+tooltip.dimensions.height>=offset.top&&newPosition.left+tooltip.dimensions.width>=offset.left)
bgiframe.call(self);});};newPosition.left+=self.options.position.adjust.x;newPosition.top+=self.options.position.adjust.y;curPosition=self.getPosition();if(newPosition.left!=curPosition.left||newPosition.top!=curPosition.top)
{returned=self.beforePositionUpdate.call(self,event);if(returned===false)return self;self.cache.position=newPosition;if(animate===true)
{self.status.animated=true;self.elements.tooltip.animate(newPosition,200,'swing',function(){self.status.animated=false});}
else self.elements.tooltip.css(newPosition);self.onPositionUpdate.call(self,event);if(typeof event!=='undefined'&&event.type&&event.type!=='mousemove')
$.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.EVENT_POSITION_UPDATED,'updatePosition');};return self;},updateWidth:function(newWidth)
{var hidden;if(!self.status.rendered)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.TOOLTIP_NOT_RENDERED,'updateWidth');else if(newWidth&&typeof newWidth!=='number')
return $.fn.qtip.log.error.call(self,2,'newWidth must be of type number','updateWidth');hidden=self.elements.contentWrapper.siblings().add(self.elements.tip).add(self.elements.button);if(!newWidth)
{if(typeof self.options.style.width.value=='number')
newWidth=self.options.style.width.value;else
{self.elements.tooltip.css({width:'auto'});hidden.hide();if($.browser.msie)
self.elements.wrapper.add(self.elements.contentWrapper.children()).css({zoom:'normal'});newWidth=self.getDimensions().width+1;if(!self.options.style.width.value)
{if(newWidth>self.options.style.width.max)newWidth=self.options.style.width.max
if(newWidth<self.options.style.width.min)newWidth=self.options.style.width.min};};};if(newWidth%2!==0)newWidth-=1;self.elements.tooltip.width(newWidth);hidden.show();if(self.options.style.border.radius)
{self.elements.tooltip.find('.qtip-betweenCorners').each(function(i)
{$(this).width(newWidth-(self.options.style.border.radius*2));})};if($.browser.msie)
{self.elements.wrapper.add(self.elements.contentWrapper.children()).css({zoom:'1'});self.elements.wrapper.width(newWidth);if(self.elements.bgiframe)self.elements.bgiframe.width(newWidth).height(self.getDimensions.height);};return $.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.EVENT_WIDTH_UPDATED,'updateWidth');},updateStyle:function(name)
{var tip,borders,context,corner,coordinates;if(!self.status.rendered)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.TOOLTIP_NOT_RENDERED,'updateStyle');else if(typeof name!=='string'||!$.fn.qtip.styles[name])
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.STYLE_NOT_DEFINED,'updateStyle');self.options.style=buildStyle.call(self,$.fn.qtip.styles[name],self.options.user.style);self.elements.content.css(jQueryStyle(self.options.style));if(self.options.content.title.text!==false)
self.elements.title.css(jQueryStyle(self.options.style.title,true));self.elements.contentWrapper.css({borderColor:self.options.style.border.color});if(self.options.style.tip.corner!==false)
{if($('<canvas>').get(0).getContext)
{tip=self.elements.tooltip.find('.qtip-tip canvas:first');context=tip.get(0).getContext('2d');context.clearRect(0,0,300,300);corner=tip.parent('div[rel]:first').attr('rel');coordinates=calculateTip(corner,self.options.style.tip.size.width,self.options.style.tip.size.height);drawTip.call(self,tip,coordinates,self.options.style.tip.color||self.options.style.border.color);}
else if($.browser.msie)
{tip=self.elements.tooltip.find('.qtip-tip [nodeName="shape"]');tip.attr('fillcolor',self.options.style.tip.color||self.options.style.border.color);};};if(self.options.style.border.radius>0)
{self.elements.tooltip.find('.qtip-betweenCorners').css({backgroundColor:self.options.style.border.color});if($('<canvas>').get(0).getContext)
{borders=calculateBorders(self.options.style.border.radius)
self.elements.tooltip.find('.qtip-wrapper canvas').each(function()
{context=$(this).get(0).getContext('2d');context.clearRect(0,0,300,300);corner=$(this).parent('div[rel]:first').attr('rel')
drawBorder.call(self,$(this),borders[corner],self.options.style.border.radius,self.options.style.border.color);});}
else if($.browser.msie)
{self.elements.tooltip.find('.qtip-wrapper [nodeName="arc"]').each(function()
{$(this).attr('fillcolor',self.options.style.border.color)});};};return $.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.EVENT_STYLE_UPDATED,'updateStyle');},updateContent:function(content,reposition)
{var parsedContent,images,loadedImages;if(!self.status.rendered)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.TOOLTIP_NOT_RENDERED,'updateContent');else if(!content)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.NO_CONTENT_PROVIDED,'updateContent');parsedContent=self.beforeContentUpdate.call(self,content);if(typeof parsedContent=='string')content=parsedContent;else if(parsedContent===false)return;if($.browser.msie)self.elements.contentWrapper.children().css({zoom:'normal'});if(content.jquery&&content.length>0)
content.clone(true).appendTo(self.elements.content).show();else self.elements.content.html(content);images=self.elements.content.find('img[complete=false]');if(images.length>0)
{loadedImages=0;images.each(function(i)
{$('<img src="'+$(this).attr('src')+'" />').load(function(){if(++loadedImages==images.length)afterLoad();});});}
else afterLoad();function afterLoad()
{self.updateWidth();if(reposition!==false)
{if(self.options.position.type!=='static')
self.updatePosition(self.elements.tooltip.is(':visible'),true);if(self.options.style.tip.corner!==false)
positionTip.call(self);};};self.onContentUpdate.call(self);return $.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.EVENT_CONTENT_UPDATED,'loadContent');},loadContent:function(url,data,method)
{var returned;if(!self.status.rendered)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.TOOLTIP_NOT_RENDERED,'loadContent');returned=self.beforeContentLoad.call(self);if(returned===false)return self;if(method=='post')
$.post(url,data,setupContent);else
$.get(url,data,setupContent);function setupContent(content)
{self.onContentLoad.call(self);$.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.EVENT_CONTENT_LOADED,'loadContent');self.updateContent(content);};return self;},updateTitle:function(content)
{if(!self.status.rendered)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.TOOLTIP_NOT_RENDERED,'updateTitle');else if(!content)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.NO_CONTENT_PROVIDED,'updateTitle');returned=self.beforeTitleUpdate.call(self);if(returned===false)return self;if(self.elements.button)self.elements.button=self.elements.button.clone(true);self.elements.title.html(content)
if(self.elements.button)self.elements.title.prepend(self.elements.button);self.onTitleUpdate.call(self);return $.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.EVENT_TITLE_UPDATED,'updateTitle');},focus:function(event)
{var curIndex,newIndex,elemIndex,returned;if(!self.status.rendered)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.TOOLTIP_NOT_RENDERED,'focus');else if(self.options.position.type=='static')
return $.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.CANNOT_FOCUS_STATIC,'focus');curIndex=parseInt(self.elements.tooltip.css('z-index'));newIndex=260001+$('div.qtip[qtip]').length-1;if(!self.status.focused&&curIndex!==newIndex)
{returned=self.beforeFocus.call(self,event);if(returned===false)return self;$('div.qtip[qtip]').not(self.elements.tooltip).each(function()
{if($(this).qtip('api').status.rendered===true)
{elemIndex=parseInt($(this).css('z-index'));if(typeof elemIndex=='number'&&elemIndex>-1)
$(this).css({zIndex:parseInt($(this).css('z-index'))-1});$(this).qtip('api').status.focused=false;}})
self.elements.tooltip.css({zIndex:newIndex});self.status.focused=true;self.onFocus.call(self,event);$.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.EVENT_FOCUSED,'focus');};return self;},disable:function(state)
{if(!self.status.rendered)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.TOOLTIP_NOT_RENDERED,'disable');if(state)
{if(!self.status.disabled)
{self.status.disabled=true;$.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.EVENT_DISABLED,'disable');}
else $.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.TOOLTIP_ALREADY_DISABLED,'disable');}
else
{if(self.status.disabled)
{self.status.disabled=false;$.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.EVENT_ENABLED,'disable');}
else $.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.TOOLTIP_ALREADY_ENABLED,'disable');};return self;},destroy:function()
{var i,returned,interfaces;returned=self.beforeDestroy.call(self);if(returned===false)return self;if(self.status.rendered)
{self.options.show.when.target.unbind('mousemove.qtip',self.updatePosition);self.options.show.when.target.unbind('mouseout.qtip',self.hide);self.options.show.when.target.unbind(self.options.show.when.event+'.qtip');self.options.hide.when.target.unbind(self.options.hide.when.event+'.qtip');self.elements.tooltip.unbind(self.options.hide.when.event+'.qtip');self.elements.tooltip.unbind('mouseover.qtip',self.focus);self.elements.tooltip.remove();}
else self.options.show.when.target.unbind(self.options.show.when.event+'.qtip-create');if(typeof self.elements.target.data('qtip')=='object')
{interfaces=self.elements.target.data('qtip').interfaces;if(typeof interfaces=='object'&&interfaces.length>0)
{for(i=0;i<interfaces.length-1;i++)
if(interfaces[i].id==self.id)interfaces.splice(i,1)}}
delete $.fn.qtip.interfaces[self.id];if(typeof interfaces=='object'&&interfaces.length>0)
self.elements.target.data('qtip').current=interfaces.length-1;else
self.elements.target.removeData('qtip');self.onDestroy.call(self);$.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.EVENT_DESTROYED,'destroy');return self.elements.target},getPosition:function()
{var show,offset;if(!self.status.rendered)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.TOOLTIP_NOT_RENDERED,'getPosition');show=(self.elements.tooltip.css('display')!=='none')?false:true;if(show)self.elements.tooltip.css({visiblity:'hidden'}).show();offset=self.elements.tooltip.offset();if(show)self.elements.tooltip.css({visiblity:'visible'}).hide();return offset;},getDimensions:function()
{var show,dimensions;if(!self.status.rendered)
return $.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.TOOLTIP_NOT_RENDERED,'getDimensions');show=(!self.elements.tooltip.is(':visible'))?true:false;if(show)self.elements.tooltip.css({visiblity:'hidden'}).show();dimensions={height:self.elements.tooltip.outerHeight(),width:self.elements.tooltip.outerWidth()};if(show)self.elements.tooltip.css({visiblity:'visible'}).hide();return dimensions;}});};function construct()
{var self,adjust,content,url,data,method,tempLength;self=this;self.beforeRender.call(self);self.status.rendered=true;self.elements.tooltip='<div qtip="'+self.id+'" '+'class="qtip '+(self.options.style.classes.tooltip||self.options.style)+'"'+'style="display:none; -moz-border-radius:0; -webkit-border-radius:0; border-radius:0;'+'position:'+self.options.position.type+';">'+'  <div class="qtip-wrapper" style="position:relative; overflow:hidden; text-align:left;">'+'    <div class="qtip-contentWrapper" style="overflow:hidden;">'+'       <div class="qtip-content '+self.options.style.classes.content+'"></div>'+'</div></div></div>';self.elements.tooltip=$(self.elements.tooltip);self.elements.tooltip.appendTo(self.options.position.container)
self.elements.tooltip.data('qtip',{current:0,interfaces:[self]});self.elements.wrapper=self.elements.tooltip.children('div:first');self.elements.contentWrapper=self.elements.wrapper.children('div:first').css({background:self.options.style.background});self.elements.content=self.elements.contentWrapper.children('div:first').css(jQueryStyle(self.options.style));if($.browser.msie)self.elements.wrapper.add(self.elements.content).css({zoom:1});if(self.options.hide.when.event=='unfocus')self.elements.tooltip.attr('unfocus',true);if(typeof self.options.style.width.value=='number')self.updateWidth();if($('<canvas>').get(0).getContext||$.browser.msie)
{if(self.options.style.border.radius>0)
createBorder.call(self);else
self.elements.contentWrapper.css({border:self.options.style.border.width+'px solid '+self.options.style.border.color});if(self.options.style.tip.corner!==false)
createTip.call(self);}
else
{self.elements.contentWrapper.css({border:self.options.style.border.width+'px solid '+self.options.style.border.color});self.options.style.border.radius=0;self.options.style.tip.corner=false;$.fn.qtip.log.error.call(self,2,$.fn.qtip.constants.CANVAS_VML_NOT_SUPPORTED,'render');};if((typeof self.options.content.text=='string'&&self.options.content.text.length>0)||(self.options.content.text.jquery&&self.options.content.text.length>0))
content=self.options.content.text;else if(typeof self.elements.target.attr('title')=='string'&&self.elements.target.attr('title').length>0)
{content=self.elements.target.attr('title').replace("\\n",'<br />');self.elements.target.attr('title','');}
else if(typeof self.elements.target.attr('alt')=='string'&&self.elements.target.attr('alt').length>0)
{content=self.elements.target.attr('alt').replace("\\n",'<br />');self.elements.target.attr('alt','');}
else
{content=' ';$.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.NO_VALID_CONTENT,'render');};if(self.options.content.title.text!==false)createTitle.call(self);self.updateContent(content);assignEvents.call(self);if(self.options.show.ready===true)self.show();if(self.options.content.url!==false)
{url=self.options.content.url;data=self.options.content.data;method=self.options.content.method||'get';self.loadContent(url,data,method);};self.onRender.call(self);$.fn.qtip.log.error.call(self,1,$.fn.qtip.constants.EVENT_RENDERED,'render');};function createBorder()
{var self,i,width,radius,color,coordinates,containers,size,betweenWidth,betweenCorners,borderTop,borderBottom,borderCoord,sideWidth,vertWidth;self=this;self.elements.wrapper.find('.qtip-borderBottom, .qtip-borderTop').remove();width=self.options.style.border.width;radius=self.options.style.border.radius;color=self.options.style.border.color||self.options.style.tip.color;coordinates=calculateBorders(radius);containers={};for(i in coordinates)
{containers[i]='<div rel="'+i+'" style="'+((i.search(/Left/)!==-1)?'left':'right')+':0; '+'position:absolute; height:'+radius+'px; width:'+radius+'px; overflow:hidden; line-height:0.1px; font-size:1px">';if($('<canvas>').get(0).getContext)
containers[i]+='<canvas height="'+radius+'" width="'+radius+'" style="vertical-align: top"></canvas>';else if($.browser.msie)
{size=radius*2+3;containers[i]+='<v:arc stroked="false" fillcolor="'+color+'" startangle="'+coordinates[i][0]+'" endangle="'+coordinates[i][1]+'" '+'style="width:'+size+'px; height:'+size+'px; margin-top:'+((i.search(/bottom/)!==-1)?-2:-1)+'px; '+'margin-left:'+((i.search(/Right/)!==-1)?coordinates[i][2]-3.5:-1)+'px; '+'vertical-align:top; display:inline-block; behavior:url(#default#VML)"></v:arc>';};containers[i]+='</div>';};betweenWidth=self.getDimensions().width-(Math.max(width,radius)*2);betweenCorners='<div class="qtip-betweenCorners" style="height:'+radius+'px; width:'+betweenWidth+'px; '+'overflow:hidden; background-color:'+color+'; line-height:0.1px; font-size:1px;">';borderTop='<div class="qtip-borderTop" dir="ltr" style="height:'+radius+'px; '+'margin-left:'+radius+'px; line-height:0.1px; font-size:1px; padding:0;">'+
containers['topLeft']+containers['topRight']+betweenCorners;self.elements.wrapper.prepend(borderTop);borderBottom='<div class="qtip-borderBottom" dir="ltr" style="height:'+radius+'px; '+'margin-left:'+radius+'px; line-height:0.1px; font-size:1px; padding:0;">'+
containers['bottomLeft']+containers['bottomRight']+betweenCorners;self.elements.wrapper.append(borderBottom);if($('<canvas>').get(0).getContext)
{self.elements.wrapper.find('canvas').each(function()
{borderCoord=coordinates[$(this).parent('[rel]:first').attr('rel')];drawBorder.call(self,$(this),borderCoord,radius,color);})}
else if($.browser.msie)self.elements.tooltip.append('<v:image style="behavior:url(#default#VML);"></v:image>');sideWidth=Math.max(radius,(radius+(width-radius)))
vertWidth=Math.max(width-radius,0);self.elements.contentWrapper.css({border:'0px solid '+color,borderWidth:vertWidth+'px '+sideWidth+'px'})};function drawBorder(canvas,coordinates,radius,color)
{var context=canvas.get(0).getContext('2d');context.fillStyle=color;context.beginPath();context.arc(coordinates[0],coordinates[1],radius,0,Math.PI*2,false);context.fill();};function createTip(corner)
{var self,color,coordinates,coordsize,path;self=this;if(self.elements.tip!==null)self.elements.tip.remove();color=self.options.style.tip.color||self.options.style.border.color;if(self.options.style.tip.corner===false)return;else if(!corner)corner=self.options.style.tip.corner;coordinates=calculateTip(corner,self.options.style.tip.size.width,self.options.style.tip.size.height);self.elements.tip='<div class="'+self.options.style.classes.tip+'" dir="ltr" rel="'+corner+'" style="position:absolute; '+'height:'+self.options.style.tip.size.height+'px; width:'+self.options.style.tip.size.width+'px; '+'margin:0 auto; line-height:0.1px; font-size:1px;">';if($('<canvas>').get(0).getContext)
self.elements.tip+='<canvas height="'+self.options.style.tip.size.height+'" width="'+self.options.style.tip.size.width+'"></canvas>';else if($.browser.msie)
{coordsize=self.options.style.tip.size.width+','+self.options.style.tip.size.height;path='m'+coordinates[0][0]+','+coordinates[0][1];path+=' l'+coordinates[1][0]+','+coordinates[1][1];path+=' '+coordinates[2][0]+','+coordinates[2][1];path+=' xe';self.elements.tip+='<v:shape fillcolor="'+color+'" stroked="false" filled="true" path="'+path+'" coordsize="'+coordsize+'" '+'style="width:'+self.options.style.tip.size.width+'px; height:'+self.options.style.tip.size.height+'px; '+'line-height:0.1px; display:inline-block; behavior:url(#default#VML); '+'vertical-align:'+((corner.search(/top/)!==-1)?'bottom':'top')+'"></v:shape>';self.elements.tip+='<v:image style="behavior:url(#default#VML);"></v:image>';self.elements.contentWrapper.css('position','relative');};self.elements.tooltip.prepend(self.elements.tip+'</div>');self.elements.tip=self.elements.tooltip.find('.'+self.options.style.classes.tip).eq(0);if($('<canvas>').get(0).getContext)
drawTip.call(self,self.elements.tip.find('canvas:first'),coordinates,color);if(corner.search(/top/)!==-1&&$.browser.msie&&parseInt($.browser.version.charAt(0))===6)
self.elements.tip.css({marginTop:-4});positionTip.call(self,corner);};function drawTip(canvas,coordinates,color)
{var context=canvas.get(0).getContext('2d');context.fillStyle=color;context.beginPath();context.moveTo(coordinates[0][0],coordinates[0][1]);context.lineTo(coordinates[1][0],coordinates[1][1]);context.lineTo(coordinates[2][0],coordinates[2][1]);context.fill();};function positionTip(corner)
{var self,ieAdjust,paddingCorner,paddingSize,newMargin;self=this;if(self.options.style.tip.corner===false||!self.elements.tip)return;if(!corner)corner=self.elements.tip.attr('rel');ieAdjust=positionAdjust=($.browser.msie)?1:0;self.elements.tip.css(corner.match(/left|right|top|bottom/)[0],0);if(corner.search(/top|bottom/)!==-1)
{if($.browser.msie)
{if(parseInt($.browser.version.charAt(0))===6)
positionAdjust=(corner.search(/top/)!==-1)?-3:1;else
positionAdjust=(corner.search(/top/)!==-1)?1:2;};if(corner.search(/Middle/)!==-1)
self.elements.tip.css({left:'50%',marginLeft:-(self.options.style.tip.size.width/2)});else if(corner.search(/Left/)!==-1)
self.elements.tip.css({left:self.options.style.border.radius-ieAdjust});else if(corner.search(/Right/)!==-1)
self.elements.tip.css({right:self.options.style.border.radius+ieAdjust});if(corner.search(/top/)!==-1)
self.elements.tip.css({top:-positionAdjust});else
self.elements.tip.css({bottom:positionAdjust});}
else if(corner.search(/left|right/)!==-1)
{if($.browser.msie)
positionAdjust=(parseInt($.browser.version.charAt(0))===6)?1:((corner.search(/left/)!==-1)?1:2);if(corner.search(/Middle/)!==-1)
self.elements.tip.css({top:'50%',marginTop:-(self.options.style.tip.size.height/2)});else if(corner.search(/Top/)!==-1)
self.elements.tip.css({top:self.options.style.border.radius-ieAdjust});else if(corner.search(/Bottom/)!==-1)
self.elements.tip.css({bottom:self.options.style.border.radius+ieAdjust});if(corner.search(/left/)!==-1)
self.elements.tip.css({left:-positionAdjust});else
self.elements.tip.css({right:positionAdjust});};paddingCorner='padding-'+corner.match(/left|right|top|bottom/)[0];paddingSize=self.options.style.tip.size[(paddingCorner.search(/left|right/)!==-1)?'width':'height'];self.elements.tooltip.css('padding',0);self.elements.tooltip.css(paddingCorner,paddingSize);if($.browser.msie&&parseInt($.browser.version.charAt(0))==6)
{newMargin=parseInt(self.elements.tip.css('margin-top'))||0;newMargin+=parseInt(self.elements.content.css('margin-top'))||0;self.elements.tip.css({marginTop:newMargin});};};function createTitle()
{var self=this;if(self.elements.title!==null)self.elements.title.remove();self.elements.title=$('<div class="'+self.options.style.classes.title+'">').css(jQueryStyle(self.options.style.title,true)).css({zoom:($.browser.msie)?1:0}).prependTo(self.elements.contentWrapper);if(self.options.content.title.text)self.updateTitle.call(self,self.options.content.title.text);if(self.options.content.title.button!==false&&typeof self.options.content.title.button=='string')
{self.elements.button=$('<a class="'+self.options.style.classes.button+'" style="float:right; position: relative"></a>').css(jQueryStyle(self.options.style.button,true)).html(self.options.content.title.button).prependTo(self.elements.title).click(function(event){if(!self.status.disabled)self.hide(event)});};};function assignEvents()
{var self,showTarget,hideTarget,inactiveEvents;self=this;showTarget=self.options.show.when.target;hideTarget=self.options.hide.when.target;if(self.options.hide.fixed)hideTarget=hideTarget.add(self.elements.tooltip);if(self.options.hide.when.event=='inactive')
{inactiveEvents=['click','dblclick','mousedown','mouseup','mousemove','mouseout','mouseenter','mouseleave','mouseover'];function inactiveMethod(event)
{if(self.status.disabled===true)return;clearTimeout(self.timers.inactive);self.timers.inactive=setTimeout(function()
{$(inactiveEvents).each(function()
{hideTarget.unbind(this+'.qtip-inactive');self.elements.content.unbind(this+'.qtip-inactive');});self.hide(event);},self.options.hide.delay);};}
else if(self.options.hide.fixed===true)
{self.elements.tooltip.bind('mouseover.qtip',function()
{if(self.status.disabled===true)return;clearTimeout(self.timers.hide);});};function showMethod(event)
{if(self.status.disabled===true)return;if(self.options.hide.when.event=='inactive')
{$(inactiveEvents).each(function()
{hideTarget.bind(this+'.qtip-inactive',inactiveMethod);self.elements.content.bind(this+'.qtip-inactive',inactiveMethod);});inactiveMethod();};clearTimeout(self.timers.show);clearTimeout(self.timers.hide);self.timers.show=setTimeout(function(){self.show(event);},self.options.show.delay);};function hideMethod(event)
{if(self.status.disabled===true)return;if(self.options.hide.fixed===true&&self.options.hide.when.event.search(/mouse(out|leave)/i)!==-1&&$(event.relatedTarget).parents('div.qtip[qtip]').length>0)
{event.stopPropagation();event.preventDefault();clearTimeout(self.timers.hide);return false;};clearTimeout(self.timers.show);clearTimeout(self.timers.hide);self.elements.tooltip.stop(true,true);self.timers.hide=setTimeout(function(){self.hide(event);},self.options.hide.delay);};if((self.options.show.when.target.add(self.options.hide.when.target).length===1&&self.options.show.when.event==self.options.hide.when.event&&self.options.hide.when.event!=='inactive')||self.options.hide.when.event=='unfocus')
{self.cache.toggle=0;showTarget.bind(self.options.show.when.event+'.qtip',function(event)
{if(self.cache.toggle==0)showMethod(event);else hideMethod(event);});}
else
{showTarget.bind(self.options.show.when.event+'.qtip',showMethod);if(self.options.hide.when.event!=='inactive')
hideTarget.bind(self.options.hide.when.event+'.qtip',hideMethod);};if(self.options.position.type.search(/(fixed|absolute)/)!==-1)
self.elements.tooltip.bind('mouseover.qtip',self.focus);if(self.options.position.target==='mouse'&&self.options.position.type!=='static')
{showTarget.bind('mousemove.qtip',function(event)
{self.cache.mouse={x:event.pageX,y:event.pageY};if(self.status.disabled===false&&self.options.position.adjust.mouse===true&&self.options.position.type!=='static'&&self.elements.tooltip.css('display')!=='none')
self.updatePosition(event);});};};function screenAdjust(position,target,tooltip)
{var self,adjustedPosition,adjust,newCorner,overflow,corner;self=this;if(tooltip.corner=='center')return target.position
adjustedPosition=$.extend({},position);newCorner={x:false,y:false};overflow={left:(adjustedPosition.left<$.fn.qtip.cache.screen.scroll.left),right:(adjustedPosition.left+tooltip.dimensions.width+2>=$.fn.qtip.cache.screen.width+$.fn.qtip.cache.screen.scroll.left),top:(adjustedPosition.top<$.fn.qtip.cache.screen.scroll.top),bottom:(adjustedPosition.top+tooltip.dimensions.height+2>=$.fn.qtip.cache.screen.height+$.fn.qtip.cache.screen.scroll.top)};adjust={left:(overflow.left&&(tooltip.corner.search(/right/i)!=-1||(tooltip.corner.search(/right/i)==-1&&!overflow.right))),right:(overflow.right&&(tooltip.corner.search(/left/i)!=-1||(tooltip.corner.search(/left/i)==-1&&!overflow.left))),top:(overflow.top&&tooltip.corner.search(/top/i)==-1),bottom:(overflow.bottom&&tooltip.corner.search(/bottom/i)==-1)};if(adjust.left)
{if(self.options.position.target!=='mouse')
adjustedPosition.left=target.position.left+target.dimensions.width;else
adjustedPosition.left=self.cache.mouse.x
newCorner.x='Left';}
else if(adjust.right)
{if(self.options.position.target!=='mouse')
adjustedPosition.left=target.position.left-tooltip.dimensions.width;else
adjustedPosition.left=self.cache.mouse.x-tooltip.dimensions.width;newCorner.x='Right';};if(adjust.top)
{if(self.options.position.target!=='mouse')
adjustedPosition.top=target.position.top+target.dimensions.height;else
adjustedPosition.top=self.cache.mouse.y
newCorner.y='top';}
else if(adjust.bottom)
{if(self.options.position.target!=='mouse')
adjustedPosition.top=target.position.top-tooltip.dimensions.height;else
adjustedPosition.top=self.cache.mouse.y-tooltip.dimensions.height;newCorner.y='bottom';};if(adjustedPosition.left<0)
{adjustedPosition.left=position.left;newCorner.x=false;};if(adjustedPosition.top<0)
{adjustedPosition.top=position.top;newCorner.y=false;};if(self.options.style.tip.corner!==false)
{adjustedPosition.corner=new String(tooltip.corner);if(newCorner.x!==false)adjustedPosition.corner=adjustedPosition.corner.replace(/Left|Right|Middle/,newCorner.x);if(newCorner.y!==false)adjustedPosition.corner=adjustedPosition.corner.replace(/top|bottom/,newCorner.y);if(adjustedPosition.corner!==self.elements.tip.attr('rel'))
createTip.call(self,adjustedPosition.corner);};return adjustedPosition;};function jQueryStyle(style,sub)
{var styleObj,i;styleObj=$.extend(true,{},style);for(i in styleObj)
{if(sub===true&&i.search(/(tip|classes)/i)!==-1)
delete styleObj[i];else if(!sub&&i.search(/(width|border|tip|title|classes|user)/i)!==-1)
delete styleObj[i];};return styleObj;};function sanitizeStyle(style)
{if(typeof style.tip!=='object')style.tip={corner:style.tip};if(typeof style.tip.size!=='object')style.tip.size={width:style.tip.size,height:style.tip.size};if(typeof style.border!=='object')style.border={width:style.border};if(typeof style.width!=='object')style.width={value:style.width};if(typeof style.width.max=='string')style.width.max=parseInt(style.width.max.replace(/([0-9]+)/i,"$1"));if(typeof style.width.min=='string')style.width.min=parseInt(style.width.min.replace(/([0-9]+)/i,"$1"));if(typeof style.tip.size.x=='number')
{style.tip.size.width=style.tip.size.x;delete style.tip.size.x;};if(typeof style.tip.size.y=='number')
{style.tip.size.height=style.tip.size.y;delete style.tip.size.y;};return style;};function buildStyle()
{var self,i,styleArray,styleExtend,finalStyle,ieAdjust;self=this;styleArray=[true,{}];for(i=0;i<arguments.length;i++)
styleArray.push(arguments[i]);styleExtend=[$.extend.apply($,styleArray)];while(typeof styleExtend[0].name=='string')
{styleExtend.unshift(sanitizeStyle($.fn.qtip.styles[styleExtend[0].name]));};styleExtend.unshift(true,{classes:{tooltip:'qtip-'+(arguments[0].name||'defaults')}},$.fn.qtip.styles.defaults);finalStyle=$.extend.apply($,styleExtend);ieAdjust=($.browser.msie)?1:0;finalStyle.tip.size.width+=ieAdjust;finalStyle.tip.size.height+=ieAdjust;if(finalStyle.tip.size.width%2>0)finalStyle.tip.size.width+=1;if(finalStyle.tip.size.height%2>0)finalStyle.tip.size.height+=1;if(finalStyle.tip.corner===true)
finalStyle.tip.corner=(self.options.position.corner.tooltip==='center')?false:self.options.position.corner.tooltip;return finalStyle;};function calculateTip(corner,width,height)
{var tips={bottomRight:[[0,0],[width,height],[width,0]],bottomLeft:[[0,0],[width,0],[0,height]],topRight:[[0,height],[width,0],[width,height]],topLeft:[[0,0],[0,height],[width,height]],topMiddle:[[0,height],[width/2,0],[width,height]],bottomMiddle:[[0,0],[width,0],[width/2,height]],rightMiddle:[[0,0],[width,height/2],[0,height]],leftMiddle:[[width,0],[width,height],[0,height/2]]};tips.leftTop=tips.bottomRight;tips.rightTop=tips.bottomLeft;tips.leftBottom=tips.topRight;tips.rightBottom=tips.topLeft;return tips[corner];};function calculateBorders(radius)
{var borders;if($('<canvas>').get(0).getContext)
{borders={topLeft:[radius,radius],topRight:[0,radius],bottomLeft:[radius,0],bottomRight:[0,0]};}
else if($.browser.msie)
{borders={topLeft:[-90,90,0],topRight:[-90,90,-radius],bottomLeft:[90,270,0],bottomRight:[90,270,-radius]};};return borders;};function bgiframe()
{var self,html,dimensions;self=this;dimensions=self.getDimensions();html='<iframe class="qtip-bgiframe" frameborder="0" tabindex="-1" src="javascript:false" '+'style="display:block; position:absolute; z-index:-1; filter:alpha(opacity=\'0\'); border: 1px solid red; '+'height:'+dimensions.height+'px; width:'+dimensions.width+'px" />';self.elements.bgiframe=self.elements.wrapper.prepend(html).children('.qtip-bgiframe:first');};$(document).ready(function()
{$.fn.qtip.cache={screen:{scroll:{left:$(window).scrollLeft(),top:$(window).scrollTop()},width:$(window).width(),height:$(window).height()}};var adjustTimer;$(window).bind('resize scroll',function(event)
{clearTimeout(adjustTimer);adjustTimer=setTimeout(function()
{if(event.type==='scroll')
$.fn.qtip.cache.screen.scroll={left:$(window).scrollLeft(),top:$(window).scrollTop()};else
{$.fn.qtip.cache.screen.width=$(window).width();$.fn.qtip.cache.screen.height=$(window).height();};for(i=0;i<$.fn.qtip.interfaces.length;i++)
{var api=$.fn.qtip.interfaces[i];if(api&&api.status.rendered===true&&(api.options.position.type!=='static'||api.options.position.adjust.scroll&&event.type==='scroll'||api.options.position.adjust.resize&&event.type==='resize'))
{api.updatePosition(event,true);}};},100);})
$(document).bind('mousedown.qtip',function(event)
{if($(event.target).parents('div.qtip').length===0)
{$('.qtip[unfocus]').each(function()
{var api=$(this).qtip("api");if($(this).is(':visible')&&!api.status.disabled&&$(event.target).add(api.elements.target).length>1)
api.hide(event);})};})});$.fn.qtip.interfaces=[]
$.fn.qtip.log={error:function(){return this;}};$.fn.qtip.constants={};$.fn.qtip.defaults={content:{prerender:false,text:false,url:false,data:null,title:{text:false,button:false}},position:{target:false,corner:{target:'bottomRight',tooltip:'topLeft'},adjust:{x:0,y:0,mouse:true,screen:false,scroll:true,resize:true},type:'absolute',container:false},show:{when:{target:false,event:'mouseover'},effect:{type:'fade',length:100},delay:140,solo:false,ready:false},hide:{when:{target:false,event:'mouseout'},effect:{type:'fade',length:100},delay:0,fixed:false},api:{beforeRender:function(){},onRender:function(){},beforePositionUpdate:function(){},onPositionUpdate:function(){},beforeShow:function(){},onShow:function(){},beforeHide:function(){},onHide:function(){},beforeContentUpdate:function(){},onContentUpdate:function(){},beforeContentLoad:function(){},onContentLoad:function(){},beforeTitleUpdate:function(){},onTitleUpdate:function(){},beforeDestroy:function(){},onDestroy:function(){},beforeFocus:function(){},onFocus:function(){}}};$.fn.qtip.styles={defaults:{background:'white',color:'#111',overflow:'hidden',textAlign:'left',width:{min:0,max:250},padding:'5px 9px',border:{width:1,radius:0,color:'#d3d3d3'},tip:{corner:false,color:false,size:{width:13,height:13},opacity:1},title:{background:'#e1e1e1',fontWeight:'bold',padding:'7px 12px'},button:{cursor:'pointer'},classes:{target:'',tip:'qtip-tip',title:'qtip-title',button:'qtip-button',content:'qtip-content',active:'qtip-active'}},cream:{border:{width:3,radius:0,color:'#F9E98E'},title:{background:'#F0DE7D',color:'#A27D35'},background:'#FBF7AA',color:'#A27D35',classes:{tooltip:'qtip-cream'}},light:{border:{width:3,radius:0,color:'#E2E2E2'},title:{background:'#f1f1f1',color:'#454545'},background:'white',color:'#454545',classes:{tooltip:'qtip-light'}},dark:{border:{width:3,radius:0,color:'#303030'},title:{background:'#404040',color:'#f3f3f3'},background:'#505050',color:'#f3f3f3',classes:{tooltip:'qtip-dark'}},red:{border:{width:3,radius:0,color:'#CE6F6F'},title:{background:'#f28279',color:'#9C2F2F'},background:'#F79992',color:'#9C2F2F',classes:{tooltip:'qtip-red'}},green:{border:{width:3,radius:0,color:'#A9DB66'},title:{background:'#b9db8c',color:'#58792E'},background:'#CDE6AC',color:'#58792E',classes:{tooltip:'qtip-green'}},blue:{border:{width:3,radius:0,color:'#ADD9ED'},title:{background:'#D0E9F5',color:'#5E99BD'},background:'#E5F6FE',color:'#4D9FBF',classes:{tooltip:'qtip-blue'}}};})(jQuery);
/**
   Class for editing maps
   @requires FeatureFactory
*/
var map_problem_severity_description = { '-1':"Low", '0':"Normal", '1':"High"};
var map_problem_type_description = {'*Origin':'Problem Origin', '-all':'All', '-scan':'Scan', '-merger':'Merger', '*Scan':'Scan Problems', '1':"Intersecting roads", '2':"Adjacent roads", '3':"Road contained in another road", '4':"Road shorter than 10 meters", '5':"Road with no GPS points", '6':"Unconnected road", '7':"Non drivable road", '8':"Duplicate road", '9':"Duplicate road", '10':"Not enough allowed turns", '11':"Roads intersecting multiple times", '12': "Problematic turn", '13':"Problematic node in roundabout", '21':"Road nearly touches junction", '22':"Road nearly touches road", '26':"Major road not connected on one side", '30':"Very short road", '31':"Touching nodes", '88':"Duplicate road", '999':"Suspicious Ramp", '*Merger':'Merger Problems', '50':'Unable to merge road geometry', '51':'Unable to connect segments', '52':'Missing road when GPX not in valid mode', '53':'Missing road attr', '54':'Missing street attr', '55':'Incorrect road params(speed/length)', '56':'During(??)', '57':'Skipped connect due to insufficient quality', '58':'Colliding alternate resolve paths', '59':'Unmatched resolve paths', '60':'Route Disconnected', '67':'Intermediate Connection'};
var map_problems_privileged_types = {'*Origin':1, '-all':1, '-merger':1, '*Merger':1, '50':1, '51':1, '52':1, '53':1, '54':1, '55':1, '56':1, '57':1, '58':1, '59':1, '60':1, '67':1};
var map_problem_priority_icon = {'1':"map_problem_circle_red.gif", '0':"map_problem_circle_orange.gif", '-1':"map_problem_circle_yellow.gif"};
var currently_marked_map_problem = {}; // BAD implementation, but otherwise have to change a lot in the flow
var currently_marked_gps_point = {}; // BAD implementation, but otherwise have to change a lot in the flow
var logged_in_user_id = '';
//var is_user_area_manager = false;
var logged_in_user_data = {};
var chosen_problem_type = '';
var lastKnownCityInViewport = '';
var lastKnownStateInViewport = '';
var isInFullScreenMode = 0;
var defaultContentWrapperWidth = $("#content_wrapper").width();
var defaultCartoucheHeight = $("#cartouche").height();
var simpleDegreesToMetersRatio = 111240;
var min_refresh_problems_zoom = 3;
var max_refresh_problems_zoom = 9;

var map_info;
var g_map;
var routingClickStatus = 0;
var g_org_layers;
g_on_logged_out = do_signin_page;


CartouchePermalink = OpenLayers.Class(OpenLayers.Control.Permalink, {
/*
   	initialize: function(options) {
   	    OpenLayers.Control.Permalink.prototype.initialize.apply(this, [options]);
   	},
*/

    updateLink: function() {

        var href = this.base;
        if (href.indexOf('?') != -1) {
            href = href.substring( 0, href.indexOf('?') );
        }
	var params = this.createParams();
	//	params.super = 'yes';
	var segsNum = 0;
	var nodesNum = 0;
	var problemsNum = 0;
	var pointsNum = 0;
	for (var i in params) {
	    if (i == 'archive_user_id' || i == 'archive_session_id' || i == 'bbox' || i == 'BBOX' || i.substring(0, 4) == 'node' || i.substring(0, 3) == 'seg' || i.substring(0, 11) == 'map_problem' || i.substring(0, 5) == 'gps_p') delete params[i];
	}
	var additionalString = "";
	for(var i in g_cartouche.featureQueue){
	    var type = g_cartouche.featureQueue[i].split(".")[0];
	    var id = g_cartouche.featureQueue[i].split(".")[1];
	    if (type == "roads") {
		segsNum++;
		//		params['seg_' + segsNum] = id;
		additionalString += '&seg-' + segsNum + '=' + id;
	    }
	    if (type == "nodes") {
		nodesNum++;
		//		params['node_' + nodesNum] = id;
		additionalString += '&node-' + nodesNum + '=' + id;
	    }
	    if (type == "map_problems") {
		problemsNum++;
		//		params['map_problem_' + problemsNum] = id;
		additionalString += '&map_problem-' + problemsNum + '=' + id;
	    }
	      if (type == "update_request") {
//		problemsNum++;
		//		params['map_problem_' + problemsNum] = id;
		additionalString += '&update_request-' + update_request + '=' + id;
	    }
	    if (type == "gps_points") {
		pointsNum++;
		//		params['node_' + nodesNum] = id;
		additionalString += '&gps_point-' + pointsNum + '=' + id;
	    }
	}
        href += '?' + OpenLayers.Util.getParameterString(params) + additionalString;
        this.element.href = href;
    }, 


 	createParams: function(center, zoom, layers) {
	
	var params = OpenLayers.Util.getParameters(this.base);
	params.zoom = zoom || this.map.getZoom();
	 center = center || this.map.getCenter();
	 if(center==null)
			return params;
	 //lon,lat
	var lat = center.lat;
	var lon = center.lon;

	if (this.displayProjection) {
	var mapPosition = OpenLayers.Projection.transform(
	{ x: lon, y: lat },
	this.map.getProjectionObject(),
	this.displayProjection );
	lon = mapPosition.x;
	lat = mapPosition.y;
	}
	params.lat = Math.round(lat*100000)/100000;
	params.lon = Math.round(lon*100000)/100000;
	
	
	/*
	
 	    var segsNum = 0;
 	    for(var feature in this.selectedFeatures){
 		var type = feature.split(".")[0];
 		var id = feature.split(".")[1];
 		segsNum++;
 		if (type == "roads") {
 		    params['seg' + segsNum] = id;
		}
 	    }
	    */
	    //layers
	layers = layers || this.map.layers;
	params.layers = '';
	
	//layers[0].params.LAYERS
	//var layersBaseOrder=new Array('aerial','shade','fleet','speed_cams','restrictions','update_requests','street_ranges','users_notes','map_problems','recent_gps_points','landmarks','gps_points','unknown_roads','line_roads','roads','managers');
	
	if(g_org_layers)
	for (var j=0;j<g_org_layers.length;j++)
	{
		var layer =null;
		for (var i=0 ; i<layers.length; i++) 
		{
			layer = layers[i];
			
			if (layer.params && layer.id==g_org_layers[j].id)
				break;
		}
		if (layer.isBaseLayer) 
					params.layers += (layer == this.map.baseLayer) ? "B" : "0";
			
		if (layer!=null && !layer.isBaseLayer)
					params.layers += (layer.getVisibility()) ? "T" : "F";
		
	
	}
	/*
	for (var i=0, len=layers.length; i<len; i++) {
		var layer = layers[i];

			if (layer.isBaseLayer) {
				params.layers += (layer == this.map.baseLayer) ? "B" : "0";
			} else {
				params.layers += (layer.getVisibility()) ? "T" : "F";
			}
	}
*/

return params;

 	    
		
 	}
	//CLASS_NAME: "CartouchePermalink"

   }
   );


function Cartouche(init_on_login){
		
    if(!init_on_login){
	this._init();
	return;
    }
	
    this.setEditMode("select");
    var tc = this;
    Login.isLoggedIn(function(is_logged_in, message, user_id, _logged_in_user_data){

	    tc.initSimplifiedPanel(message);
	    logged_in_user_data = _logged_in_user_data;
	    logged_in_user_id = (user_id ? user_id : '');
		
	    if(is_logged_in){
		tc._init();
		return;
	    }
		
	    tc._init();
	    return;

	    $("#viewPanel").hide();
	    $("#layersPanel").hide();
	    tc._setToolsPanelContents("login_tools");
		
		
	    var login = function(){
		
		$("#editPanel .contents .error").fadeOut("slow");
		Login.formLogin("loginForm",function(result,message, user_id, _logged_in_user_data){
			logged_in_user_data = _logged_in_user_data;
			logged_in_user_id = (user_id ? user_id : '');
			tc.getOnViewChanged()();

			if(result){
			
			    $("#viewPanel").show();
			    $("#layersPanel").show();
			    tc._init();
				
			}
			else{
			    if($("#editPanel .contents .error").length==0)
				$("#editPanel .contents").prepend("<div class='error'>Login failed: "+message+"</div>");
			    else{
				
				
				$("#editPanel .contents .error").text("Login failed: "+message);
				$("#editPanel .contents .error").fadeIn("slow");
			    }
			}
		    });
		
	    }
		
	    $("#loginForm").keypress(function(e){
		    if(e.which==13){//enter key
			login();
			return false;
		    }
		});
		

	    $("#editPanel #submit").click(login);
			
	});
    
		
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.MAX_AERIAL_PHOTO_ZOOM = 20;
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._init = function(){
    
	var tc = this

	$.getJSON(url="/KART/map_info",callback=function(json){
	
		json.base_layer_type = "WMS";
		tc.map_info = json;
		var bounds = new OpenLayers.Bounds();
		bounds.extend(new OpenLayers.LonLat(json.left,json.top));
		bounds.extend(new OpenLayers.LonLat(json.right,json.bottom));
	
		var wms_servers = json.boom_wms_servers;
	    
		var gps_points_servers = json.boom_gps_points_servers;
		var wfs_server = json.boom_wfs_server;
		
		var edit_servers = json.edit_servers;
		var default_center = new OpenLayers.LonLat(lon=json.default_center.lon,lat=json.default_center.lat);
		
		if( extractParam("proj")=="3785" || json.projection=="EPSG:900913"){
			edit_servers = json.edit_servers_mercator;
			gps_points_servers = json.edit_servers_mercator;
			default_center.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
			tc._initMap(bounds,wms_servers,edit_servers,wfs_server,gps_points_servers, null,default_center);
		}else{
			$.getJSON(url="map-capabilities.json",callback=function(map_caps){
				tc._initMap(bounds,wms_servers,edit_servers,wfs_server,gps_points_servers, map_caps,default_center);
			});
		}
	});


	$("#form_route .input_end_from").after("<img onClick=\"g_cartouche.routingIconClicked(1)\" class=\"routing_icon\" id=\"routing_from_icon\" style=\"margin-top: -2px; padding: 2px; margin-left: 4px; float: left\" src=\"/images/from.gif\" width=\"20\"></img>");
	$("#form_route .input_end_to").after("<span class=\"from_to_separator\">&nbsp;</span>");
	$("#form_route .input_end_to").after("<img onClick=\"g_cartouche.routingIconClicked(2)\" class=\"routing_icon\" id=\"routing_to_icon\"  style=\"margin-top: -2px; padding: 2px; margin-left: 4px; float: left\" src=\"/images/to.gif\" width=\"20\"></img>");

	/*$("#englishLink").hover(function(){$(this).css("opacity",1);},function(){if ($("#franchLink").css("opacity")==1) $(this).css("opacity",0.3);});
	$("#franchLink").hover(function(){$(this).css("opacity",1);},function(){if ($("#englishLink").css("opacity")==1) $(this).css("opacity",0.3);});
    	$("#clang").show();*/
};
//-------------------------------------------------------------------------------------------------------------------	
Cartouche.prototype._initMap = function(bounds,wms_servers,edit_servers,wfs_server,gps_points_servers, map_capabilities,default_center){
    
    this.wfs_server = wfs_server;
    this.gps_points_servers = gps_points_servers;
  
    var options = {
	projection: new OpenLayers.Projection("EPSG:900913"),
	displayProjection: new OpenLayers.Projection("EPSG:4326"),
	units: "m",
	//numZoomLevels:18,
	//numZoomLevels:20,
	//numZoomLevels:12,
	numZoomLevels:10,
	controls: [
			new OpenLayers.Control.Attribution({displayClass:"attrib"})//,
			//new OpenLayers.Control.Graticule(),
			],
	maxResolution: 38.21851413574219,
	//maxResolution:152.87405654296876,
	maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34,
                                     20037508.34, 20037508.34)
     };


    if(map_capabilities){
	options = {
		projection: new OpenLayers.Projection("EPSG:4326"),
		numZoomLevels:10,
		controls: [new OpenLayers.Control.Attribution({displayClass:"attrib"})],
	//	maxResolution:.00034332275390625
		maxResolution:.00034332275390625
	}
    }
    
   this.map = new OpenLayers.Map($('#cartouche').get(0),options);

    this.initHotKeys();
    
    var layers = Layers.make(bounds,wms_servers,edit_servers,gps_points_servers, map_capabilities);
    this.layers_loading = 0;
    var tc = this;
    for(var i in layers){
		
	this._addLoadingIndication(layers[i]);
	this.map.addLayer(layers[i]);    
    }
		
	if(document.URL.indexOf("lat=") == -1 && document.URL.indexOf("lon=") == -1 /*&& document.URL.indexOf("zoom=") == -1*/){
		if(hasMapCookie())
			this.setMapPositionFromCookie();
		else
			this.map.setCenter(default_center);
	}
	
    this.edit_panel_contents_stack = [];

    var queryInd = document.createElement("div");
    $(queryInd).addClass("queryIndicator");
    this.map.viewPortDiv.appendChild(queryInd);
    
    this.featureQueue = [];
    this.selectedFeatures = {};
    this.featuresPopups = [];
    this.aux_split_road = "";                        
		

    // !!!!!!!!!!
    this.additionalMarkingsLayer = 
    new OpenLayers.Layer.WMS($("#additional_markings",Layers.mappingQ).text(), 
			     edit_servers, 
				{layers: 'additional_markings', format: 'image/png', transparent: "true",
				 _selected_segment_ids: "",
				 _selected_node_ids: "",
				 _selected_map_problem_id: ""
				},
				{alpha:true,visibility:false,buffer:2,singleTile:true, opacity:0.5} );
    
    this.map.addLayer(this.additionalMarkingsLayer);
    this.map.raiseLayer(this.additionalMarkingsLayer,100);
    this.additionalMarkingsLayer.setVisibility(false);
    //!!! !   !!!                 !!!!!!!!!!!!! !  !! !!!!! !!!!!!!! ! !!!

    this.featuresLayer = new OpenLayers.Layer.Vector("edit features");
    this.map.addLayer(this.featuresLayer);
    
    //        this.newFeaturesLayer = new OpenLayers.Layer.Vector("add features",{style:{strokeWidth:4,strokeColor: "#00ffff",strokeOpacity:0.8}});
    this.newFeaturesLayer = new OpenLayers.Layer.Vector("add features",{sssstyle:{strokeWidth:4,strokeColor: "#00ffff",strokeOpacity:0.8}});
    this.map.addLayer(this.newFeaturesLayer);
		
    this.markersLayer = new OpenLayers.Layer.Markers("locations");
    this.map.addLayer(this.markersLayer);
		
    this.gmlReports = new GmlReports(this.map);
		
    this._initMapControls();
    $(".olControlPermalink a").text($("#name_permalink").text());
		
		
    var overview_layer = new OpenLayers.Layer.WMS( "Overview", 
						   edit_servers,{layers: 'shade,roads', format: 'image/png'},{singleTile:true});
		
    var ovmap_options = {
	layers: [overview_layer],
	minRatio: 4,
	maxRatio: 8,
	resolutionFactor:5,
	size: new OpenLayers.Size(130, 90),
	mapOptions:{
		projection:options.projection,
		displayProjection:options.displayProjection,
		maxExtent:options.maxExtent
	}
    };
    
   
	var overview_control = new OpenLayers.Control.OverviewMap(ovmap_options);
	tc.map.addControl(overview_control);
	overview_control.maximizeControl();
		
		
    $(".olControlOverviewMapExtentRectangle").append("<div style='width:100%;height:100%;background-color:#fff000;'></div>");
    $(".olControlOverviewMapExtentRectangle div").fadeTo(0,0.3);
		
    //must be initialized after controls ...
    this._initPanels();
    this.factory = new FeatureFactory();
		
    this.updateToolsPanel();
		
    this.stillInformingMapViewChanged = false;
    this.map.events.register("moveend", this, this.mapMoveEnd);
    //this.map.events.register("zoomstart", this, this.mapZoomStart); - doesn't seem like this event exists...
    this.map.events.register("zoomend", this, this.mapZoomEnd);
    //    this.map.events.register("dragend", this, this.mapViewChanged);

    this.map.events.register("click", this, this.onclick);
		
		
    this.map.events.register("mouseover",this,function(e){
		
	    var lonlat = this.map.getLonLatFromViewPortPx(e.xy);
	    this.map.lastMouseLonlat = lonlat;
	    if (this.measurementControl.handler.line) this.measurementControl.measure(this.measurementControl.handler.line.geometry, "measurepartial");
		
	});
	
    this.getOnViewChanged()();//init all view control states
    this.map.events.register("moveend",this,this.getOnViewChanged());
		
		 
    //add marker
    var params = OpenLayers.Util.getParameters();
    if (params.marker == "true") {

		var point = new OpenLayers.LonLat(params.lon,  params.lat);
		if(tc.map.getProjection()=="EPSG:900913")
			point.transform(new OpenLayers.Projection("EPSG:4326"),this.map.getProjectionObject());

		this.markersLayer.addMarker(new OpenLayers.Marker(point));
    }


    // style the sketch fancy
    var sketchSymbolizers = {
	"Point": {
	    pointRadius: 4,
	    graphicName: "square",
	    fillColor: "white",
	    fillOpacity: 1,
	    strokeWidth: 1,
	    strokeOpacity: 1,
	    strokeColor: "#333333"
	},
	"Line": {
	    strokeWidth: 3,
	    strokeOpacity: 1,
	    strokeColor: "#666666",
	    strokeDashstyle: "dash"
	},
	"Polygon": {
	    strokeWidth: 2,
	    strokeOpacity: 1,
	    strokeColor: "#666666",
	    fillColor: "white",
	    fillOpacity: 0.3
	}
    };
    var style = new OpenLayers.Style();
    style.addRules([
		    new OpenLayers.Rule({symbolizer: sketchSymbolizers})
		    ]);
    var styleMap = new OpenLayers.StyleMap({"default": style});
		
    measureControls = {
	line: new OpenLayers.Control.Measure(
					     OpenLayers.Handler.Path, {
						 persist: true,
						 handlerOptions: {
						     layerOptions: {styleMap: styleMap}
						 }
					     }
					     ),
	polygon: new OpenLayers.Control.Measure(
						OpenLayers.Handler.Polygon, {
						    persist: true,
						    handlerOptions: {
							layerOptions: {styleMap: styleMap}
						    }
						}
						)
    };


	//    for(var key in measureControls) {
	this.measurementControl = measureControls['line'];
	    this.measurementControl.events.on({
			"measure": this.handleMeasurements,
			"measurepartial": this.handleMeasurements
			});
	this.measurementControl.handler.style = sketchSymbolizers.Line;
	    this.map.addControl(this.measurementControl);
	    //    }


	this.writeCookie();

	//var names = ['seg', 'seg_1', 'seg_2', 'seg_3', 'seg_4', 'seg_5', 'seg_6', 'seg_7', 'seg_8'];

	this.useUrlBBox(window.location.href);
	this.useUrlArchiveData(window.location.href);

	this.selectObjectsByUrl(window.location.href);


	this.nav_layer = new OpenLayers.Layer.Vector("routes");
	this.map.addLayer(this.nav_layer);


	g_map = this.map;
	g_map.markersLayer = this.markersLayer;
	g_map.map_info = this.map_info;

};

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.mapMoveEnd = function(event) {
    //    if (!this.mapZoomNotEnded)
    //	this.mapViewChanged();
}

//-------------------------------------------------------------------------------------------------------------------
/*Cartouche.prototype.mapZoomStart = function(event) {
    //    this.mapZoomNotEnded = true;
    
}*/

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.mapZoomEnd = function(event) {
    //    this.mapZoomNotEnded = false;
    //    this.mapViewChanged();	
	if($("#map_problems").hasClass("selectedLayer") && g_map.zoom>=min_refresh_problems_zoom && g_map.zoom<=max_refresh_problems_zoom)     //**************************************************************************************************************************
		$(".layersContainer .layer#map_problems #refresh_label").show();
	else
		$(".layersContainer .layer#map_problems #refresh_label").hide();
}

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.clearMapViewChanged = function() {
    $("#mapWarningMessage").get(0).innerHTML = "";
    $("#mapWarningMessage").hide();
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.mapViewChanged = function() {
    var tc = this;
    //    if (logged_in_user_id) {
	url = "/map_edit/user_map_view_changed.php";

	var extent = tc.map.getExtent().clone();
	if(tc.map.getProjection()=="EPSG:900913")
		extent.transform(tc.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));
	var coords = extent.toBBOX().split(",");

	extentStr = coords[0]+" "+coords[1]+","+coords[2]+" "+coords[3];

	//var coords = tc.map.getExtent().toBBOX().split(",");
	//extentStr = coords[0]+" "+coords[1]+","+coords[2]+" "+coords[3];
	var params = {"bbox":extentStr};
	if (!tc.stillInformingMapViewChanged) {
	    tc.stillInformingMapViewChanged = true;
	    hasChange = 0;
	    lastKnownCityInViewport = '';
	    lastKnownStateInViewport = '';
	    $.post( url, params, function(response){
		var json = eval("("+response+")");

		if(json.reply.error) {
		} else {
		    hasChange = json.reply.has_change;
		    var is_canada = json.reply.is_canada;
		    lastKnownCityInViewport = json.reply.city_name;
		    lastKnownStateInViewport = json.reply.state_name;
		    if (json.reply.road_six=='t')
		    {
			$("#mapWarningMessage").get(0).innerHTML = "בעקבות עבודות תשתית של waze עריכת כביש 6 אינה אפשרית. לפרטים נוספים קרא <a style='color:white' href='http://www.waze.co.il/forum/viewtopic.php?f=3&t=7035#p41874'>כאן</a>";
			$("#mapWarningMessage").show();
		    }
		    else
		    if (hasChange) {
			$("#mapWarningMessage").get(0).innerHTML = "<u>Notice</u><br/>Area is being edited by someone else</b>";
			$("#mapWarningMessage").show();
			//			alert($("#mapWarningMessage").get(0).innerHTML);
		    } else {
			tc.clearMapViewChanged();
		    }
		}
		
		$("#locationInformation").get(0).innerHTML = (lastKnownCityInViewport.length > 1 ? lastKnownCityInViewport : '-') + ((lastKnownStateInViewport && lastKnownStateInViewport.length > 1) ? ', ' + lastKnownStateInViewport : '');

		
		//$("select[name='state_name']").val(lastKnownStateInViewport);
		//$("input[name='city_name'][type='text']").val(lastKnownCityInViewport);
		tc.stillInformingMapViewChanged = false;
		//		    alert("done");
		}) ;
	}
	
	//    }
}


//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.startMeasurement = function() {
    this._setToolsPanelContents("measurement_tool");
    this.measurementControl.activate();
};
//------------------------------------------------------------------------------------------------------
Cartouche.prototype.stopMeasurement = function() {
    this.measurementControl.deactivate();
    this.updateToolsPanel();
};

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.handleMeasurements = function(event) {
    var geometry = event.geometry;
    var units = event.units;
    var order = event.order;
    var measure = event.measure;
    var element = document.getElementById('output');
    var out = "";
    if(order == 1) {
	out += "Length: " + measure.toFixed(3) + " " + units;
    } else {
	out += "Area: " + measure.toFixed(3) + " " + units + "&#xB2;";
    }
    $("#editPanel .contents #measurement_result").get(0).innerHTML = out;
};
		
		
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._addLoadingIndication = function(layer){
		
    var tc = this;
		
    var name = layer.name;
    layer.events.register("loadstart",this,function(){
		
	    if(tc.layers_loading<=0){// <= and not == in case the ie hack will do decrement tc.layers_loading below 0
			
		tc.layers_loading == 0;
		$("#layersLoading").show();
		this.clearMapViewChanged();
		tc.layersLoadingInterval =window.setInterval ( function(){
			
			var txt = $("#layersLoading").text();
			var first_period = txt.indexOf(".");
			var last_period = txt.lastIndexOf(".");
			
			var period_count = first_period > -1 ? last_period - first_period +2 : 1;
			var MAX_PERIODS = 3;
			txt =  first_period > -1 ?  txt.substring(0,first_period) : txt;
				
			var next_period_count = period_count % (MAX_PERIODS+1);
			for(var i=0; i < next_period_count; i++)
			    txt=txt+".";
				
			$("#layersLoading").text(txt);
				
		    }, 300 );
	    }
	    tc.layers_loading++;
			
	});
		
    var layerDone  = function(){
	tc.layers_loading--;
			
	if(tc.layers_loading<=0){// <= and not == in case the ie hack will do decrement tc.layers_loading below 0
	    window.clearInterval(tc.layersLoadingInterval);
	    $("#layersLoading").hide();
	    this.mapViewChanged();
	}
    }
		
    layer.events.register("loadend",this,layerDone);
    layer.events.register("loadcancel",this,layerDone);
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.createMapMapProblemsLegendRows =  function(tableObject) {
    var body = tableObject.getElementsByTagName('tbody')[0];
    for (var i in map_problem_type_description) {
	var row = body.insertRow(-1);
	var cell1 = row.insertCell(0);
	var cell2 = row.insertCell(1);
	cell1.innerHTML = "<div class=\"legend_symbol\">" + i + "</div>";
	cell2.innerHTML = map_problem_type_description[i];
    }
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.OLDcreateMapMapProblemsLegend =  function(legendObject) {
    var table = document.createElement("Table");
    legendObject.append(table);
    var tbody=document.createElement("tbody");
    table.appendChild(tbody);
    var row = tbody.insertRow(-1);
    var cell1 = row.insertCell(0);
    //    var body = legendObject.getElementsByTagName('tbody')[0];
    for (var i in map_problem_type_description) {
	cell1.innerHTML += "<a style=\"display: inline\" href=\"\#\" onClick=\"javascript:g_cartouche.chooseSpecificProblemType(" + i + ");\"><div id=\"map_problems_legend_type_" + i + "\" style=\"border-style: none; margin-left: 2px; margin-right: 0px; margin-top: 2px; margin-bottom: 2px\" class=\"legend_symbol\" title=\"" + map_problem_type_description[i] + "\"><img src=\"images/" + map_problem_priority_icon[0] + "\"/><span style=\"display: block; text-align: center; font-weight: bold; margin-top:-20px; margin-left: -2px; margin-right: 0px; color: black; z-index: 100000\" href=\"\#\">" + i + "</span></div></a>";
    }
    //    var mdivs = cell1.getElementsByTagName('div');
};

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.createMapMapProblemsLegend =  function(legendObject) {
    //    var span = document.createElement("span");
    //    legendObject.append(span);
    select = legendObject.get(0);
    
    var innerHtml = "";
    
    for (var i in map_problem_type_description) {
	var optionStyle = "";
	//	if (map_problems_privileged_types[i] != undefined) optionStyle="style=\"display: none;\"";
	if (map_problems_privileged_types[i] != undefined) optionStyle="class=\"staff\"";
	if (i.substring(0, 1) == '*') {
	    innerHtml += "<optgroup " + optionStyle + "\" label=\"" + map_problem_type_description[i] + "\"></optgroup>";
	} else {
	    var value = i;
	    if (i.substring(0, 1) == '-') value = i.substring(1);
	    innerHtml += "<option " + optionStyle + " value=\"" + value + "\">"
		+ (i.substring(0, 1) == '-' ? '' : "&nbsp;(" + value + ")&nbsp;")
		+ map_problem_type_description[i]
		+ "</option>";
	}
	
    }
    //    innerHtml += "</select>";
    select.innerHTML = innerHtml;
};

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.refreshFilteredProblemType = function(){
    chosen_problem_type = document.map_problems_legend_form.problem_type_filter.value
    this.refreshMapProblemsView();
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.OLDchooseSpecificProblemType = function(type){
    if ($("#map_problems_legend_type_" + chosen_problem_type).length != 0) {
	$("#map_problems_legend_type_" + chosen_problem_type).get(0).style.backgroundColor="#FFFFFF";
    }
    if (chosen_problem_type == type) {
	chosen_problem_type = '';
    } else {
	chosen_problem_type = type;
	$("#map_problems_legend_type_" + chosen_problem_type).get(0).style.backgroundColor="#6060A0";
    }
    Layers.mapProblemsLayer.mergeNewParams({_SPECIFIC_PROBLEM_TYPE:chosen_problem_type});
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._initPanels = function(){
		
    var tc = this;
    var measurement_system = $(".measurement_system").text();
    if(measurement_system == "metric"){
	$(".metric").show();
	$(".imperial").hide();
    }
    else{
	$(".metric").hide();
	$(".imperial").show();
    }
		
		
    $(".panel:not(#archivePanel)").fadeTo(0, 0.85);
    $("#archivePanel").fadeTo(0,0.95);
    
    
      $("#archivePanel #add_filter").click(function(e){
    
               var filter = $("<div class='filter'></div>");
              $(".archive_filters").after(filter);
               $(filter).html($("#filter_mold").html());
               $(".filter_name",filter).text($(".archive_filters :selected").text()+" (comma separated)");
               $(".filter_data",filter).attr("name",$(".archive_filters").val());
               $("a.remove",filter).click(function(e){
                      $(filter).remove();
               });
    
    });
    
    //create the modal edit panel
    $(".panel").draggable({
	    opacity:0.6,
		stop:function(e,ui){
		tc.writeCookie();
	    }
	});
		
	$.getJSON( "/KART/mini_profile", data={},function(json){
	  
		if(json.success && json.value.areaManager==true)
			$("#open_pending").show();
			
		if(json.success && json.value.isStaff==true)
			$("#open_pending").show();
	  
	}) ;
	  
    $("#editPanel .contents").html($('#initial_tools').html());
		 
    Login.isLoggedIn(function(is_logged_in,user_name, user_id, _logged_in_user_data){
		
	    if(!is_logged_in)
		return;
	    logged_in_user_data = _logged_in_user_data;
	    logged_in_user_id = (user_id ? user_id : '');
	    tc.getOnViewChanged()();
			
	});
		 
    $("#layersPanel .contents .layersContainer").sortable({
		 
	    helper:function(e, el){
			
		var helper = document.createElement("div");
		$(".layersContainer").append(helper);
		$(helper).addClass("layer");
		if($(el).hasClass("selectedLayer"))
		    $(helper).addClass("selectedLayer");
		else
		    $(helper).css("background-color","#eeeeee");
		var name = $(el).text();
		$(helper).text(name);
			
		return helper;
			
	    },
		stop:function(e,ui){
				
		//the order of the layers in the layer panel is reversed index-wise (since we want the top layers
		//to appear on top in the panel) thus layers with a high index in the OpenLayers map will have a low index as
		//divs in the layers panel. In addition the base layer "Aerial" is not listed in the panel.
		//We transform panel index back to map index ... 
		var map =  tc.map;
		var layer_name = $(ui.item).text();	
		var layer = map.getLayersByName(layer_name)[0];

		var current_index  = map.getLayerIndex(layer);

		// convert from panel layer index to map layer index ...
		// -3 for the feature layers and markers layer
		var new_index = map.getNumLayers() - 3 - 1 - $("#layersPanel .contents .layersContainer .layer").index(ui.item);
		map.raiseLayer(layer,new_index-current_index);
	    }
	});
		 
		 
    $(".panel").each(function(){
		 
	    var contents = $(".contents",this);
	    $(".show",this).click(function(){
		
		    contents.slideToggle(function(){
			    tc.writeCookie();
			});
		    $(this).toggleClass("expand");
				
		    return false;
				
		});
		
	    var panel = this;
		
	    $(".close",this).click(function(e){
		
		    $(panel).fadeOut();
		    if(panel.id=="archivePanel"){
			tc.gmlReports.selector.deactivate();
			tc.gmlReports.layer.removeFeatures(tc.gmlReports.layer.features);
		    }
			
		    return false;
				
		});
		
	});
		 
    this.addAutoComplete("viewPanel");

    Login.isLoggedIn(function(is_logged_in,user_name, user_id, _logged_in_user_data){
	    //	    if(is_logged_in) {
	    //		$("#open_archive").show();
	    //		if (_logged_in_user_data.staff && _logged_in_user_data.staff == 't') $("#compile_client_map").show();
	    //
	    //	    }
	    //	    if (is_logged_in && logged_in_user_data.rank && _logged_in_user_data.rank >= 3) {
	    //		$("#tab_route").show();
	    //	    } else {
	    //		$("#tab_route").hide();
	    //	    }
	});
		
		
    $("#search_map_form #findForm").keypress(function(e){
	    if(e.which==13){//enter key
		tc.find();
		return false;
	    }
	});
		
    this._initLayersPanel();
	
    if(hasMapCookie()){
	var panels_info = this.getPanelsInfoCookie();
	if(!panels_info)
	    return;
			
	$.each(panels_info,function(i,val){
		if(i=="archivePanel")
		    return;
		
		
		
		if(val.left=="auto")
		    $("#"+i).css("right",val.right+"px").css("top",val.top+"px");
		else
		    $("#"+i).css("left",val.left+"px").css("top",val.top+"px");
		/*	
		if(val.open)
		    $("#"+i+" .contents").show();
		else 
		    $("#"+i+" .contents").hide();
		*/
	    })
		
	    }
	$("#archivePanel .update_archive").click(function(){
		tc.createArchivePage(1);
		return false;
	});
    if(hasMapCookie()){
	var gps_points_prefs = this.getGPSPointsInfoCookie();
	if (gps_points_prefs) {
	    if (gps_points_prefs.gps_points_arrows != undefined) document.gps_points_form.gps_points_arrows.checked = gps_points_prefs.gps_points_arrows;
	    if (gps_points_prefs.gps_points_colors != undefined) document.gps_points_form.gps_points_arrows.value = gps_points_prefs.gps_points_colors;
	    if (gps_points_prefs.filter_low_weight != undefined)  document.gps_points_form.filter_low_weight.checked = gps_points_prefs.filter_low_weight;
	}

	var boom_additional_prefs = this.getBoomAdditionalPrefsInfoCookie();
	if (boom_additional_prefs) {
	    if (boom_additional_prefs.road_show_turns != undefined) document.roads_form.road_show_turns.checked = boom_additional_prefs.road_show_turns;
	}

	var map_problems_prefs = this.getMapProblemsPrefsInfoCookie();
	if (map_problems_prefs) {
	    if (map_problems_prefs.map_problems_colors != undefined) document.map_problems_legend_form.map_problems_colors.value = map_problems_prefs.map_problems_colors;
	    if (map_problems_prefs.problem_type_filter != undefined)  document.map_problems_legend_form.problem_type_filter.value = map_problems_prefs.problem_type_filter;
	    if (map_problems_prefs.map_problems_show_resolved != undefined)  document.map_problems_legend_form.map_problems_show_resolved.checked = map_problems_prefs.map_problems_show_resolved;
	    if (map_problems_prefs.map_problems_show_low_priority != undefined) document.map_problems_legend_form.map_problems_show_low_priority.checked = map_problems_prefs.map_problems_show_low_priority;
	}
	
    }


	
    //    tc.createMapMapProblemsLegend($("map_problems_legend_form"));
    //    tc.createMapMapProblemsLegend($("#map_problems_l_f"));
    tc.createMapMapProblemsLegend($("#map_problems_type_filter"));
    $("#map_problems_filter_form").keypress(function(e){
	    if(e.which==13){//enter key
		tc.refreshMapProblemsView();
		return false;
	    }
	});
		
    tc.updatePanelsViews(tc);
    
};


//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.setMapProblemsFilter = function(){
};
	 
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._initLayersPanel = function(){
		  
    var utility_layer_names = {locations:"true","add features":true,"edit features":true};
	   
    var tc = this;
    var layers_info = null;
		
    var org_layers=this.map.layers;
    g_org_layers= new Array();
    for (var i=0, len=org_layers.length; i<len; i++) {
		var layer = org_layers[i];
		g_org_layers[i]=layer;
	}
		
    if(document.location.search.indexOf("layers=")<0 && hasMapCookie())
	layers_info = this.getLayersVisibilityFromCookie();

		
    $(".layersContainer .layer").each(function(){
		
	    var layer_name = $(this).text();
	    var layer_id = this.id;
	   
	    var layer = tc.map.getLayersByName(layer_name)[0];
	    
	    if(layers_info)
		layer.setVisibility(layers_info[layer_id]);
		
	    if(layer.getVisibility()){
		$(this).addClass("selectedLayer");
			  
		if(this.id=="roads")
		    $("#roads_panel").slideToggle("slow");

		if(this.id=="map_problems")
		    $("#map_problems_panel").slideToggle("slow");

		if(this.id=="gps_points")
		    $("#gps_points_view").slideToggle("slow");
			
	    }
		
	    $(this).click(function(){
		
		    var map = tc.map;
		    var layer_name = $(this).text() ;
		    var type = tc.layerNameToType(layer_name);
			
		    for(var i in map.layers){
			var next = map.layers[i];
			if(next.name == layer_name)
			    next.setVisibility(!next.getVisibility());
		    }
			
		    if(type){
			var remove_features = true;
			var layers = tc.typeToLayers(type);
			
			for(var i in layers)
			    if(layers[i].getVisibility() && layers[i].params && layers[i].params.LAYERS.indexOf(type)>-1)
				remove_features = false;
				
			if(remove_features){
			    tc._deselectFeatureTypes(eval("['"+type.replace(",","','")+"']"));
			    tc.updateToolsPanel();
			}
		    }
		   
		    $(this).toggleClass("selectedLayer");
			
		    if(this.id=="roads"){
			$("#roads_panel").slideToggle("slow");
		    }

		    if(this.id=="map_problems"){
			
			Login.isLoggedIn(function(is_logged_in){
		
				/*if(is_logged_in)
				    $(".layersContainer .layer#map_problems #refresh_label").toggle();    */
				
				if(is_logged_in &&  $("#map_problems").hasClass("selectedLayer") && tc.map.zoom>=min_refresh_problems_zoom && tc.map.zoom<=max_refresh_problems_zoom)     //**************************************************************************************************************************
					$(".layersContainer .layer#map_problems #refresh_label").show();
				else
					$(".layersContainer .layer#map_problems #refresh_label").hide();
				
			    });
			
			$("#map_problems_panel").slideToggle("slow");
			$("#map_problems_form").slideToggle("slow");
		    }
			
		    if(this.id=="gps_points"){
			$("#gps_points_view").slideToggle("slow");
			$("#gps_points_form").slideToggle("slow");
		    }

		    tc.writeCookie();
		});
		
	});
		
    $(".layersContainer .layer#map_problems #refresh_label").click(function(){
		
	    tc.refreshMapProblems();
	    return false;
	});

    	
    Login.isLoggedIn(function(is_logged_in){
			    
	    if(is_logged_in &&  $("#map_problems").hasClass("selectedLayer") && tc.map.zoom>=min_refresh_problems_zoom && tc.map.zoom<=max_refresh_problems_zoom)     //**************************************************************************************************************************
		$(".layersContainer .layer#map_problems #refresh_label").show();
	    else
		$(".layersContainer .layer#map_problems #refresh_label").hide();
	});
		

};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.refreshGPSPointsPane = function() {

    this._initLayersPanel();
		
};

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.refreshMapProblems = function(){

    var tc = this;
    this.requiresLogin(function(){

	    tc._deselectFeatureTypes(["map_problems"]);
	    tc.updateToolsPanel();
	    //        tc.deselectAll();

	    var url = "/map_edit/map_problems.php";
		
	    
	    var extent = tc.map.getExtent().clone();
	    if(tc.map.getProjection()=="EPSG:900913")
			extent.transform(tc.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));
	    var coords = extent.toBBOX().split(",");

	    extentStr = coords[0]+" "+coords[1]+","+coords[2]+" "+coords[3];
	    var params = {"bbox":extentStr};
	    var resultCallback = function(response){
		$(".layersContainer .layer#map_problems .refresh_indicator").hide();		
		if (tc.map.zoom>=min_refresh_problems_zoom && tc.map.zoom<=max_refresh_problems_zoom)
			$(".layersContainer .layer#map_problems #refresh_label").show();
		var json = eval("("+response+")");
		var map_problems_layer = tc.map.getLayersByName($(".layersContainer #map_problems").text())[0];
		map_problems_layer.redraw(true);
		var restrictions_layer = tc.map.getLayersByName($(".layersContainer #restrictions").text())[0];
		restrictions_layer.redraw(true);
			
		if(json.reply.error)
		    tc.displayEditPanelMessage(json.reply.message,true);
			
	    }
		
	    $(".layersContainer .layer#map_problems #refresh_label").hide();
	    $(".layersContainer .layer#map_problems .refresh_indicator").show();
		
	    $.get( url, params,resultCallback );
		
	},revert_to_previous_contents=true,indicate=true);
		
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._initMapControls = function(){
    //modify control
    var tc = this;

    this.drawing_controls = [];		 
    this.modifyControl = new OpenLayers.Control.ModifyFeature(this.featuresLayer,{
	    resetVertices: function() {
			
		OpenLayers.Control.ModifyFeature.prototype.resetVertices.apply(this);
		for(i in this.vertices){
		    var next = this.vertices[i];
		    next.style = {strokeWidth:3,strokeColor: "#0000b0",strokeOpacity:0.8,pointRadius: 8,fillColor:"#0000b0",fillOpacity:0.1};
		}
		this.layer.removeFeatures(this.vertices);
		this.layer.addFeatures(this.vertices);
			
	    }
	}
	);
    this.drawing_controls.push(this.modifyControl);		
    this.modifyControl.virtualStyle= {strokeWidth:3,strokeColor: "blue",strokeOpacity:0.5,pointRadius: 4,fillColor:"white",fillOpacity:1.0};
    this.map.addControl(this.modifyControl);

    

    var tc = this;
    this.modifyControl.selectControl.onSelect = function(feature){
	tc.modifyControl.originalGeometry = feature.geometry.clone();
    }
    this.modifyControl.mode = OpenLayers.Control.ModifyFeature.RESHAPE  | OpenLayers.Control.ModifyFeature.DRAG;

    this.modifyControl.deactivate();
    this.moveModifyControl = new OpenLayers.Control.ModifyFeature(this.featuresLayer,{
	    resetVertices: function() {
			
		OpenLayers.Control.ModifyFeature.prototype.resetVertices.apply(this);
		for(i in this.vertices){
		    var next = this.vertices[i];
		    next.style = {strokeWidth:3,strokeColor: "#0000b0",strokeOpacity:0.8,pointRadius: 8,fillColor:"#0000b0",fillOpacity:0.1};
		}
		this.layer.removeFeatures(this.vertices);
		this.layer.addFeatures(this.vertices);
			
	    }
	}
	);
		
    this.moveModifyControl.virtualStyle= {strokeWidth:3,strokeColor: "blue",strokeOpacity:0.5,pointRadius: 4,fillColor:"white",fillOpacity:1.0};
    this.map.addControl(this.moveModifyControl);
    this.drawing_controls.push(this.moveModifyControl);

    var tc = this;
    this.moveModifyControl.selectControl.onSelect = function(feature){
	tc.moveModifyControl.originalGeometry = feature.geometry.clone();
    }
    this.moveModifyControl.mode = OpenLayers.Control.ModifyFeature.DRAG | OpenLayers.Control.ModifyFeature.RESIZE | OpenLayers.Control.ModifyFeature.ROTATE;
    //    this.moveModifyControl.mode = OpenLayers.Control.ModifyFeature.RESHAPE;

    this.moveModifyControl.deactivate();

    this.landmarkModifyControl = new OpenLayers.Control.ModifyFeature(this.featuresLayer,{
	    resetVertices: function() {
			
		OpenLayers.Control.ModifyFeature.prototype.resetVertices.apply(this);
		for(i in this.vertices){
		    var next = this.vertices[i];
		    next.style = {strokeWidth:3,strokeColor: "#0000b0",strokeOpacity:0.8,pointRadius: 8,fillColor:"#0000b0",fillOpacity:0.1};
		}
		this.layer.removeFeatures(this.vertices);
		this.layer.addFeatures(this.vertices);
			
	    },
	    dragComplete: function(vertex){
		
		if (vertex.geometry.parent)
		{
			if (vertex.geometry.parent.components[0].x==vertex.geometry.x && vertex.geometry.parent.components[0].y==vertex.geometry.y)
			{
				//vertex.geometry.parent.components[vertex.geometry.parent.components.length-1].move(vertex.geometry.x,vertex.geometry.y);
				vertex.geometry.parent.components[vertex.geometry.parent.components.length-1].x=vertex.geometry.x;
				vertex.geometry.parent.components[vertex.geometry.parent.components.length-1].y=vertex.geometry.y;
			}
			else
				if (vertex.geometry.parent.components[vertex.geometry.parent.components.length-1].x==vertex.geometry.x && vertex.geometry.parent.components[vertex.geometry.parent.components.length-1].y==vertex.geometry.y)
				{
					//vertex.geometry.parent.components[0].move(vertex.geometry.x,vertex.geometry.y);
					vertex.geometry.parent.components[0].x=vertex.geometry.x;
					vertex.geometry.parent.components[0].y=vertex.geometry.y;
				}
			 //tc.redrawFeatureType("landmarks");
		}
		OpenLayers.Control.ModifyFeature.prototype.dragComplete.apply(this);
		this.layer.drawFeature(this.feature, this.selectControl.renderIntent);
			
	    }
	}
	);
    this.drawing_controls.push(this.landmarkModifyControl);	
    this.landmarkModifyControl.virtualStyle= {strokeWidth:3,strokeColor: "blue",strokeOpacity:0.5,pointRadius: 4,fillColor:"white",fillOpacity:1.0};
    this.map.addControl(this.landmarkModifyControl);

    this.landmarkModifyControl.selectControl.onSelect = function(feature){
	tc.landmarkModifyControl.originalGeometry = feature.geometry.clone();
    }
    this.landmarkModifyControl.mode = OpenLayers.Control.ModifyFeature.RESHAPE | OpenLayers.Control.ModifyFeature.DRAG | OpenLayers.Control.ModifyFeature.ROTATE;
    this.landmarkModifyControl.deactivate();

    


    //draw controls (road)
    this.drawRoadControl = new OpenLayers.Control.DrawFeature(layer=this.newFeaturesLayer,handler=OpenLayers.Handler.Path,{featureAdded:this.getOnRoadAdded()});
    this.drawRoadFreehandControl = new OpenLayers.Control.DrawFeature(layer=this.newFeaturesLayer,handler=OpenLayers.Handler.Path,{featureAdded:this.getOnRoadAdded(), handlerOptions: {freehand: true}});
    this.drawRoadControl.handler.style = {strokeWidth:5,strokeColor: "black",strokeOpacity:0.8,pointRadius: 3,fillColor:"white"};
		
    this.drawing_controls.push(this.drawRoadControl);
    this.drawing_controls.push(this.drawRoadFreehandControl);
	
    this.map.addControl(this.drawRoadControl);
    this.drawRoadControl.deactivate();
    this.map.addControl(this.drawRoadFreehandControl);
    this.drawRoadFreehandControl.deactivate();


    //draw controls (landmark)
    this.drawLandmarkControl = new OpenLayers.Control.DrawFeature(layer=this.newFeaturesLayer,handler=OpenLayers.Handler.Polygon,{featureAdded:this.getOnLandmarkAdded()});
    this.drawing_controls.push(this.drawLandmarkControl);
    //    this.drawLandmarkControl.handler.style = {strokeWidth:3,strokeColor: "black",strokeOpacity:0.2,pointRadius: 2,fillColor:"white"};
    this.map.addControl(this.drawLandmarkControl);
    this.drawLandmarkControl.deactivate();
    
    this.drawLandmarkFreehandControl = new OpenLayers.Control.DrawFeature(layer=this.newFeaturesLayer,handler=OpenLayers.Handler.Polygon,{featureAdded:this.getOnLandmarkAdded(), handlerOptions: {freehand: true}});
     this.drawing_controls.push(this.drawLandmarkFreehandControl);
    //    this.drawLandmarkFreehandControl.handler.style = {strokeWidth:3,strokeColor: "black",strokeOpacity:0.2,pointRadius: 2,fillColor:"white"};
    this.map.addControl(this.drawLandmarkFreehandControl);
    this.drawLandmarkFreehandControl.deactivate();
	

	 //draw controls (lasso)
    this.drawLassoControl = new OpenLayers.Control.DrawFeature(layer=this.newFeaturesLayer,handler=OpenLayers.Handler.Polygon,{featureAdded:this.getOnLassoAdded()});
    this.drawing_controls.push(this.drawLassoControl);
    this.map.addControl(this.drawLassoControl);
    this.drawLassoControl.deactivate();
 
    //drag node control
    this.dragNodeControl = new OpenLayers.Control.DragFeature(this.featuresLayer,{geometryTypes:["OpenLayers.Geometry.Point"],doneDragging:this.onNodeMoved});
    this.drawing_controls.push(this.dragNodeControl);
    this.map.addControl(this.dragNodeControl);
    this.dragNodeControl.deactivate();
		 
    this.map.addControl(new OpenLayers.Control.Navigation());
	this.map.addControl(new OpenLayers.Control.WazePanZoomBar());
		 
    this.map.addControl(new OpenLayers.Control.ScaleLine());
    this.map.addControl(new OpenLayers.Control("TTTT"));
		
    this.map.addControl(this.mousePositionControl = new OpenLayers.Control.MousePosition(
							     {
								 formatOutput:function(lonlat){
								     var digits = parseInt(this.numDigits);
								     return "lon: "+lonlat.lon.toFixed(digits)+" , lat:"+lonlat.lat.toFixed(digits) + "&nbsp;<a style=\"display: inline;\" href=\"#\" onclick=\"event.cancelBubble=true; alert('Copy the following coordinates line:\\n" + lonlat.lat.toFixed(digits) + " " + lonlat.lon.toFixed(digits) + "');\"><img border=\"0\" src=\"images/edit-copy.png\" align=\"top\"/></a>";  ;
								 }
							     }
							     ));


    /* NEW ROUNDABOUT */
    
    this.roundaboutModifyControl = new OpenLayers.Control.ModifyFeature(this.newFeaturesLayer,{
	    resetVertices: function() {
			
		OpenLayers.Control.ModifyFeature.prototype.resetVertices.apply(this);
		for(i in this.vertices){
		    var next = this.vertices[i];
		    next.style = {strokeWidth:3,strokeColor: "#0000b0",strokeOpacity:0.8,pointRadius: 8,fillColor:"#0000b0",fillOpacity:0.1};
		}
		this.layer.removeFeatures(this.vertices);
		this.layer.addFeatures(this.vertices);
			
	    }

	}
	);
		
    this.roundaboutModifyControl.virtualStyle= {strokeWidth:3,strokeColor: "blue",strokeOpacity:0.5,pointRadius: 4,fillColor:"white",fillOpacity:1.0};
    this.drawing_controls.push(this.roundaboutModifyControl);
    this.map.addControl(this.roundaboutModifyControl);

    this.roundaboutModifyControl.selectControl.onSelect = function(feature){
	tc.roundaboutModifyControl.originalGeometry = feature.geometry.clone();
    }

    this.roundaboutModifyControl.dragControl.oldOnDrag = this.roundaboutModifyControl.dragControl.onDrag;
    this.roundaboutModifyControl.dragControl.onDrag = function(feature, pixel){
	tc.roundaboutModifyControl.dragControl.oldOnDrag(feature, pixel);

	var radius;
	var centerLonLat;
	if(tc.map.getProjection()=="EPSG:900913"){
		radius = tc.roundaboutModifyControl.feature.geometry.getBounds().getWidth() / 2;
		centerLonLat = tc.roundaboutModifyControl.feature.geometry.getBounds().getCenterLonLat().clone();
		centerLonLat.transform(tc.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));
	}
	else{
		var radiusInDegrees = tc.roundaboutModifyControl.feature.geometry.getBounds().getWidth() / 2;
		radius = (Math.floor(radiusInDegrees * simpleDegreesToMetersRatio * 10)) / 10;
		centerLonLat = tc.roundaboutModifyControl.feature.geometry.getBounds().getCenterLonLat();
	}
	
	$("#editPanel .contents input[name=radius]").val(radius);
	$("#editPanel .contents input[name=longitude]").val(centerLonLat.lon);
	$("#editPanel .contents input[name=latitude]").val(centerLonLat.lat);
    };

    this.roundaboutModifyControl.mode = OpenLayers.Control.ModifyFeature.RESIZE ;//| OpenLayers.Control.ModifyFeature.ROTATE | OpenLayers.Control.ModifyFeature.DRAG;
    //    this.roundaboutModifyControl.mode = OpenLayers.Control.ModifyFeature.RESHAPE | OpenLayers.Control.ModifyFeature.DRAG | OpenLayers.Control.ModifyFeature.ROTATE;
    this.roundaboutModifyControl.deactivate();

    /* NEW ROUNDABOUT */

    //permalink
    //    var permalink = new OpenLayers.Control.Permalink();
    var permalink = new CartouchePermalink("SuperPermalink");
    this.map.addControl(permalink);
    this.permalinkControl = permalink;
		
    //navigation history
    //this.map.addControl(new OpenLayers.Control.NavigationHistory({activateOnDraw:true}));
    this.navHistory = new OpenLayers.Control.NavigationHistory();
    this.map.addControl(this.navHistory);
		   
    $(".olControlScaleLine,.olControlMousePosition,.olControlPermalink").fadeTo(0, 0.95);

}

    function test(e) {
	var a = 1;
	alert(e);
    };
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.moveNode = function(){
		
    this._setToolsPanelContents("move_node_tools");
    this.dragNodeControl.activate();
    this.dragNodeControl.originalGeometry =this.selectedFeatures[this.featureQueue[0]].vector.geometry.clone();
		
    var feature = this.selectedFeatures[this.featureQueue[0]].vector;
    this.featuresLayer.eraseFeatures(feature);
    feature.style = {strokeWidth:4,strokeColor: "#ffdd00",strokeOpacity:1.0,pointRadius: 6,fillColor:"transparent",fillOpacity:0.3};
    this.featuresLayer.drawFeature(feature);
		
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.getOnRoadAdded = function(){
		
    var tc = this;
    return function(){
		tc.drawRoadControl.deactivate();
		tc.drawRoadFreehandControl.deactivate();

		$("#editPanel #applyFixIndicator").show();
		$("#editPanel .contents").fadeTo(1, 0.3);
	
		var center = tc.newFeaturesLayer.features[0].geometry.getCentroid().clone();		
		if(tc.map.getProjection()=="EPSG:900913")
			center.transform(tc.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));
				
		$.getJSON(url="/KART/where",data={lon:center.x,lat:center.y},function(response){

			$("#editPanel .contents").fadeTo(0.3, 1);
			$("#editPanel #applyFixIndicator").hide();

			tc._setToolsPanelContents("edit_road_details_tools");
			$("#edit_road_details").hide();
			$("#editPanel form select[name=direction]").val(2);
			//$("#editPanel form input[name=city_name]").val(lastKnownCityInViewport);
			//$("#editPanel form select[name=state_name]").val(lastKnownStateInViewport);
			$("#new_road_details").show();
			$("#editPanel .contents .stats").hide();

			tc.addAutoComplete("editPanel");

			$("#editPanel .contents form input[name=id]").val("-1");
		
			var str_rep = "";
			var points = tc.newFeaturesLayer.features[0].geometry.components;
			for(var i in points){
			  
				var point = points[i].clone();
				if(tc.map.getProjection()=="EPSG:900913")
					point.transform(tc.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));
				str_rep+=point.x+","+point.y+" ";
			}
		
			$("#editPanel .contents #roadCoordinates textarea").val(str_rep);
			$("#editPanel .contents #roadCoordinates").show();

			if(response.success){
			
				if(response.value.country.length > 0)
					$("#editPanel form input[name=country_name]").val(response.value.country);
				
				if(response.value.province.length > 0)
					$("#editPanel form select[name=province_name]").val(response.value.province);
				else
					$("#editPanel form select[name=province_name]").attr("disabled","true");

				if(response.value.city.length > 0)
					$("#editPanel form input[name=city_name]").val(response.value.city);

			}
		});
		
    }
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.addAutoComplete= function(panel){
    
	var tc=this;
	$("#"+panel+" .contents input[name=city_name]").autocomplete("/KART/autocomplete",
		{
			extraParams:{
				state_name:function(){
					return $("#"+panel+" .contents select[name=state_name]").val();
				},
				name:"city_name",
				left:function(){
					return tc.map.getExtent().left;
				},
				right:function(){
					return tc.map.getExtent().right;
				},
				top:function(){
					return tc.map.getExtent().top;
				},
				bottom:function(){
					return tc.map.getExtent().bottom;
				}
			}
		});
	
	
	$("#"+panel+" .contents input[name=street_name]").autocomplete("/KART/autocomplete",
		{
			extraParams:{
				state_name:function(){
					return $("#"+panel+" .contents select[name=state_name]").val();
				},
				name:"street_name",
				city_name:function(){
					return $("#"+panel+" .contents input[name=city_name]").val();
				},
				left:function(){
					return tc.map.getExtent().left;
				},
				right:function(){
					return tc.map.getExtent().right;
				},
				top:function(){
					return tc.map.getExtent().top;
				},
				bottom:function(){
					return tc.map.getExtent().bottom;
				}
			},
			cacheLength:1
		}
	);
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.layerNameToType = function(layer_name){
		
    if(!this.map.getLayersByName(layer_name) || this.map.getLayersByName(layer_name).length==0)
	return null;
		
    var layer = this.map.getLayersByName(layer_name)[0];
    if(!layer || layer.id.indexOf("WMS")<0)
	return null;
		
    var mappingQ = $(".layersContainer");
		 
    var notFeatureLayers = {
	"Aerial":true
    }
    notFeatureLayers[$("#shade",mappingQ).text()] = true;
    notFeatureLayers[$("#managers",mappingQ).text()] = true;
    //notFeatureLayers[$("#gps_points",mappingQ).text()] = true;
    notFeatureLayers[$("#recent_gps_points",mappingQ).text()] = true;
    notFeatureLayers[$("#segments_for_deletion",mappingQ).text()] = true;
    //notFeatureLayers[$("#map_problems",mappingQ).text()] = true;
    notFeatureLayers[$("#restrictions",mappingQ).text()] = true;
    //    notFeatureLayers[$("#restrictions_solutions",mappingQ).text()] = true;
    //    notFeatureLayers[$("#landmarks",mappingQ).text()] = true;
    notFeatureLayers[$("#junction_names",mappingQ).text()] = true;
    notFeatureLayers[$("#additional_markings",mappingQ).text()] = true;

    if(notFeatureLayers[layer.name])
	return null;
		
    if(layer.params.LAYERS.indexOf("roads")==0 ||  layer.params.LAYERS.indexOf("line_roads")==0)
	return "roads"
	else
	    return layer.params.LAYERS;
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.typeToLayers = function(type){
	   
    var layersWithType = [];
    if(type=="nodes")//nodes does not have it's own layer, it is found in roads
	type = "roads";

    var layers = this.map.layers;
    for(var i in layers){
	var next = layers[i];
	if(next.params && next.params.LAYERS && next.params.LAYERS.indexOf(type)>-1)
	    layersWithType.push(next);
    }

    return layersWithType;
};
//-------------------------------------------------------------------------------------------------------------------

Cartouche.prototype._setToolsPanelContents = function(contents_id,prepended_features_info, appended_features_info,callback){
		
    var displayFilters = {
	"edit_road_details_tools":function(){
	    $("#editPanel").width("250px");
	},
	"edit_landmark_details_tools":function(){
	    $("#editPanel").width("250px");
	},
	"edit_landmark_point_details_tools":function(){
	    $("#editPanel").width("250px");
	}
    }


    $("#editPanel .contents").hide();
    //revert to normal width
    $("#editPanel").width("200px");
		  
    var q =  $("#editPanel .contents").html($('#'+contents_id).html());
		  
    if(prepended_features_info)
	$(".selectedFeatures",q).prepend(prepended_features_info);
    if(appended_features_info)
	$(".selectedFeatures",q).append(appended_features_info);
		  
    if(displayFilters[contents_id])
	displayFilters[contents_id]();
		  
    if(callback)
	callback();

    $("#editPanel .contents").fadeIn("slow"); 

};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._countFeatures = function(){
		
    var count = {};
    count["overall"] = 0;
    for(var type in this.factory.FEATURE_TYPES)
	count[type] = 0;
		
    for(var id in this.selectedFeatures){
	var type = id.split(".")[0];
	count[type]++;
	count.overall++;
    }              
    return count;
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._deselectFeatureTypes = function(types){
		
	  
    var removeFeatureList = [];
    var removeVectorList = [];
		 
    for(var id in this.selectedFeatures){
	var nextType = id.split(".")[0];
	for(var i in types){
	    var type=types[i];
	    if(nextType == type){
		removeFeatureList.push(id);
		removeVectorList.push(this.selectedFeatures[id].vector);
	    }
				  
	}
			  
    }
		 
    this.featuresLayer.removeFeatures(removeVectorList);
	  
    for(var i in removeFeatureList)
	delete this.selectedFeatures[removeFeatureList[i]];
		
    //rebuild the features queue
    var newFeatureQueue = []
    for(var i in this.featureQueue){
	var next_id = this.featureQueue[i];
	if(this.selectedFeatures[next_id])
	    newFeatureQueue.push(next_id);
    }
		
    this.featureQueue = newFeatureQueue;

    this.doSelectionUpdates();
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._deselectOtherFeaturesTypes = function(types){
		
    var removeFeatureList = [];
    var removeVectorList = [];
		 
    for(var id in this.selectedFeatures){
	var nextType = id.split(".")[0];
	var misses = 0;
	for(var i in types){
	    var type=types[i];
	    if(nextType != type)
		misses++;
	}
			  
	if(misses==types.length){
	    removeFeatureList.push(id);
	    removeVectorList.push(this.selectedFeatures[id].vector);
	} 
    }
		 
    this.featuresLayer.removeFeatures(removeVectorList);
	  
    for(var i in removeFeatureList)
	delete this.selectedFeatures[removeFeatureList[i]];
		
    //rebuild the features queue
    var newFeatureQueue = []
    for(var i in this.featureQueue){
	var next_id = this.featureQueue[i];
	if(this.selectedFeatures[next_id])
	    newFeatureQueue.push(next_id);
    }
		
    this.featureQueue = newFeatureQueue;
    
    this.doSelectionUpdates();

};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._deselectOtherFeatures = function(feature_id){
    this.doSelectionUpdates();		
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._mapToArray = function(map){
		
    var arr = [];
    for(var key in map)
	arr.push(map[key]);
		
    return arr;
};

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.problemDescriptionHtml = function(type, priority, isMain, url){
    return "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"margin-bottom: " + (isMain ? "4" : "0") + "px; margin-top: 0px;" + (isMain ? " background-color: #FFFFC4;" : "") + " border-style: solid; border-width: " + (isMain ? "1px" : "0px") + "\"><tr><td width=\"1%\"><div style=\"margin-left: 0px; margin-right: 0px; margin-top: 0px; margin-bottom: 0px; padding: 0px;\">" + (url ? "<a style=\"border-width: 0; margin: 1px\" href=\"" + url + "\">" : "") + "<img border=\"0\" src=\"images/" + map_problem_priority_icon[priority] + "\"/><span style=\"display: block; text-align: center; font-weight: bold; margin-top:-22px; margin-left: -2px; margin-right: 0px; color: black; z-index: 100000\" href=\"\#\">" + type  + "</span> " + (url ? "</a>" : "") + "</div></td><td><div style=\" margin-left: 3px\">" + (url ? "<a style=\"border-width: 0; margin: 1px\" href=\"" + url + "\">" : "") + map_problem_type_description[type] + (url ? "</a>" : "") + "</div></td></tr></table>";
};

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.updateAdditionalProblemsInPanel = function(){

    $("#editPanel .contents #problemAdditionalProblems").get(0).innerHTML = "";
    if (currently_marked_map_problem['additional_problems_id_0'].length > 0) {
	if (currently_marked_map_problem['additional_problems_id_0'].length > 0) {
	    $("#editPanel .contents #problemAdditionalProblems").get(0).innerHTML +=  this.problemDescriptionHtml(currently_marked_map_problem['additional_problems_type_0'], currently_marked_map_problem['additional_problems_priority_0'], false, "javascript:g_cartouche.deselectAll(); g_cartouche.onclick(null, '', '" + currently_marked_map_problem['additional_problems_bbox_0'] + "', '" + currently_marked_map_problem['additional_problems_id_0'] + "')");
	}
	if (currently_marked_map_problem['additional_problems_id_1'].length > 0) {
	    $("#editPanel .contents #problemAdditionalProblems").get(0).innerHTML += this.problemDescriptionHtml(currently_marked_map_problem['additional_problems_type_1'], currently_marked_map_problem['additional_problems_priority_1'], false, "javascript:g_cartouche.deselectAll(); g_cartouche.onclick(null, '', '" + currently_marked_map_problem['additional_problems_bbox_1'] + "', '" + currently_marked_map_problem['additional_problems_id_1'] + "')");
	}
	if (currently_marked_map_problem['additional_problems_id_2'].length > 0) {
	    $("#editPanel .contents #problemAdditionalProblems").get(0).innerHTML += this.problemDescriptionHtml(currently_marked_map_problem['additional_problems_type_2'], currently_marked_map_problem['additional_problems_priority_2'], false, "javascript:g_cartouche.deselectAll(); g_cartouche.onclick(null, '', '" + currently_marked_map_problem['additional_problems_bbox_2'] + "', '" + currently_marked_map_problem['additional_problems_id_2'] + "')");
	}
	if (currently_marked_map_problem['additional_problems_id_3'].length > 0) {
	    $("#editPanel .contents #problemAdditionalProblems").get(0).innerHTML += this.problemDescriptionHtml(currently_marked_map_problem['additional_problems_type_3'], currently_marked_map_problem['additional_problems_priority_3'], false, "javascript:g_cartouche.deselectAll(); g_cartouche.onclick(null, '', '" + currently_marked_map_problem['additional_problems_bbox_3'] + "', '" + currently_marked_map_problem['additional_problems_id_3'] + "')");
	}
    } else {
    }
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.updateToolsPanel = function(){

    var tc = this;
   // if($("#editPanel .help_tooltip").length>0)
   $("#editPanel .help_tooltip").qtip("destroy");

    this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
		 
    var count = this._countFeatures();
		  
    if(count.landmark_points==0 && count.landmarks==0 && count.roads==0 && count.nodes==0 && count.map_problems==0 && count.gps_points==0 && count.overall > 0){
	this.editFeature(count);
	return;
    }
		  
    if(count.landmark_points==0 && count.landmarks==0 && count.roads==0 && count.nodes==0 && count.map_problems==0 && count.gps_points==0){
	this._setToolsPanelContents("initial_tools",null,null,function(){
		$("#editPanel .select_help").qtip({
		  	content: { text: $("#select_tooltip").html() },
		   	show: 'mouseover',
		   	hide: {when:'mouseout',fixed:true},
			position: { adjust: { screen: true } }

		})
		$("#editPanel .add_node_help").qtip({
		  	content: { text: $("#add_node_tooltip").html() },
		   	show: 'mouseover',
		   	hide: {when:'mouseout',fixed:true},
			position: { adjust: { screen: true },scroll:false,resize:false }
		})
		$("#editPanel .remove_node_help").qtip({
		  	content: { text: $("#remove_node_tooltip").html() },
		   	show: 'mouseover',
		   	hide: {when:'mouseout',fixed:true},
			position: { adjust: { screen: true },scroll:false,resize:false }
		})
		
	});
	
    }

    var features_names_string = "";
    for(var id in this.selectedFeatures){
	var type = id.split(".")[0];
	if (type == "roads") {
	    if (features_names_string.length > 0) features_names_string = features_names_string + ", ";
	    if (this.selectedFeatures[id].details.street_name!=null)
	    features_names_string = features_names_string + this.selectedFeatures[id].details.street_name;
	}
	if (type == "landmarks" || type == "landmark_points") {
	    if (features_names_string.length > 0) features_names_string = features_names_string + ", ";
	    features_names_string = features_names_string + this.selectedFeatures[id].details.name;
	}
    }
    features_names_string = features_names_string + "";

		  
    if(count.roads==1 && count.nodes==0){
	if(this.selectedFeatures[this.featureQueue[0]].details["direction"]=="1")
	    this._setToolsPanelContents("one_two_way_road_tools", null, "<br/>(" + features_names_string + ")");
	else
	    this._setToolsPanelContents("one_road_tools", null, "<br/>(" + features_names_string + ")");
    }
	  
    if(count.landmarks==1)
	this._setToolsPanelContents("one_landmark_tools", null, "<br/>(" + features_names_string + ")");


    if(count.landmark_points==1)
	this._setToolsPanelContents("one_landmark_point_tools", null, "<br/>(" + features_names_string + ")");

    if(count.roads==0 && count.nodes==1)
	this._setToolsPanelContents("one_intersection_tools");
		 
    if(count.roads==2 && count.nodes==0)
	this._setToolsPanelContents("two_roads_tools",count.roads+" ", "<br/>(" + features_names_string + ")");
		 
    if(count.roads>2 && count.nodes==0)
	this._setToolsPanelContents("multi_roads_tools",count.roads+" ", "<br/>(" + features_names_string + ")");
		 
    if(count.roads==0 && count.nodes>1)
	this._setToolsPanelContents("multi_intersections_tools",count.nodes+" ");
		   
    if(count.roads==1 && count.nodes==1) {
	this._setToolsPanelContents("one_node_one_road_tools");
	return;
    }

    if(count.roads==1 && count.nodes==2) {
	this._setToolsPanelContents("two_nodes_one_road_tools");
	return;
    }

    if(count.roads>0 && count.nodes>0)
	this._setToolsPanelContents("mixed_selection_tools");
    if(count.map_problems==1){
	this._setToolsPanelContents("problem_solving_tool");
	$("#editPanel .contents #problemPriority").text(map_problem_severity_description[currently_marked_map_problem['priority']] );
	$("#editPanel .contents #problemTypeDescription").get(0).innerHTML = "";
	$("#editPanel .contents #problemTypeDescription").get(0).innerHTML += this.problemDescriptionHtml(currently_marked_map_problem['type'], currently_marked_map_problem['priority'], true);
	//      $("#editPanel .contents #problemTypeDescription").get(0).innerHTML += "(" + currently_marked_map_problem['type'] + ") " + map_problem_type_description[currently_marked_map_problem['type']];
	$("#editPanel .contents #problemPointsNum").text(currently_marked_map_problem['points_num']);
	//      $("#editPanel .contents #problemText").text('');

	if (currently_marked_map_problem['weight'].length > 0) {
	    var txt = $("#editPanel .contents #problemWeight").text();
	    $("#editPanel .contents #problemWeight").get(0).innerHTML = txt + currently_marked_map_problem['weight'];
	    $("#editPanel .contents #problemWeightSpan").show();
	} else {
	    $("#editPanel .contents #problemWeightSpan").hide();
	}

	if (currently_marked_map_problem['session_id_1'].length > 0) {
	    var txt = $("#editPanel .contents #problemSession").text();
	    $("#editPanel .contents #problemSession").get(0).innerHTML = 
		"<a style=\"display:inline;\" href=\"javascript: g_cartouche.showGPSPointsSessionForMapProblem('" + currently_marked_map_problem['session_id_1'] + "')\"><img border=\"0\" align=\"bottom\" src=\"images/small-car.gif\"></img>" + txt + "</a>" ;
	    $("#editPanel .contents #problemSessionDiv").show();
	} else {
	    $("#editPanel .contents #problemSessionDiv").hide();
	}

	if (currently_marked_map_problem['data_file_name'].length > 0) {
	    var bounds = tc.map.getExtent();
	    //	    bounds = "ll";
	    var txt = $("#editPanel .contents #problemArchive").text();
	    $("#editPanel .contents #problemArchive").get(0).innerHTML = 
		"<a href=\"#\" style=\"display:inline;\" onClick=\"g_cartouche.zoomOut(); g_cartouche.openArchive(); g_cartouche.gmlReports.showReport(" + currently_marked_map_problem['session_id_1'] + ", '" +  currently_marked_map_problem['data_file_name'] + "', g_cartouche.map.getExtent()); g_cartouche.gmlReports.selector.activate();\">" + txt +"</a>";
	    
	    $("#editPanel .contents #problemArchiveDiv").show();
	} else {
	    $("#editPanel .contents #problemArchiveDiv").hide();
	}



	//if (logged_in_user_data && logged_in_user_data.staff && logged_in_user_data.staff == 't' && currently_marked_map_problem['resolvable'] == 'true') {
	    if (currently_marked_map_problem['resolve_resolution'] == 'RESOLVED') {
		$("#editPanel .contents #problemResolveResolution").get(0).innerHTML = currently_marked_map_problem['resolve_resolution'];
		$("#editPanel .contents #problemResolveResolverUserName").get(0).innerHTML = currently_marked_map_problem['resolve_resolver_user_name'];
		$("#editPanel .contents #problemResolveUpdateDate").get(0).innerHTML = currently_marked_map_problem['resolve_update_date'];
		$("#editPanel .contents #problemResolveReason").get(0).innerHTML = currently_marked_map_problem['resolve_reason'];


		$("#editPanel .contents #problemResolveStatus").show();
		$("#editPanel .contents #problemMarkAsResolved").hide();
	    } else {
		var txt = $("#editPanel .contents #problemMarkAsResolvedLink").text();
		$("#editPanel .contents #problemMarkAsResolvedLink").get(0).innerHTML = 
		    "<a style=\"display:inline; float: none;\" href=\"javascript: g_cartouche.markProblemAsResolved(" + currently_marked_map_problem['id'] + ", $('#editPanel .contents #problemResolutionReason').get(0).value)\">" + txt + "</a>" ;
		$("#editPanel .contents #problemResolveStatus").hide();
		$("#editPanel .contents #problemMarkAsResolved").show();
	    }

	    $("#editPanel .contents #problemResolveStatusDiv").show();
	/*} else {
	    $("#editPanel .contents #problemResolveStatusDiv").hide();
	}*/

	if (currently_marked_map_problem['segment_id_1'].length + currently_marked_map_problem['segment_id_2'].length + currently_marked_map_problem['segment_id_3'].length + currently_marked_map_problem['segment_id_4'].length > 0) {
	    $("#editPanel .contents #problemText").get(0).innerHTML = '';
		  
	    var listElement = document.createElement('ol');
	    //          listElement.style.marginLeft = "-18px";
	    listElement.style.marginTop = "0px";
	    listElement.style.marginBottom = "0px";
	    listElement.style.paddingLeft = "0px";
	    listElement.style.paddingRight = "0px";
	    $("#editPanel .contents #problemText").get(0).appendChild(listElement);
	    if (currently_marked_map_problem['segment_id_1'].length > 0) {
		var streetName = currently_marked_map_problem['street_name_1'];
		if (streetName.length < 1) streetName = "''";
		listElement.innerHTML+= "<li style=\"list-style-position: inside;\"><a style=\"display: inline\" href=\"" + "javascript:g_cartouche.onclick(null, '" + currently_marked_map_problem['segment_id_1'] + "', '" + currently_marked_map_problem['segment_bbox_1'] + "')" + "\">" + streetName + "&nbsp;&nbsp;<small>[" + currently_marked_map_problem['segment_weight_1'] + "]</small>" + "</a></li>";
	    }
		  
	    if (currently_marked_map_problem['segment_id_2'].length > 0) {
		var streetName = currently_marked_map_problem['street_name_2'];
		if (streetName.length < 1) streetName = "''";
		listElement.innerHTML+= "<li style=\"list-style-position: inside;\"><a style=\"display: inline\" href=\"" + "javascript:g_cartouche.onclick(null, '" + currently_marked_map_problem['segment_id_2'] + "', '" + currently_marked_map_problem['segment_bbox_2'] + "')" + "\">" + streetName + "&nbsp;&nbsp;<small>[" + currently_marked_map_problem['segment_weight_2'] + "]</small>" + "</a></li>";
	    }
	}

	//      if (true || currently_marked_map_problem['segment_id_1'].length + currently_marked_map_problem['segment_id_2'].length + currently_marked_map_problem['segment_id_3'].length + currently_marked_map_problem['segment_id_4'].length > 0) {
	//          $("#editPanel .contents #problemText").get(0).innerHTML += "</ol>";
	//      }



	if (currently_marked_map_problem['suggestion_id_1'].length + currently_marked_map_problem['suggestion_id_2'].length + currently_marked_map_problem['suggestion_id_3'].length + currently_marked_map_problem['suggestion_id_4'].length > 0) {
	    var listElement = document.createElement('ul');
	    listElement.style.marginTop = "0px";
	    listElement.style.marginBottom = "0px";
	    listElement.style.paddingLeft = "0px";
	    listElement.style.paddingRight = "0px";
	    $("#editPanel .contents #problemSuggestedFix").get(0).innerHTML = "";
	    $("#editPanel .contents #problemSuggestedFix").get(0).appendChild(listElement);

		
	    //          $("#editPanel .contents #problemSuggestedFix").get(0).innerHTML = "<ul>";
	    if (currently_marked_map_problem['suggestion_id_1'].length > 0 && currently_marked_map_problem['suggestion_description_1'].indexOf("Delete segment")<0)
		listElement.innerHTML += "<li  style=\"list-style-position: inside;\"><a style=\"display: inline\" href=\"" + "javascript:g_cartouche.doProblemSuggestedFix(" + currently_marked_map_problem['suggestion_id_1'] + ")\">" + currently_marked_map_problem['suggestion_description_1'] + "</a>" + (currently_marked_map_problem['suggestion_relevant_session_ids_1'].length > 0 ? "&nbsp;<a title=\"View the track used for the decision\" style=\"display:inline;\" href=\"javascript: g_cartouche.showGPSPointsSessionForMapProblem('" + currently_marked_map_problem['suggestion_relevant_session_ids_1'] + "')\"><img border=\"0\" align=\"bottom\" src=\"images/small-car.gif\"></img></a>" : "") + (currently_marked_map_problem['type'] == -10 ? "<a style=\"display: inline\" href=\"javascript: g_cartouche.showRestrictionsSolutions(" + currently_marked_map_problem['suggestion_id_1'] + ")\">show</a>" : "") + "</li>";
	    if (currently_marked_map_problem['suggestion_id_2'].length > 0 && currently_marked_map_problem['suggestion_description_2'].indexOf("Delete segment")<0)
		listElement.innerHTML += "<li  style=\"list-style-position: inside;\"><a style=\"display: inline\" href=\"" + "javascript:g_cartouche.doProblemSuggestedFix('" + currently_marked_map_problem['suggestion_id_2'] + "')\">" + currently_marked_map_problem['suggestion_description_2'] + "</a>" + (currently_marked_map_problem['type'] == -10 ? "<a style=\"display: inline\" href=\"javascript: g_cartouche.showRestrictionsSolutions(" + currently_marked_map_problem['suggestion_id_2'] + ")\">show</a>" : "") + "</li>";
	    if (currently_marked_map_problem['suggestion_id_3'].length > 0 && currently_marked_map_problem['suggestion_description_3'].indexOf("Delete segment")<0)
		listElement.innerHTML += "<li  style=\"list-style-position: inside;\"><a style=\"display: inline\" href=\"" + "javascript:g_cartouche.doProblemSuggestedFix('" + currently_marked_map_problem['suggestion_id_3'] + "')\">" + currently_marked_map_problem['suggestion_description_3'] + "</a></li>";
	    if (currently_marked_map_problem['suggestion_id_4'].length > 0 && currently_marked_map_problem['suggestion_description_4'].indexOf("Delete segment")<0)
		listElement.innerHTML += "<li  style=\"list-style-position: inside;\"><a style=\"display: inline\" href=\"" + "javascript:g_cartouche.doProblemSuggestedFix('" + currently_marked_map_problem['suggestion_id_4'] + "')\">" + currently_marked_map_problem['suggestion_description_4'] + "</a></li>";
	}
		  
	//          if (currently_marked_map_problem['suggestion_id_1'].length + currently_marked_map_problem['suggestion_id_2'].length + currently_marked_map_problem['suggestion_id_3'].length + currently_marked_map_problem['suggestion_id_4'].length > 0) {
	//          $("#editPanel .contents #problemSuggestedFix").get(0).innerHTML += "</ul>";
	//      }

	<!--          $("#editPanel .contents #problemSuggestedFix").text(currently_marked_map_problem['suggestion_description_1']); -->



	     this.updateAdditionalProblemsInPanel();
    }

    if(count.gps_points==1){
	this._setToolsPanelContents("gps_point_info");
	$("#editPanel .contents #gpsPointDirection").text(Math.floor(currently_marked_gps_point['direction']));
	$("#editPanel .contents #gpsPointWeight").text(Math.floor(currently_marked_gps_point['weight']));
	$("#editPanel .contents #gpsPointCreationTime").text(currently_marked_gps_point['creation_time']);
	$("#editPanel .contents #gpsPointSessionId").text(currently_marked_gps_point['session_id']);
    }

};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.updateAdditionalMarkingsLayer = function(){
    var show = document.roads_form.road_show_turns.checked
    var tc = this;

    var seg_ids = "";
    var node_ids = "";
    var map_problems_ids = "";
    for(var i in tc.featureQueue){
	var type = tc.featureQueue[i].split(".")[0];
	if (type == "roads") {
	    if (seg_ids.length > 0) seg_ids = seg_ids + ",";
	    seg_ids = seg_ids + tc.featureQueue[i].replace("roads.","");
	}
	if (type == "nodes") {
	    if (node_ids.length > 0) node_ids = node_ids + ",";
	    node_ids = node_ids + tc.featureQueue[i].replace("nodes.","");
	}
	if (type == "map_problems") {
	    if (map_problems_ids.length > 0) map_problems_ids = map_problems_ids + ",";
	    map_problems_ids = map_problems_ids + tc.featureQueue[i].replace("map_problems.","");
	}
    }


    if (map_problems_ids.length > 0) {
	tc.additionalMarkingsLayer.mergeNewParams({ 
		_selected_map_problem_id:map_problems_ids
	    });
	tc.additionalMarkingsLayer.setVisibility(true);
    } else {
	if (show && seg_ids.length + node_ids.length > 0) {
	    this.additionalMarkingsLayer.mergeNewParams({ 
		    _selected_segment_ids:seg_ids,
		    _selected_node_ids:node_ids
		});
	    this.additionalMarkingsLayer.setVisibility(true);
	} else {
	    this.additionalMarkingsLayer.mergeNewParams({ 
		    _selected_segment_ids:'',
		    _selected_node_ids:'',
		    _selected_map_problem_id:''
		});
	    this.additionalMarkingsLayer.setVisibility(false);
	}
    }

    //    if ($("#archivePanel").get(0) == undefined || $("#archivePanel").get(0).style.display=="none") {
    //	tc.gmlReports.selector.deactivate();
    //	tc.gmlReports.layer.removeFeatures(tc.gmlReports.layer.features);
    //    }

   this.writeCookie();
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.doSelectionUpdates = function(){
    this.updateAdditionalMarkingsLayer();
    this.featuresUpdated();
}

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.showGPSPointsSessionForMapProblem = function(sessionId){
    document.gps_points_form.gps_points_arrows.checked = true;
    //    this._initLayersPanel();
    this.markGPSPointSession(sessionId);
    Layers.gpsPointsLayer.setVisibility(true);
    $("#gps_points").addClass("selectedLayer");
    $("#gps_points_view").show();
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.editFeature = function(count){
		
    //find out the feature type
    var type = null;
    for(var next in count)
	if(count[next]>0)
	    type = next;
		   
    var feature_info = this.factory.FEATURE_TYPES[type];
		  
    var msg = null; 
    if(count[type] > 1){
	var nid = "#"+feature_info.noun_id;
	msg = count[type]+" "+$(nid+" .plural").text()
	    }
		
    this._setToolsPanelContents(type+"_tools", msg);


    var details =  this.factory.mergeDetails(this.selectedFeatures,type);
    this.updateEditPanelForm(details);
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.updateEditPanelForm = function(details){
		
    var contentsQ =  $("#editPanel .contents");
    $("input,select,textarea",contentsQ).each(function(){
	    var name = this.name;
	    if(details[name]){
			
		if($(this).attr("type") == "checkbox"){
		
		    this.checked = (details[name] == "true");
		    //if(details[name]==this.value)
		    //    $(this).val(details[name]);
		}
		else
		    this.value = details[name];
	    }
	});
		  
    $(".stats div",contentsQ).each(function(){
	    $("span:empty",this).prepend(details[this.id]);
	});
		
    $("#user span a",contentsQ).text(details["user_name"]);
    $("#user span span",contentsQ).text($("#user_ranks #rank-"+details["user_rank"]).text());
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.editRoadGeometry = function(){
    var tc = this;
    tc.hideFeaturesNumbering();

    this.modifyControl.activate();
    this._setToolsPanelContents('edit_road_geometry_tools', null, ' (' + this.selectedFeatures[this.featureQueue[0]].details.street_name + ')');
    count = this._countFeatures();
    if(count.roads==1) {
	//	var obj = {};
	var feature = this.selectedFeatures[this.featureQueue[0]].vector;
	this.modifyControl.originalGeometry =feature.geometry.clone();
	this.modifyControl.selectFeature(feature);
    }
	   
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.exitEditRoadGeometry =  function(){

    if(this.modifyControl.feature){
		
	this.modifyControl.layer.eraseFeatures(this.modifyControl.feature);
	this.modifyControl.feature.geometry = this.modifyControl.originalGeometry;
	this.modifyControl.layer.drawFeature(this.modifyControl.feature);
    }
		
    this.modifyControl.deactivate();
    this.doSelectionUpdates();
    this.updateToolsPanel();
};
//-------------------------------------------------------------------------------------------------------------------
/* 
   Deselect (or unselect) all selected map features
*/
Cartouche.prototype.deselectAll = function() {

    this.setEditMode("select","true");

    this.selectedFeatures = {};
    this.featureQueue = [];
    if(!this.featuresLayer)
    return;
	this.featuresLayer.removeFeatures(this.featuresLayer.features); //remove all features
    if(this.newFeaturesLayer)
	this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
    if (this.roundaboutModifyControl.feature) 
	this.roundaboutModifyControl.layer.eraseFeatures(this.roundaboutModifyControl.feature);
		  
    this.updateToolsPanel();
    this.doSelectionUpdates();

    for(var i in this.drawing_controls){
	var control = this.drawing_controls[i];
	control.deactivate();
    }
    //    this.featuresUpdated();

};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._isEditDetailsMode = function(){
    return  $("#editPanel .contents span").hasClass("editRoadDetailsMode");
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.deselectFeature = function(feature_id){
		
    var features = this.selectedFeatures[feature_id]["vector"];
    this.featuresLayer.removeFeatures(features);
    delete this.selectedFeatures[feature_id];
		  
    var index = -1;
    for(var i in this.featureQueue)
	if(this.featureQueue[i]==feature_id)
	    index = i;
		  
    if(index>=0)
	this.featureQueue.splice(index,1);
		  
    //if we are in road details edit mode and still have at least on selected road,
    //do not leave this mode, just refresh
    if(this._isEditDetailsMode()){
	this.editRoadDetails();
	return;
    }
		  
    this.updateToolsPanel();
    this.doSelectionUpdates();
};


//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.hideFeaturesNumbering = function(){
    var tc = this;
    for (var i in tc.featuresPopups) {
	var p = tc.featuresPopups[i];
	if (p) tc.map.removePopup(p);
    }   
}

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.refreshFeaturesNumbering = function(){
    var tc = this;
    var index = 1;
    tc.hideFeaturesNumbering();
    tc.featuresPopups = [];
    for(var i in tc.featureQueue){
	var id = tc.featureQueue[i];
	var type = id.split(".")[0];
	var feature = tc.selectedFeatures[id];
	var anchor;
	
	if (feature.details.anchor_hint_x && feature.details.anchor_hint_y) {
	    anchor = new OpenLayers.LonLat(feature.details.anchor_hint_x, feature.details.anchor_hint_y);
	} else {
	    var geom = feature.vector.geometry;
	    geom.calculateBounds();
	    var centeroid = geom.getCentroid();
	    anchor = new OpenLayers.LonLat(centeroid.x, centeroid.y);
	    if (type == 'roads') {
		anchor = geom.getBounds().getCenterLonLat();
	    }
	}
	var popup = new OpenLayers.Popup("chicken",
					 //					 new OpenLayers.LonLat(center.x, center.y),
					 anchor,
						     new OpenLayers.Size(2,2),
					 "&nbsp;" + index + "<span style=\"position: absolute; left: -1px; top: -3px; font-size: 9pt\">&#x2196;</span>",
						     false);
	//	popup.setContentHTML("<span style=\"background-color: black; \">" + index + "</span>");
	index++;
	popup.updateSize();
	popup.setOpacity(0.4);
	popup.setBackgroundColor('#FFA0A0');
	popup.setBorder('30px');
	tc.selectedFeatures[id].popup = popup;
	tc.map.addPopup(popup);
	tc.featuresPopups.push(popup);
	
    }
};

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.featuresUpdated = function(){
    this.permalinkControl.updateLink();
    this.refreshFeaturesNumbering();
};
    

//-------------------------------------------------------------------------------------------------------------------
/*
  Callback, used for ajax request for features where mapped was clicked by the user
*/
Cartouche.prototype.getOnclickCallback = function(allowAddSegment){
		  
    var tc = this;
		  
    var callback = function(feed){
			  
	$(".queryIndicator").hide();

	//no feature found ...
	if($(":ns(http://www.opengis.net/gml,null)",feed).length>0){
			
	    //deselect last selected element
	    if(tc.featureQueue.length==0) {
		///		tc.featuresUpdated();
		tc.doSelectionUpdates();
		return;
	    }
			
	    if (!allowAddSegment) {
		tc.deselectAll();
		//		tc.featuresUpdated();
		return;
	    } else {
		//		tc.deselectFeature(tc.featureQueue[tc.featureQueue.length-1]);
		//		tc.featuresUpdated();
		return;
	    }
	}

	var features = null
			
	var cont = true;
	//            $(":ns(http://www.opengis.net/gml,featureMember)",feed).each(function(){
	$(":ns(http://www.opengis.net/gml,featureMember)",feed).each(function(){
		if (cont) {
		    cont = false;
		    $(this).children().each(function(){
				
			    var feature_id = $(this).attr('fid');
			    if(feature_id.indexOf("roads")>-1)
				feature_id = "roads" +"."+feature_id.split(".")[1];
				
			    var already_selected = tc.selectedFeatures[feature_id] ? true:false;
			    if(already_selected){//deselect this feature
				tc.deselectFeature(feature_id);
				//				tc.featuresUpdated();
				return;
			    }
				 
			    var type = feature_id.split(".")[0];
				
			    if(!allowAddSegment 
			       || (type!="roads" && type!="nodes")
			       || (tc.featureQueue.length > 0 && tc.featureQueue[tc.featureQueue.length-1].split(".")[0] == 'map_problems')
			       ){
				 
				tc._deselectFeatureTypes([type]);
				tc._deselectOtherFeaturesTypes([type]);
				
			    } else {
				// NOT ANYMORE - //we only allow one selected node, so we deselect all nodes anyway, also we do not want nodes and roads selected simoulatniously
				//				tc._deselectOtherFeaturesTypes(["roads"]);
			    }

			    //find the right parsing ...
			    var feature =tc.factory.make(this);
			    if(tc.map.getProjection()=="EPSG:900913"){
				feature.vector.geometry.transform(new OpenLayers.Projection("EPSG:4326"),tc.map.getProjectionObject());
				var anchor_lonlat = new OpenLayers.LonLat(feature.details.anchor_hint_x,feature.details.anchor_hint_y);
				anchor_lonlat.transform(new OpenLayers.Projection("EPSG:4326"),tc.map.getProjectionObject());
				feature.details.anchor_hint_x = anchor_lonlat.lon;
				feature.details.anchor_hint_y = anchor_lonlat.lat;
			    }
				
			    if(feature){
				tc.featuresLayer.addFeatures(feature.vector);
				tc.selectedFeatures[feature_id] =feature;
			    }
				
			    tc.featureQueue.push(feature_id);

			    if (type == "map_problems") {
				//                        var feature_coords = feature.vector.geometry;
				var rect = new OpenLayers.Bounds(
								 $(":ns(http://www.ttt.org/myns,xmin)",this).text(),
								 $(":ns(http://www.ttt.org/myns,ymin)",this).text(),
								 $(":ns(http://www.ttt.org/myns,xmax)",this).text(),
								 $(":ns(http://www.ttt.org/myns,ymax)",this).text()
								 ).toGeometry();

				  if(tc.map.getProjection()=="EPSG:900913")
					rect.transform(new OpenLayers.Projection("EPSG:4326"),tc.map.getProjectionObject());
				//                        alert(feature_coords);
				//                        if (feature_coords.bounds == null) {
				//                        var x = feature_coords.x;
				//                        var y = feature_coords.y;
				//                        tc.map.setCenter(new OpenLayers.LonLat(x, y));
				//                        tc.map.zoomTo(11);
				//                        } else {
				tc.map.zoomToExtent(rect.getBounds());
				tc.map.zoomOut();
				//                        var x = (feature_coords.bounds.left + feature_coords.bounds.right) / 2;
				//                        var y = (feature_coords.bounds.top + feature_coords.bounds.bottom) / 2;
				//                        tc.map.setCenter(new OpenLayers.LonLat(x, y));
				//                        tc.map.zoomTo(11);
				//                        };
				//                        alert(feature_coords);
				currently_marked_map_problem['type'] = $(":ns(http://www.ttt.org/myns,type)",this).text();
				currently_marked_map_problem['priority'] = $(":ns(http://www.ttt.org/myns,priority)",this).text();
				var cur_problem_id = $(":ns(http://www.ttt.org/myns,id)",this).text();
				var points = $(":ns(http://www.opengis.net/gml,Point)",this);
				currently_marked_map_problem['points_num'] = points.length;
				
				// Insert these into an array

				currently_marked_map_problem['street_name_1'] = $(":ns(http://www.ttt.org/myns,street_name_1)",this).text();
				currently_marked_map_problem['street_name_2'] = $(":ns(http://www.ttt.org/myns,street_name_2)",this).text();
				currently_marked_map_problem['street_name_3'] = $(":ns(http://www.ttt.org/myns,street_name_3)",this).text();
				currently_marked_map_problem['street_name_4'] = $(":ns(http://www.ttt.org/myns,street_name_4)",this).text();
				currently_marked_map_problem['segment_id_1'] = $(":ns(http://www.ttt.org/myns,segment_id_1)",this).text();
				currently_marked_map_problem['segment_id_2'] = $(":ns(http://www.ttt.org/myns,segment_id_2)",this).text();
				currently_marked_map_problem['segment_id_3'] = $(":ns(http://www.ttt.org/myns,segment_id_3)",this).text();
				currently_marked_map_problem['segment_id_4'] = $(":ns(http://www.ttt.org/myns,segment_id_4)",this).text();
				currently_marked_map_problem['segment_weight_1'] = $(":ns(http://www.ttt.org/myns,segment_weight_1)",this).text();
				currently_marked_map_problem['segment_weight_2'] = $(":ns(http://www.ttt.org/myns,segment_weight_2)",this).text();
				currently_marked_map_problem['segment_weight_3'] = $(":ns(http://www.ttt.org/myns,segment_weight_3)",this).text();
				currently_marked_map_problem['segment_weight_4'] = $(":ns(http://www.ttt.org/myns,segment_weight_4)",this).text();
				currently_marked_map_problem['segment_bbox_1'] = $(":ns(http://www.ttt.org/myns,segment_bbox_1)",this).text();
				currently_marked_map_problem['segment_bbox_2'] = $(":ns(http://www.ttt.org/myns,segment_bbox_2)",this).text();
				currently_marked_map_problem['segment_bbox_3'] = $(":ns(http://www.ttt.org/myns,segment_bbox_3)",this).text();
				currently_marked_map_problem['segment_bbox_4'] = $(":ns(http://www.ttt.org/myns,segment_bbox_4)",this).text();
				currently_marked_map_problem['suggestion_id_1'] = $(":ns(http://www.ttt.org/myns,suggestion_id_1)",this).text();
				currently_marked_map_problem['suggestion_description_1'] = $(":ns(http://www.ttt.org/myns,suggestion_description_1)",this).text();
				currently_marked_map_problem['suggestion_id_2'] = $(":ns(http://www.ttt.org/myns,suggestion_id_2)",this).text();
				currently_marked_map_problem['suggestion_description_2'] = $(":ns(http://www.ttt.org/myns,suggestion_description_2)",this).text();
				currently_marked_map_problem['suggestion_id_3'] = $(":ns(http://www.ttt.org/myns,suggestion_id_3)",this).text();
				currently_marked_map_problem['suggestion_description_3'] = $(":ns(http://www.ttt.org/myns,suggestion_description_3)",this).text();
				currently_marked_map_problem['suggestion_id_4'] = $(":ns(http://www.ttt.org/myns,suggestion_id_4)",this).text();
				currently_marked_map_problem['suggestion_description_4'] = $(":ns(http://www.ttt.org/myns,suggestion_description_4)",this).text();
				currently_marked_map_problem['suggestion_relevant_session_ids_1'] = $(":ns(http://www.ttt.org/myns,suggestion_relevant_session_ids_1)",this).text();
				currently_marked_map_problem['suggestion_relevant_session_ids_2'] = $(":ns(http://www.ttt.org/myns,suggestion_relevant_session_ids_2)",this).text();
				currently_marked_map_problem['suggestion_relevant_session_ids_3'] = $(":ns(http://www.ttt.org/myns,suggestion_relevant_session_ids_3)",this).text();
				currently_marked_map_problem['suggestion_relevant_session_ids_4'] = $(":ns(http://www.ttt.org/myns,suggestion_relevant_session_ids_4)",this).text();


				currently_marked_map_problem['session_id_1'] = $(":ns(http://www.ttt.org/myns,session_id_1)",this).text();
				currently_marked_map_problem['weight'] = $(":ns(http://www.ttt.org/myns,weight)",this).text();
				currently_marked_map_problem['data_file_name'] = $(":ns(http://www.ttt.org/myns,data_file_name)",this).text();
				currently_marked_map_problem['origin'] = $(":ns(http://www.ttt.org/myns,origin)",this).text();
				currently_marked_map_problem['resolvable'] = $(":ns(http://www.ttt.org/myns,resolvable)",this).text();
				currently_marked_map_problem['id'] = $(":ns(http://www.ttt.org/myns,id)",this).text();

				currently_marked_map_problem['resolve_resolution'] = $(":ns(http://www.ttt.org/myns,resolve_resolution)",this).text();
				currently_marked_map_problem['resolve_resolver_user_id'] = $(":ns(http://www.ttt.org/myns,resolve_user_id)",this).text();
				currently_marked_map_problem['resolve_resolver_user_name'] = $(":ns(http://www.ttt.org/myns,resolve_resolver_user_name)",this).text();
				currently_marked_map_problem['resolve_update_date'] = $(":ns(http://www.ttt.org/myns,resolve_update_date)",this).text();
				currently_marked_map_problem['resolve_reason'] = $(":ns(http://www.ttt.org/myns,resolve_reason)",this).text();

				var pindex = 0;
				currently_marked_map_problem['additional_problems_id_0'] = '';
				currently_marked_map_problem['additional_problems_id_1'] = '';
				currently_marked_map_problem['additional_problems_id_2'] = '';
				currently_marked_map_problem['additional_problems_id_3'] = '';
				currently_marked_map_problem['additional_problems_id_4'] = '';
				currently_marked_map_problem['additional_problems_id_5'] = '';
				currently_marked_map_problem['additional_problems_id_6'] = '';
				currently_marked_map_problem['additional_problems_id_7'] = '';

				$(".map_problems_refresh_indicator").show();





				
				var mRectText = (parseFloat($(":ns(http://www.ttt.org/myns,xmin)",this).text()) - 0.0006) + ',' + (parseFloat($(":ns(http://www.ttt.org/myns,ymin)",this).text()) - 0.0006) + ',' + (parseFloat($(":ns(http://www.ttt.org/myns,xmax)",this).text()) + 0.0006) + ',' + (parseFloat($(":ns(http://www.ttt.org/myns,ymax)",this).text()) + 0.0006);
				tc.onclick(null, '', mRectText, cur_problem_id, 10, 
					   function(localFeed) {
				
					       $(":ns(http://www.opengis.net/gml,featureMember)",localFeed).each(function(){
						       $(this).children().each(function(){
					
							       var type = $(this).attr('fid').split(".")[0];
					
							       if (type == "map_problems") {
								   if ($(":ns(http://www.ttt.org/myns,id)",this).text() != cur_problem_id) { // Don't add the main one
								       currently_marked_map_problem['additional_problems_id_' + pindex] = $(":ns(http://www.ttt.org/myns,id)",this).text();
								       currently_marked_map_problem['additional_problems_type_' + pindex] = $(":ns(http://www.ttt.org/myns,type)",this).text();
								       currently_marked_map_problem['additional_problems_priority_' + pindex] = $(":ns(http://www.ttt.org/myns,priority)",this).text();
						
								       var rectText = ($(":ns(http://www.ttt.org/myns,xmin)",this).text()) + ',' + ($(":ns(http://www.ttt.org/myns,ymin)",this).text()) + ',' + ($(":ns(http://www.ttt.org/myns,xmax)",this).text()) + ',' + ($(":ns(http://www.ttt.org/myns,ymax)",this).text());
								       currently_marked_map_problem['additional_problems_bbox_' + pindex] = rectText;
								       pindex++;
								   }
							       }
							   }
							   );
						   });
					       $(".map_problems_refresh_indicator").hide();
					       tc.updateAdditionalProblemsInPanel();
					   });
				
				
			    }


			    if (type == "gps_points") {
				currently_marked_gps_point['direction'] = $(":ns(http://www.ttt.org/myns,angle)",this).text();
				currently_marked_gps_point['weight'] = $(":ns(http://www.ttt.org/myns,weight)",this).text();
				currently_marked_gps_point['creation_time'] = $(":ns(http://www.ttt.org/myns,creation_time)",this).text();
				currently_marked_gps_point['session_id'] = $(":ns(http://www.ttt.org/myns,session_id)",this).text();
			    }
				
			if (type=="update_requests")
			{
				
				var lonlat = new OpenLayers.LonLat(feature.vector.geometry.x,feature.vector.geometry.y);
				tc.map.setCenter(lonlat);
				
			}
				
			    var count = tc._countFeatures();
			    if(tc._isEditDetailsMode() && count.roads == count.overall)
				tc.editRoadDetails();
			    else if(tc._isEditDetailsMode() && count.landmarks == count.overall)
				tc.editLandmarkDetails();
			    else if(tc._isEditDetailsMode() && count.landmark_points == count.overall)
				tc.editLandmarkPointDetails();
			    else
				tc.updateToolsPanel();
				
				var num_pending="";
				for(var i in tc.featureQueue)
					if(tc.featureQueue[i].indexOf("roads")==0)
						num_pending+= tc.featureQueue[i].replace("roads.","")+",";
		
				num_pending = num_pending.replace(/\,$/,"");//remove trailing comma
				if(num_pending.length > 0)
					$.getJSON("/KART/pending",data={"num_pending":num_pending},function(json){
						
						
						if(!json.success ||  json.value == 0 )
							return;
						
						if(count.roads==1)
							tc.displayEditPanelMessage("Warning: The selected road is pending for deletion",is_error=true);
							
						if(count.roads>1 && (count.roads==json.value))
							tc.displayEditPanelMessage("Warning: All selected roads are pending for deletion",is_error=true);
							
						if(count.roads>json.value)
							tc.displayEditPanelMessage("Warning: Some of the selected roads are pending for deletion",is_error=true);
							
					});
				   
			});
			 
		}
	    });

	tc.doSelectionUpdates();
	
	
	//	tc.featuresUpdated();
    }
		  
    return callback;
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._getFeatureTypeString = function(){

    var str="";
    var layers = this.map.layers;
    for(var i in layers){
	var next = layers[i];
	if(next.getVisibility()){
		var type = this.layerNameToType(next.name);
		 if( type && type!="aerial")
			str = type+ ","+str;
	}
    }
		   
    str = str.replace(/(^landmarks)|(,landmarks)/,"$&,landmark_points");//regexp explanation: match either 'roads' in beginning of string or ',roads' elsewhere and concat to the match the string ',nodes'
    if(!this._isEditDetailsMode())//in this mode we select nodes as well
	str = str.replace(/(^roads)|(,roads)/,"$&,nodes");//regexp explanation: match either 'roads' in beginning of string or ',roads' elsewhere and concat to the match the string ',nodes'

    return str.substring(0,str.length-1);//remove the last comma
		   
};
//-------------------------------------------------------------------------------------------------------------------
/*
  handler for clicks on the map
*/
Cartouche.prototype.onclick = function(e, forceSegmentId, forceBounds, forceMapProblemId, maxFeatures, forceCallback, forceAddFeature, forceNodeId, forceGPSPointId,forceUpdateRequestId){

    if(this.mode=="add_node"){
	var lonlat = this.map.getLonLatFromViewPortPx(e.xy);
	this.addNode(lonlat);
	return;
    }
    else if(this.mode=="remove_node"){
	var lonlat = this.map.getLonLatFromViewPortPx(e.xy);
	this.removeNode(lonlat);
	return;
    }

    this.modifyControl.deactivate();
    this.moveModifyControl.deactivate();
    this.landmarkModifyControl.deactivate();
    var url=this.wfs_server;
    var bounds, minXY, maxXY;       
    var localMaxFeatures = maxFeatures;
    if (!localMaxFeatures) localMaxFeatures = 1;
    var tolerance = 7;
    var featuresTypes;
    var boundsText;       
    if (e != null) {
	var lonlat = this.map.getLonLatFromViewPortPx(e.xy);
		   
	this.map.queryPoint = this.map.getLonLatFromPixel(
							  new OpenLayers.Pixel(e.xy.x, e.xy.y));
		   
	minXY = this.map.getLonLatFromPixel(
					    new OpenLayers.Pixel(e.xy.x-tolerance, e.xy.y+tolerance));
	maxXY = this.map.getLonLatFromPixel(
					    new OpenLayers.Pixel(e.xy.x+tolerance, e.xy.y-tolerance));
		   
	bounds = new OpenLayers.Bounds(minXY.lon, minXY.lat, maxXY.lon, maxXY.lat);
	if(this.map.getProjection()=="EPSG:900913")
		bounds.transform(this.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));
	
	
	boundsText = bounds.toBBOX();
	forceSegmentId = '';
	forceNodeId = '';
	forceMapProblemId = '';
	featuresTypes = this._getFeatureTypeString()
	    } else {
	if (forceSegmentId && forceSegmentId.length > 0) {
	    boundsText = forceBounds;
	    featuresTypes = 'roads';
	    if (forceSegmentId == 'ANY') forceSegmentId = '';
	}
	if (forceNodeId && forceNodeId.length > 0) {
	    boundsText = forceBounds;
	    featuresTypes = 'nodes';
	}
	if (forceMapProblemId && forceMapProblemId.length > 0) {
	    boundsText = forceBounds;
	    featuresTypes = 'map_problems';
	}
	if (forceGPSPointId && forceGPSPointId.length > 0) {
	    boundsText = forceBounds;
	    featuresTypes = 'gps_points';
	}
	if (forceUpdateRequestId && forceUpdateRequestId.length > 0) {
	    boundsText = forceBounds;
	    featuresTypes = 'update_requests';
	}
    };
    if (forceGPSPointId == undefined) forceGPSPointId='';
    if (forceNodeId == undefined) forceNodeId='';
    if (forceSegmentId == undefined) forceSegmentId='';
    if (forceMapProblemId == undefined) forceMapProblemId='';
    if (forceUpdateRequestId == undefined) forceUpdateRequestId='';
    // now create request url for features
    var params ={
	SERVICE: "WFS",
	VERSION: "1.0.0",
	REQUEST: "GetFeature",
	TYPENAME:featuresTypes,
	MAXFEATURES: localMaxFeatures,
	BBOX: boundsText,
	WIDTH: Layers.gpsPointsLayer.tileSize.w,
	_GPS_POINTS_ARROWS:document.gps_points_form.gps_points_arrows.checked,
	_GPS_POINTS_COLORS:document.gps_points_form.gps_points_colors.value,
	_GPS_POINTS_FILTER_USER_TRACKS:document.gps_points_form.filter_user_tracks.checked,
	_GPS_POINTS_FILTER_LOW_WEIGHT:document.gps_points_form.filter_low_weight.checked,
	_GPS_POINTS_USER_ID:logged_in_user_id,
	_MARK_SESSION_ID:document.gps_points_form.marked_session_id.value,
	_MAP_PROBLEMS_CITY_NAME:document.map_problems_filter_form.city_name.value,
	_MAP_PROBLEMS_STREET_NAME:document.map_problems_filter_form.street_name.value,
	_MAP_PROBLEMS_FILTER_MANAGED_AREA:document.map_problems_filter_form.filter_managed_area.checked,
	_MAP_PROBLEMS_FILTER_NEXT_TO_USER_SEGMENTS:document.map_problems_filter_form.filter_next_to_user_segments.checked,
	_MAP_PROBLEMS_FILTER_BY_DAYS:document.map_problems_filter_form.map_problems_filter_by_days.value,
	_MAP_PROBLEMS_USER_ID:logged_in_user_id,
	_MAP_PROBLEMS_TYPE_FILTER:document.map_problems_legend_form.problem_type_filter.value,
	_MAP_PROBLEMS_COLORS:document.map_problems_legend_form.map_problems_colors.value,
	_MAP_PROBLEMS_SHOW_RESOLVED:document.map_problems_legend_form.map_problems_show_resolved.checked,
	_MAP_PROBLEMS_SHOW_LOW_PRIORITY:document.map_problems_legend_form.map_problems_show_low_priority.checked,
	_GPS_POINTS_COLORS:document.gps_points_form.gps_points_colors.value,
	_FORCE_SEGMENT_ID:forceSegmentId,
	_FORCE_NODE_ID:forceNodeId,
	_FORCE_GPS_POINT_ID:forceGPSPointId,
	_FORCE_MAP_PROBLEMS_ID:(forceMapProblemId ? forceMapProblemId : ''),
	_FORCE_UPDATE_REQUEST_ID:forceUpdateRequestId
    }

    if (e != null) {
	var qindQ =  $(".queryIndicator");
	qindQ.css("left", (e.xy.x - 5) + 'px');
	qindQ.css("top", (e.xy.y - 5) + 'px');
	qindQ.show();
    } else {
	e = {};
	e.metaKey = false;
	if (forceAddFeature != undefined && forceAddFeature) {
	    e.ctrlKey = true;
	} else {
	    e.ctrlKey = false;
	}
    }

    $.get( url,params,(forceCallback ? forceCallback : this.getOnclickCallback(e.ctrlKey || e.metaKey)), "xml" ) ;
};
//===========================================================================
Cartouche.prototype.epochTimeToString = function(epoch){
    var dDate = new Date();
    var mEpoch = parseInt(epoch); 
    if(mEpoch<10000000000) mEpoch *= 1000; // convert to milliseconds (Epoch is usually expressed in seconds, but Javascript uses Milliseconds)
		
    dDate.setTime(mEpoch)
    return dDate;
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.segmentSelect = function(url,params,center_on){

	var tc = this;
	this.updateAction(url,params,null,"",on_finish=function(json){
	
		if(!(json.value instanceof Array))
			 json.value = [ json.value];
			
		var union = new OpenLayers.Geometry.Collection();
		for(var i in json.value){
		
			var next =  json.value[i];
			var feature_id = "roads" +"."+next.id;
			
			//find the right parsing ...
			var feature =tc.factory.makeRoadFromJSON(next);
			
			if(feature){
				if(tc.map.getProjection()=="EPSG:900913"){
					feature.vector.geometry.transform(new OpenLayers.Projection("EPSG:4326"),tc.map.getProjectionObject());
					var anchor_lonlat = new OpenLayers.LonLat(feature.details.anchor_hint_x,feature.details.anchor_hint_y);
					anchor_lonlat.transform(new OpenLayers.Projection("EPSG:4326"),tc.map.getProjectionObject());
					feature.details.anchor_hint_x = anchor_lonlat.lon;
					feature.details.anchor_hint_y = anchor_lonlat.lat;
				}
					
				union.addComponents([feature.vector.geometry]);
				tc.featuresLayer.addFeatures(feature.vector);
				tc.selectedFeatures[feature_id] =feature;
			}
				
			tc.featureQueue.push(feature_id);
			
			
		
		}
		
		if(center_on){
			union.calculateBounds();
			tc.map.zoomToExtent(union.getBounds());
		}
		tc.updateToolsPanel();
		//tc.editRoadDetails();
		tc.featuresUpdated();
		//tc.doSelectionUpdates();
		var count = tc._countFeatures();
			    
		var num_pending="";
		for(var i in tc.featureQueue)
		if(tc.featureQueue[i].indexOf("roads")==0)
			num_pending+= tc.featureQueue[i].replace("roads.","")+",";
		
		num_pending = num_pending.replace(/\,$/,"");//remove trailing comma
		if(num_pending.length > 0)
			$.getJSON("/KART/pending",data={"num_pending":num_pending},function(json){
				
				if(!json.success ||  json.value == 0 )
					return;
				
				if(count.roads==1)
					tc.displayEditPanelMessage("Warning: The selected road is pending for deletion",is_error=true);
					
				if(count.roads>1 && (count.roads==json.value))
					tc.displayEditPanelMessage("Warning: All selected roads are pending for deletion",is_error=true);
					
				if(count.roads>json.value)
					tc.displayEditPanelMessage("Warning: Some of the selected roads are pending for deletion",is_error=true);
					
			});
	
	});

}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.multiSegmentSelect = function(){

	
	var start_seg_id = null;
	var end_seg_id = null;
	
	var seg_ids = [];
	for(var i in this.selectedFeatures)
		seg_ids.push(this.selectedFeatures[i].details.id);
		
	this.segmentSelect("/KART/multi_segment_select",{start_seg_id:seg_ids[0],end_seg_id:seg_ids[1]});
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.editRoadDetails = function(){

    var count = this._countFeatures();
    if(count.nodes !=0)
	throw "ERROR - edit road only roads are selected or no features at all"

	    if(count.roads==0){
		this._setToolsPanelContents("edit_road_details_tools_no_roads");
		return;
	    }

    this._setToolsPanelContents("edit_road_details_tools");
	
  

    if(count.roads > 1)
	$("#editPanel .selectedFeatures").append(" (" + count.roads+ " " + $("#road_noun .plural").text() +" )");
	
	
    var details =  this.factory.mergeDetails(this.selectedFeatures,"roads");
    this.setAlternativeStreetNames(details["id"]);
    
    $("#countryInput input").show();
    $("#selectCountryDDL").remove();
    
     
	$("#country_change_indicator").show();
	var params = {"seg_id":details["id"]};
	$.getJSON(url="/KART/CrossCountrySeg",data=params,function(json){

			$("#country_change_indicator").hide();
			if(!json.success)
				return;

			if(json.value.length==1 && json.value[0]==$("#countryInput input").val())
				return;

			$("#countryInput input").hide();
			$("#selectCountryDDL").remove();

			var s="<select id='selectCountryDDL'>";
			var alt_c = json.value;
			for(var c in alt_c)
				s+="<option value='"+alt_c[c]+"'>"+alt_c[c]+"</option>";
	
			s+="</select>";
	
			$(s).insertAfter($("#countryInput input"));
			$("#selectCountryDDL option[value='"+details["country_name"]+"']").attr("selected","selected");
			$("#selectCountryDDL").change(function(){ 
				$("#countryInput input").val($("#selectCountryDDL").val());
			});
	
	
	});	
	  
    
    this.updateEditPanelForm(details);
    var contentsQ =  $("#editPanel .contents");

    this.addAutoComplete("editPanel");

    var time = details["from_cross_time"];
    if(details["to_cross_time"] && details["to_cross_time"].length>0 && details["to_cross_time"]!=time)
	time+="/"+details["to_cross_time"];

    //replace some text with correct values 
    $("#cross_time span",contentsQ).eq(0).text(time);
    var road_speed= (details["road_speed"] && details["road_speed"].length > 0) ? details["road_speed"] : "0";
    var measurement_system = $(".measurement_system").text();
    if(measurement_system=="metric")
	$("#road_speed span",contentsQ).eq(0).text(Math.round(parseInt(details["road_speed"])*3.6));
    else
	$("#road_speed span",contentsQ).eq(0).text(Math.round(parseInt(details["road_speed"])*(3600/1609.344)));
		
    $("#update_user span a",contentsQ).prepend(details["update_user"]);
    //    $("#update_time span a",contentsQ).prepend(this.epochTimeToString(details["update_time"]));
    //    $("#update_time span",contentsQ).prepend(this.epochTimeToString(details["update_time"]));
    //    $("#update_time span",contentsQ).prepend(Date());
    

};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.setAlternativeStreetNames = function(seg_id){
	
	if (seg_id.indexOf(",")>-1)//check if there's more than 1 street
		return;

	//only on street
	var params = {"seg_id":seg_id};
	$("#open_archive_indicator_alt_street").show();
	$.getJSON(url="/KART/getStreetAlternativeNames",data=params,function(json){
		var names=eval("("+json.reason+")");
		$("#open_archive_indicator_alt_street").hide();
		for(var i=0;i<names.names.length;i++)
		{
			var alias = $("<tr id='"+"street_name_id_"+$("#editPanel .street_name_row").length+"'></tr>");
			$("#editPanel .street_name_row:last").after(alias);
			alias.html($("#alt_street_name_row_mold").html());
			alias.addClass("street_name_row");
			$("input",alias).attr("name","street_name_"+$("#editPanel .street_name_row").length);
			$("input",alias).val(names.names[i]);
			$("th",alias).css("width","57px");
			
			$(".removeAliasStreet",alias).click(function(){
			
				$(this).parent().remove();
				
			});
			$(".removeAliasStreet",alias).hover(function(){
			
				$(this).css("cursor","hand");
				
			},function(){
				$(this).css("cursor","pointer");
			});
			
			/*
			var alt = $("<tr class='street_name_row ac_input'><th>Street:</th><td class='alt_street_name'><input name='street_name' value='"+names.names[i]+"'></input></td></tr>");
			$("input",alt).attr("name","street_name_"+$("#editPanel .street_name_row").length);
			$(alt).insertAfter($(".street_name_row"));*/
			
		}
		  
		  
		
	});
			


};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.exitEditRoadDetails = function(){
    this.updateToolsPanel();
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.resetData = function(){
    $("#editPanel .contents :input:not(:hidden)").each(function(){this.value=""});
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.addNewFeature = function(){
		  
    this.selectedFeatures = {};
    this.featureQueue = [];
    this.featuresLayer.removeFeatures(this.featuresLayer.features); //remove all features
    this.newFeaturesLayer.removeFeatures( this.newFeaturesLayer.features);//remove any existing new features
    this._setToolsPanelContents('add_feature_tools');
};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.addRoad = function(){
	this.deselectAll();
    this.setEditMode("");
    $("#cartouche").css("cursor","crosshair");
    $("#editPanel .contents a").removeClass("selected");
    $("#editPanel .contents a#add_road").addClass("selected");	
    this.drawRoadControl.activate();
		 
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.addRoadFreehand = function(){
	$("#editPanel .contents a").removeClass("selected");
	$("#editPanel .contents a#add_road_freehand").addClass("selected");
		
	this.drawRoadFreehandControl.activate();
		 
};
//-------------------------------------------------------------------------------------------------------------------
 Cartouche.prototype.setEditMode = function(mode,fromDeselect){
    
    var tc = this;
    
    if(mode=="select"){
	if (fromDeselect!="true")
		tc.deselectAll();
	$("#editPanel .contents a").removeClass("selected");
    	$("#editPanel .contents a#select_tool").addClass("selected");   	 
    	$("#cartouche").css("cursor","default");
	$("#editPanel .allow_all_turns").slideUp('slow');
	this.mode="select";
    }
    else if(mode=="add_node"){
	tc.deselectAll();
	$("#editPanel .contents a").removeClass("selected");
    	$("#editPanel .contents a#add_junction").addClass("selected");
    	$("#cartouche").css("cursor","pointer");
	$("#editPanel .allow_all_turns").slideDown('slow');
	this.mode="add_node";
	
	if(this.allow_all_turns)
		$("#editPanel [name='allow_all_turns']").attr('checked','true');

	$("#editPanel [name='allow_all_turns']").change(function(){
		if($(this).is(':checked'))		
			tc.allow_all_turns = true;
		else
			tc.allow_all_turns = false;
	});
	
    }
    else if(mode=="remove_node"){
    tc.deselectAll();
	$("#editPanel .contents a").removeClass("selected");
    	$("#editPanel .contents a#remove_junction").addClass("selected");
    	$("#cartouche").css("cursor","pointer");
	this.mode="remove_node";
    }
    else{
	$("#editPanel .allow_all_turns_toggle").slideUp('slow');
    }

};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.exitAddFeature = function(){
	  
    this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
    this.drawRoadControl.deactivate();
    this.drawRoadFreehandControl.deactivate();
    this.drawLandmarkControl.deactivate();
    this.drawLandmarkFreehandControl.deactivate();
    this.drawLassoControl.deactivate();
    this.drawLassoFreehandControl.deactivate();
    //this.drawNodeControl.deactivate();
    this.updateToolsPanel();
};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.preLogout = function(){
    //    is_user_area_manager = false;
    logged_in_user_data = {};
    logged_in_user_id = '';
    //    this.initMapProblemsView();
    //    this._initPanels();
    this.getOnViewChanged()();
		
};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.logout = function(){
	  
    var tc = this;
    var  onLogout = function(response){
	tc.preLogout();
		 
	var json = eval("("+response+")");
	if(!json.reply.login){
	    tc.updateToolsPanel();
		  
	    $("#open_archive").hide();
	    $("#compile_client_map").hide();
	    $(".layersContainer .layer#map_problems #refresh_label").hide();
	}
    }
		 
    Login.logout(onLogout);
};
//------------------------------------------------------------------------------------------------------------------- 

Cartouche.prototype.displayEditPanelMessage = function(message,is_error){

    $("#editPanel .contents .error, #editPanel .contents .message").remove();
    var class_name = is_error ? "error" : "message";
    //    var title = message;
    //    title = title.replace('->', '\n');
    //    $("#editPanel .contents").prepend("<div class='"+class_name+"' title=\""+title+"\">"+message+"</div>");
	$("#editPanel .contents").prepend("<div class='"+class_name+"'>"+message+"</div>");
}
//------------------------------------------------------------------------------------------------------------------- 

Cartouche.prototype.displayViewPanelMessage = function(message,is_error){

    if(is_error){
	if($("#viewPanel .message .error").length == 0)
	    $("#viewPanel .message").prepend("<div class='error'>"+message+"</div>");
	else
	    $("#viewPanel .message .error").text(message); 
    }
    else
	$("#viewPanel .message .error").remove();
		
};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.saveNewRoad =function(){
		
    var geom = this.newFeaturesLayer.features[0].geometry;
		
    var polyline = "";
    for(var i in geom.components){
	var p = geom.components[i];
	polyline+=p.x+","+p.y+" ";
    }
		
    var additionalParams = {"the_geom":polyline};
    this.saveEditDetails(additionalParams);

};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.saveSpeedCamDetails = function(){

	var measurement_system = $(".measurement_system").text();
	var cam_speed = $("#editPanel input[name=cam_speed]").val();
	if(measurement_system == "imperial"){
			cam_speed = Math.round(parseInt(cam_speed)* 1.609);
	}
	var additionalParams = {"cam_speed":cam_speed};
		
		this.uploadEditPanelForm("/map_edit/update.php", "roads"/*$("#editPanel form input[name=update_property]").val()*/,deselect_on_success=true,additionalParams);
//	this.saveEditDetails(additionalParams);
}
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.saveEditDetails = function(additionalParams){

$("#countryInput input").show();
    $("#selectCountryDDL").remove();
    this.uploadEditPanelForm("/KART/update", "roads"/*$("#editPanel form input[name=update_property]").val()*/,deselect_on_success=true,additionalParams);
		
};
//-------------------------------------------------------------------------------------------------------------------

Cartouche.prototype.uploadEditPanelForm = function(upload_url,feature_type_affected,deselect_on_success,additionalParams){
		
	var tc = this;
		
	var params = {separator:"false",locked:"false"};//init checkbox fields with false since otherwise they will not be sent when their value is false
	$.each($("#editPanel form").serializeArray(),function(){
		if(this.name == "update_property")
			params["update_type"]=this.value;
		else
			params[this.name]=this.value;
	});

	//add additional params if any ...
	if(additionalParams)
		for(var key in additionalParams)
			params[key] = additionalParams[key];
	    
	var geom = null;
	if(tc.featureQueue.length == 0)///this is a new road
		geom = tc.newFeaturesLayer.features[0].geometry;
	
	this.editFeatureAction(upload_url,params,geom,feature_type_affected,null,null,on_fail=function(json,message){
		
		if(json.reason!="missing feature")
			return;

		var create_features_dialog = $("#create_features_dialog").modal({
					containerCss: {
					    height: 150,
					    width: 280
					},

					onShow:function(){
						
						if(json.value.missing=="city")
							$("#create_features_dialog .city_to_add td:eq(1)").text(params.city_name);
						else
							$("#create_features_dialog .city_to_add").hide()

						if(json.value.missing=="city" || json.value.missing=="street" || json.value.missing.indexOf("street_name_")>-1)
							if ( json.value.missing.indexOf("street_name_")>-1)
								$("#create_features_dialog .street_to_add td:eq(1)").text(params[json.value.missing]);
							else
								$("#create_features_dialog .street_to_add td:eq(1)").text(params.street_name);
						else
							$("#create_features_dialog .street_to_add").hide();
						
						$("#create_features_dialog .create_features").unbind();
						$("#create_features_dialog .create_features").click(function(){
							create_features_dialog.close();
							params["create_if_missing"]=true;
							tc.editFeatureAction(upload_url,params,geom,feature_type_affected,null,null);
							return false;
						});	

						$("#create_features_dialog .cancel").unbind();
						$("#create_features_dialog .cancel").click(function(){
							create_features_dialog.close();
							return false;
						});	
						
					}
		});
/*
		if (json.reason=="missing feature" && json.value.missing=="city")
			tc.addCityStreet(params,true);

		if (json.reason=="missing feature" && json.value.missing=="street")
			tc.addCityStreet(params,false);
*/	
	});
		
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.updateAction = function(url,params,feature_types_affected,success_msg,on_finish,on_fail){
	
	var tc = this;
	
	$("#editPanel #applyFixIndicator").show();
	$("#editPanel .contents").fadeTo(1, 0.3);
	this.requiresLogin(function(){
		
		$.post(url,data=params,function(json){
	     
			$("#editPanel .contents").fadeTo(0.3, 1);
			$("#editPanel #applyFixIndicator").hide();
			if(json.reply && json.reply.error){
				tc.displayEditPanelMessage(json.reply.message,is_error=true);
				if(on_fail)
					on_fail(json,json.reply.message);
			}
			else if(!json.reply && !json.success){
				if (json.reason=="missing feature")
				{
					if (json.value.missing=="city")
						tc.displayEditPanelMessage("missing city and street",is_error=true);
					else
						tc.displayEditPanelMessage("missing street",is_error=true);
				}
				else
				tc.displayEditPanelMessage(json.reason,is_error=true);
				if(on_fail)
					on_fail(json,json.reason);
			}
			else{
				tc.modifyControl.deactivate();
				tc.redrawFeatureType(feature_types_affected);
				tc.deselectAll();
				
				var message = "";
				if(success_msg)
					message = success_msg;
				else if(json.reply)
					message = json.reply.message;
				else
					message = json.reason;
				
				tc.displayEditPanelMessage(message);
				
				if(on_finish)
					on_finish(json,message);
			}
	    
		},'json');
	    
	},revert_to_previous_contents=true);
	
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.updateActionConfirm = function(url,params,feature_types_affected,success_msg,on_finish){
	
	var tc = this;
	this.requiresConfirm(function(){
		tc.updateAction(url,params,feature_types_affected,success_msg,on_finish);
	    
	},revert_to_previous_contents=true);
	
	
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.editSegmentAction = function(url,params,geom,success_msg,on_finish,on_fail){
	this.editFeatureAction(url,params,geom,"roads",success_msg,on_finish,on_fail);
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.editFeatureAction = function(url,params,geom,feature_types_affected,success_msg,on_finish,on_fail){
	
	
	if(geom){
		var geom_projected = null;
		if(this.map.getProjection()=="EPSG:900913"){
			geom_projected = geom.clone();
			geom_projected.transform(this.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));
		}
		else 
			geom_projected = geom;
		
		var polyline = "";
		for(var i in geom_projected.getVertices()){
			var p = geom_projected.getVertices()[i];
			polyline+=p.x+","+p.y+" ";
		}
		if(geom_projected.CLASS_NAME== "OpenLayers.Geometry.Polygon"){
			var p = geom_projected.getVertices()[0];
			polyline+=p.x+","+p.y+" ";
		}
		
		params["the_geom"]=polyline;
		params["change_geom"] = true;
	}
	
	this.updateAction(url,params,feature_types_affected,success_msg,on_finish,on_fail)
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.saveEditRoadGeometry = function(){ 
	   
	var params = {};
	var details =this.selectedFeatures[this.featureQueue[0]].details;
	var vector = this.selectedFeatures[this.featureQueue[0]].vector;
	
	for(var next in details)
		params[next]=details[next];
		
	this.editSegmentAction("/KART/update",params,vector.geometry);
};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.saveUpdateRequest = function(){
		
	var params = $("#editPanel form").serialize();
	var type = $("#editPanel form input[name=update_property]").val(); 
	var url = "/KART/update_request";
	var map_url = $(".olControlPermalink a").get(0).href;
	params+="&url="+encodeURIComponent(map_url);
	this.updateAction(url,params,type)
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.deleteFeatures = function(){
		
	var type = $("#editPanel form input[name=update_property]").val(); 
	var url = "/map_edit/delete.php";
	var params = $("#editPanel form").serialize();
	params = params.replace("update_property","type");
	this.updateActionConfirm(url,params,type);
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.redrawFeatureType = function(types){
		  
    if(!types)
	return;
	
    if(typeof types == "string")
	types = [types];
	
    for(var i in types){
	var type = types[i];
	var layers =this.typeToLayers(type);
	for(var j in layers)
		layers[j].redraw(true);
    }
    
    this.mapViewChanged();
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.requiresLogin = function(operation,revert_to_previous_contents,indicate){
		
    var tc = this;
		
    Login.isLoggedIn(function(logged_in){
		
	    if(logged_in){
		operation();
	    }
	    else{
		$("#editPanel .contents").fadeTo(0.3, 1);
		$("#editPanel #applyFixIndicator").hide();
		tc.showLoginForm(operation,revert_to_previous_contents);
		if(indicate)
		    $("#editPanel").effect("shake", { times: 3 ,direction:"up"}, 80);
	    }
	});
};

//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.getRequiresLogin = function(operation,revert_to_previous_contents){
		
    var tc = this;
    return function(){
	tc.requiresLogin(operation,revert_to_previous_contents);
    }
};

//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.getRequiresConfirm = function(operation){
    
    var tc = this;
    return function(){
	tc.requiresConfirm(operation);
    }
};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.showLoginForm = function(onLoginSuccess,revert_to_previous_contents,last_login_error){
		
    if(!last_login_error){//only save the panel on a fresh login ... otherwise it is just saving the login contents
		
	contents = {};
	contents.width = $("#editPanel").width();
	contents.html = $("#editPanel .contents").remove();
	this.edit_panel_contents_stack.push(contents);
		
	$("#editPanel").append("<div class='contents'></div>");
    };
    //$(".user").hide();
    this._setToolsPanelContents("login_tools");
		
    var tc = this;
    $("#loginForm").keypress(function(e){
	    if(e.which==13){//enter key
		tc.login(onLoginSuccess,revert_to_previous_contents);
		return false;
	    }
	});
		
    if(last_login_error)
	$("#editPanel .contents").prepend("<div class='error'>Login failed: "+last_login_error+"</div>");
		  
    $("#loginForm #submit").click(function(e){
	    tc.login(onLoginSuccess,revert_to_previous_contents);
	    return false;
	});
		 
    $("#loginForm input").eq(0).focus();//focus on first input field
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.requiresConfirm = function(operation, importance){
    var tc = this;

    HotKeys.add('y', function(e) {
	    tc.revertEditPanelContents();
	    operation();
	    return false;
	}, {disable_in_input:true});
    HotKeys.add('n', function(e) {
	    tc.revertEditPanelContents();
	    return false;
	}, {disable_in_input:true});
		
    this.showConfirm(operation, importance);
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.showConfirm = function(operation, importance){
		
    $("#editPanel #exclamation").hide();
    contents = {};
    contents.width = $("#editPanel").width();
    contents.html = $("#editPanel .contents").remove();
    this.edit_panel_contents_stack.push(contents);
    $("#editPanel").append("<div class='contents'></div>");
		
    this._setToolsPanelContents("confirm_tools");

    if (importance) {
	$("#editPanel #exclamation").show();

	if (importance == 2) $("#editPanel").effect("shake", { times: 1 ,direction:"up"}, 100);
	//        $("#refresh_label").effect("shake", { times: 1 ,direction:"right"}, 50);
    }
		
    var tc = this;
	
	   
    $("#editPanel #yes").click(function(e){
	    tc.revertEditPanelContents();
	    operation();
	    return false;
    });


};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.revertEditPanelContents = function(){
		
    HotKeys.remove('y');
    HotKeys.remove('n');

    if(this.edit_panel_contents_stack==0)
	return;
		
    //$("#editPanel .user").show();
    $("#editPanel .contents").hide();
		
		
    var contents = this.edit_panel_contents_stack.pop();
		
    //revert to the first contents ...
    //while(this.edit_panel_contents_stack.length > 0)
    //    contents = this.edit_panel_contents_stack.pop();
		
    $("#editPanel").width(contents.width);
    $("#editPanel .contents").replaceWith(contents.html);
    $("#editPanel .contents").fadeIn("slow");
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.login = function(onLoginSuccess,revert_to_previous_contents){

    var tc = this;
    var onLogin = function(result,message, user_id, _logged_in_user_data){
	if(result){
	    //            is_user_area_manager = (area_manager == 't');
	    logged_in_user_data = _logged_in_user_data;
	    logged_in_user_id = user_id;
	    tc.getOnViewChanged()();
	    if(onLoginSuccess){
			
		if(revert_to_previous_contents)
		    tc.revertEditPanelContents();
			
		onLoginSuccess();
	    }
	    else
		tc.updateToolsPanel();
			
	    $("#open_archive").show();
	    if (logged_in_user_data.staff && logged_in_user_data.staff == 't') {
			$("#compile_client_map").show();
	    }
	    nav_refresh_logged_status();
					    
	    if($("#map_problems").hasClass("selectedLayer") && tc.map.zoom>=min_refresh_problems_zoom && tc.map.zoom<=max_refresh_problems_zoom)				//**************************************************************************************************************************
		$(".layersContainer .layer#map_problems #refresh_label").show();
	}
	else
	    tc.showLoginForm(onLoginSuccess,revert_to_previous_contents,message);
    }

    Login.formLogin("loginForm",onLogin);
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.updatePanelsViews = function(tc){
    tc.initGPSPointsView();
    tc.getOnViewChanged()();
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.refreshOnExternalLogin = function(){

    this.updatePanelsViews(this);
		
    $("#open_archive").show();

    if (logged_in_user_data.staff && logged_in_user_data.staff == 't') {
	$("#compile_client_map").show();
	$("#fleet").show();
    }
    if($("#map_problems").hasClass("selectedLayer") && this.map.zoom>=min_refresh_problems_zoom && this.map.zoom<=max_refresh_problems_zoom)
	$(".layersContainer .layer#map_problems #refresh_label").show();
		
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.refreshOnExternalLogout = function(){

    this.updatePanelsViews(this);
			
    $("#open_archive").hide();
    $("#fleet").hide();
    $("#compile_client_map").hide();
		
    if($("#map_problems").hasClass("selectedLayer")){
	$(".layersContainer .layer#map_problems #refresh_label").hide();
    }
		
};
//--------------------------------------------------------------------------------------------------------------------
//Assumes this.featureQueue contains two elements
/*Cartouche.prototype.mergeRoads = function(){
    this.roadManipulation("/map_edit/merge_segments.php");
};*/
//--------------------------------------------------------------------------------------------------------------------
//Assumes this.featureQueue contains at least two elements
Cartouche.prototype.disconnectRoadsFromNode = function(raise){

	var params = {
				is_raise: raise ? true:false,
				seg_ids:""
				};
				
	//add selected segs
	for(var i in this.featureQueue)
		params.seg_ids+= this.featureQueue[i].replace("roads.","")+",";
		
	params.seg_ids = params.seg_ids.replace(/\,$/,"");//remove trailing comma
		
	this.editSegmentAction("/KART/bridge_segments",params);
		
}
//--------------------------------------------------------------------------------------------------------------------
//Assumes this.featureQueue contains the right two elements
Cartouche.prototype.disconnectRoadFromNode = function(){

	var params = {};
	var url = "/KART/disconnect_segment_node";
	
	//add seg and node
	
	for(var i in this.featureQueue){
		if(this.featureQueue[i].indexOf("roads")==0)
			params.seg_id= this.featureQueue[i].replace("roads.","");
		if(this.featureQueue[i].indexOf("nodes")==0)
			params.node_id= this.featureQueue[i].replace("nodes.","");
	}	
	this.editSegmentAction(url,params,null,"Disconnect done.");
};
//--------------------------------------------------------------------------------------------------------------------
//Assumes this.featureQueue contains the right three elements
Cartouche.prototype.moveRoadBetweenNodes = function(){
    this.roadManipulation("/map_edit/move_road_between_nodes.php");
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.raiseRoadLevelToMaximum = function(){
    this.roadManipulation("/map_edit/change_road_level.php", null, {action: 'to-top'});
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.lowerRoadLevelToMinimum = function(){
    this.roadManipulation("/map_edit/change_road_level.php", null, {action: 'to-bottom'});
};
//--------------------------------------------------------------------------------------------------------------------
//Assumes this.featureQueue contains two elements
Cartouche.prototype.connectRoads = function(){

	var params = {
		seg_ids:""
	};
			
	//add selected segs
	for(var i in this.featureQueue)
		params.seg_ids+= this.featureQueue[i].replace("roads.","")+",";
		
	params.seg_ids = params.seg_ids.replace(/\,$/,"");//remove trailing comma
	this.updateAction("/KART/connect_segments",params,"roads","Segments connected.");
  
};
//--------------------------------------------------------------------------------------------------------------------
//Assumes this.featureQueue contains two elements
Cartouche.prototype.disconnectRoads = function(){

    var params = {};
			
    //add selected segs
    params.from_seg_id= this.featureQueue[0].replace("roads.","");
    params.to_seg_id= this.featureQueue[1].replace("roads.","");
		
    this.updateAction("/KART/restrict_turn",params,"roads","Turning restricted.");
};
//--------------------------------------------------------------------------------------------------------------------
//Assumes this.featureQueue contains two elements
Cartouche.prototype.bridge = function(){

    var params = {};
			
   var params = {seg_ids:""};
	for(var i in this.featureQueue)
		params.seg_ids+=this.featureQueue[i].replace("roads.","")+",";
	
	params.seg_ids = params.seg_ids.replace(/\,$/,"");//remove trailing comma
		
    this.updateAction("/WAS/bridge_segments",params,"roads","Roads bridges.");
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.oneWayToTwoWay = function(){
	var url = "/KART/separate_segment";
	var params = {id:this.featureQueue[0].replace("roads.","")};
	this.editSegmentAction(url,params,null,"Road separated to two one directional roads.");
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.reverseRoadDirection = function(){
	var url = "/KART/reverse_segments";
	var params = {seg_ids:""};
	for(var i in this.featureQueue)
		params.seg_ids+=this.featureQueue[i].replace("roads.","")+",";
	
	params.seg_ids = params.seg_ids.replace(/\,$/,"");//remove trailing comma
	this.editSegmentAction(url,params,null,"Road/s reversed.");
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.deleteRoad = function(){

	var url = "/KART/delete_segments";
	var params = {ids:""};
	//add selected segs
	for(var i in this.featureQueue)
		params.ids+= this.featureQueue[i].replace("roads.","")+",";
		
	params.ids = params.ids.replace(/\,$/,"");//remove trailing comma
	this.del_ids = params.ids;
	
	this.updateActionConfirm(url,params,"roads",null,function(){
		$("#editPanel .contents #undo_delete").show();
	});
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.undoDeleteRoad = function(){

	var params = {id: this.del_ids};
	var url ="/KART/undo_delete";
	this.updateAction(url,params,["roads","restrictions"],null,function(){
		$("#editPanel .contents #undo_delete").hide();
	});
}
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.roadManipulation = function(manipulation_url,onSuccess, additionalParams, noDeselect, importance, noIdParam, noConfirmation, noRefreshLayers, sendGeometry){
	   
	var tc = this;
	var func =  this.getRequiresLogin(function(){

				 var params = {};
				 //add additional params if any ...
				 if(additionalParams)
				     for(var key in additionalParams)
					 params[key] = additionalParams[key];


				 if(tc.featureQueue.length==1) {
				     params["id"] =  tc.featureQueue[0].replace("roads.","");
				     params["id"] =  params["id"].replace("landmarks.","");
				     params["id"] =  params["id"].replace("landmark_points.","");
				     if (tc.featureQueue[0].indexOf(".") > 0) {
					 params["update_type"] = tc.featureQueue[0].substr(0, tc.featureQueue[0].indexOf("."));
				     }
				 } else {
				     params["id"] = "";
				     var seg_num = 1;
				     var node_num = 1;
				     for(var i in tc.featureQueue){
					 var type = tc.featureQueue[i].split(".")[0];
					 if (type == "roads") {
					     if (sendGeometry) {
						 var geom = tc.selectedFeatures[tc.featureQueue[i]].vector.geometry;
						 var polyline = "";
						 for(var ii in geom.components){
						     var p = geom.components[ii];
						     polyline+=p.x+","+p.y+" ";
						 }
						 params["seg_the_geom" + seg_num] = polyline;
						 
					     }
					     params["seg"+(seg_num++)] = tc.featureQueue[i].replace("roads.","");
					 } else if (type == "nodes") {
					     params["node"+(node_num++)] = tc.featureQueue[i].replace("nodes.","");
					 }
					 if (params["id"].length > 0) params["id"] = params["id"] + ",";
					 params["id"] = params["id"] + tc.featureQueue[i].replace("roads.","");
				     }
				 }
			  
				 if (noIdParam) delete params["id"];

				 var url = manipulation_url;
			
				 $("#editPanel #applyFixIndicator").show();
				 $("#editPanel .contents").fadeTo(1, 0.3);
				 var resultCallback = function(response){
				     $("#editPanel .contents").fadeTo(0.3, 1);
				     $("#editPanel #applyFixIndicator").hide();
				     var json = eval("("+response+")");
				     if(json.reply && json.reply.error){
					 tc.revertEditPanelContents();
					 tc.displayEditPanelMessage(json.reply.message,is_error=true);
				     }
				     else{
					 if(!json.successful && json.reason){
					     tc.revertEditPanelContents();
					     tc.displayEditPanelMessage(json.reason,is_error=true);
					 }
					 else{
			
					     var msg = json.reply ? json.reply.message : json.reason;
					     tc.displayEditPanelMessage(msg,is_error=false);
					     if (!noRefreshLayers) {
						 tc.redrawFeatureType("roads");
						 tc.redrawFeatureType("landmarks");
						 tc.redrawFeatureType("restrictions");
					     }
					     
					     if (!noDeselect) 
						tc.deselectAll();
					    
					     if(onSuccess)
						 onSuccess(json.reply);
					 }
				     }
				 }

				 $.get( url, params,resultCallback ) ;
			     });
    if (!noConfirmation) this.requiresConfirm(func, importance); else func();
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.getParseRoundabout = function(){
		
    var tc = this;
    return function(response){
	var roundabout_vectors = [];
	$(":ns(http://www.opengis.net/gml,LineString) :ns(http://www.opengis.net/gml,coordinates)",response).each(function(){
		
		var geo_str = $.trim($(this).text()).split(" ");
		var geometry = new OpenLayers.Geometry.LineString();
		for(var i in geo_str){
		    var next_point_str  = geo_str[i].split(",");
		    var x = parseFloat(next_point_str[0]);
		    var y = parseFloat(next_point_str[1]);
		    geometry.addPoint(new OpenLayers.Geometry.Point(x=x,y=y));
			
		}
		var vec = new OpenLayers.Feature.Vector(geometry=geometry);
		vec.style = {strokeWidth:4,strokeColor: "#000",strokeOpacity:0.8,pointRadius: 10,fillColor:"transparent",fillOpacity:0.3};
		roundabout_vectors.push(vec);
	    });
		
	tc.newFeaturesLayer.removeFeatures(tc.newFeaturesLayer.features);
	tc.newFeaturesLayer.addFeatures(roundabout_vectors);
	tc.featuresLayer.removeFeatures(tc.selectedFeatures[tc.featureQueue[0]].vector);
    }
		
};

/* NEW ROUNDABOUT */
//-------------------------------------------------------------------------------------------------------------------  
Cartouche.prototype.cancelCreateRoundabout = function(){

    //restore node display
    this.roundaboutModifyControl.deactivate();
    this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
    var feature =this.selectedFeatures[this.featureQueue[0]].vector;
    this.featuresLayer.addFeatures(feature);
    this.updateToolsPanel();
};

//-------------------------------------------------------------------------------------------------------------------  
Cartouche.prototype.saveNewRoundabout = function(){
	   
	this.roundaboutModifyControl.deactivate();
	params = {
		radius:$("#editPanel form [name=radius]").val(),
		node_id:this.featureQueue[0].replace("nodes.","")//,
		//longitude:$("#editPanel form [name=longitude]").val(),
		//latitude:$("#editPanel form [name=latitude]").val()
	}

	var start = this.map.getLonLatFromViewPortPx(new OpenLayers.Pixel(0,0));
	var end = this.map.getLonLatFromViewPortPx(new OpenLayers.Pixel(20,0));

	var buffer = new OpenLayers.LonLat(end.lon - start.lon,end.lat - start.lat);

	if(this.map.getProjection()=="EPSG:4326")
		buffer.transform(this.map.getProjectionObject(),new OpenLayers.Projection("EPSG:900913"));

	params["metric_buffer"] = Math.abs(buffer.lon);
	this.updateAction("/KART/create_roundabout",params,"roads","Roundabout created.");
};

//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.updateRoundaboutDisplay = function(){
    var tc = this;
    //    var params = $("#editPanel form").serialize();
    var node = tc.selectedFeatures[tc.featureQueue[0]];
    var point = node.vector.geometry.clone();
    var params =  { "longitude": $("#editPanel .contents input[name=longitude]").val(),
    		    "latitude": $("#editPanel .contents input[name=latitude]").val(),
    		    "radius": $("#editPanel .contents input[name=radius]").val()
    }


    if (!params.longitude || params.longitude < 1) {
	params.longitude = point.x;
	params.latitude = point.y;
    }
    
    
    if (!params.radius || params.radius < 1) {
	params.radius = 10; // DEFAULT
    }

	
    tc.updateEditPanelForm(params);
   
//   if(this.map.getProjection()=="EPSG:900913")
//		bounds.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));

    var geom = null;
    
    if(tc.map.getProjection()=="EPSG:900913")
	geom = OpenLayers.Geometry.Polygon.createRegularPolygon(point, params.radius, 50, 0);
    else
	geom = OpenLayers.Geometry.Polygon.createRegularPolygon(point, params.radius / simpleDegreesToMetersRatio, 50, 0);
	
    var vec = new OpenLayers.Feature.Vector(geometry=geom);
    
    vec.style = {strokeWidth:4,strokeColor: "#000",strokeOpacity:0.8,pointRadius: 10,fillColor:"transparent",fillOpacity:0.3};
    //		roundabout_vectors.push(vec);

//     var coordinates =$.trim(coordinatesStr).split(" ");

//     var pline = new OpenLayers.Geometry.LineString();
//     for(var i in coordinates){
// 	var point = coordinates[i].split(",");
// 	pline.addPoint(new OpenLayers.Geometry.Point(x=point[0],y=point[1]));
//     }
//     var polyline_vector = new OpenLayers.Feature.Vector(geometry=pline);


    //	var feature = this.selectedFeatures[this.featureQueue[0]].vector;
    if (true) {
	tc.roundaboutModifyControl.activate();
	//    var feature = polyline_vector;
	var feature = vec;
	
	if (this.newFeaturesLayer.features) this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
	if (this.roundaboutModifyControl.feature) tc.roundaboutModifyControl.layer.eraseFeatures(this.roundaboutModifyControl.feature);
	
	tc.newFeaturesLayer.addFeatures(feature);
	this.roundaboutModifyControl.originalGeometry =feature.geometry.clone();
	this.roundaboutModifyControl.selectFeature(feature);
    }
};
//--------------------------------------------------------------------------------------------------------------------
/**
 * assumes feature queue has one feature init - a node
 */
Cartouche.prototype.createRoundabout = function(){
		
    var tc = this;

    
	tc.requiresLogin(function(){

	    var node = tc.selectedFeatures[tc.featureQueue[0]];
	    var point = node.vector.geometry.clone();
	    
	    
	    $("#editPanel #createRoundaboutForm").keypress(function(e){
		    if(e.which==13){//enter key
			tc.saveNewRoundabout();
			return false;
		    }
		    
		    return true;
		});
	    
	    $("#editPanel .contents input[name=radius]").keypress(function (e){
		    
		    
		    var character = String.fromCharCode(e.which);
		    if (character.match(/[\d\s\b]/g)) {
			return true;
		    }
		    else {
			return false;
		    }
		    
		});
	    
	    
	    var bounds = tc.map.getExtent();
	    
	    // now create request url for features
	    
	    //var bounds = OpenLayers.Bounds.fromSize(new OpenLayers.Size(5,5));
	    
	    //bounds = bounds.scale(ratio=1,origin=lonlat);
	   
	    
	    
	     if(tc.map.getProjection()=="EPSG:900913")
			point.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));
	
	    var params ={
		SERVICE: "WFS",
		VERSION: "1.0.0",
		REQUEST: "GetFeature",
		TYPENAME:"best_fit_gps_points_cluster",
		MAXFEATURES: 2,
		BBOX: bounds.toBBOX(),
		_CENTER_X: point.x,
		_CENTER_Y: point.y,
		WIDTH: Layers.gpsPointsLayer.tileSize.w
	    }
	    
	    
	    
		tc._setToolsPanelContents("create_roundabout_tools");
		tc.updateRoundaboutDisplay();
	    
    
	},revert_to_previous_contents=true,indicate=true);


	    return;


    var url = "/map_edit/draw_circle.php";
		
    $("#editPanel #applyFixIndicator").show();
    $("#editPanel .contents").fadeTo(1, 0.3);
    var resultCallback = function(response){
	$("#editPanel .contents").fadeTo(0.3, 1);
	$("#editPanel #applyFixIndicator").hide();
	 
	tc.getParseRoundabout()(response);
	params["radius"]=$(":ns(http://www.ttt.org/myns,radius)",response).eq(0).text();
	tc._setToolsPanelContents("create_roundabout_tools");
	tc.updateEditPanelForm(params);
		
	$("#editPanel #createRoundaboutForm").keypress(function(e){
		if(e.which==13){//enter key
		    tc.saveNewRoundabout();
		    return false;
		}
			
		return true;
	    });
		
	$("#editPanel .contents input[name=radius]").keypress(function (e){
			
			
		var character = String.fromCharCode(e.which);
		return character.match(/[\d\s\b]/g);

	    });
		
		  
    }

    $.post( url, params,resultCallback ) ;
	   
};
/* NEW ROUNDABOUT */


//-------------------------------------------------------------------------------------------------------------------
/**
   Assumes only one node is selected
*/
Cartouche.prototype.saveMoveNode = function(){

		//rl,params,feature_types_affected,success_msg,on_finish,on_fail
		var tc = this;
		//updateActionConfirm = function(url,params,feature_types_affected,success_msg,on_finish)
		 
		var node = tc.selectedFeatures[tc.featureQueue[0]];
		var point = node.vector.geometry.clone();
		//var feature = tc.selectedFeatures[tc.featureQueue[0]].vector;
		
		if(this.map.getProjection()=="EPSG:900913")
			point.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));
			
		var params =  { "id":node.details.id,"longitude": point.x, "latitude": point.y };
		
		this.updateAction("/map_edit/move_node.php",params,"nodes","Node moved");
		
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.removeAllTurnRestrictions = function(){

	var node = this.selectedFeatures[this.featureQueue[0]];
	var feature = node.vector;
	var params =  { "node_id":node.details.id };
	var url = "/KART/allow_all_turns";
	
	var tc = this;
	this.updateAction(url,params,["nodes","restrictions"],"Update done",
		on_finish=function(){
			tc.dragNodeControl.originalGeometry =feature.geometry.clone();
		},
		on_fail=function(){
			tc.featuresLayer.removeFeatures(feature);
			feature.geometry = tc.dragNodeControl.originalGeometry.clone();
			tc.featuresLayer.addFeatures(feature);
		}
	);
	
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.restrictAllTurns = function(){

	var node =this.selectedFeatures[this.featureQueue[0]];
	
	var params =  { "node_id":node.details.id };
	var url = "/KART/restrict_all_turns";
	
	var tc = this;
	var vec = node.vector;
	this.updateAction(url,params,["nodes","restrictions"],"Update done",
		on_finish=function(){
			tc.dragNodeControl.originalGeometry =vec.geometry.clone();
		},
		on_fail=function(){
			tc.featuresLayer.removeFeatures(vec);
			vec.geometry = tc.dragNodeControl.originalGeometry.clone();
			tc.featuresLayer.addFeatures(vec);
		}
	);
}
//-------------------------------------------------------------------------------------------------------------------
/*
Cartouche.prototype.deleteNode = function(){

	var params = {node_id:this.featureQueue[0].replace("nodes.","")};
	this.updateAction("/KART/delete_node",params,"nodes","Node deleted");
}*/
 //----------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.exitMoveNode  = function(){

	var feature = this.selectedFeatures[this.featureQueue[0]].vector;
		
	this.featuresLayer.eraseFeatures(feature);
	feature.geometry = this.dragNodeControl.originalGeometry;
	feature.style = this.factory.FEATURE_TYPES.nodes.style;
	this.featuresLayer.drawFeature(feature);
		
	this.dragNodeControl.deactivate();
	this.updateToolsPanel();

};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.onAddressPick = function(e){
       
          this.modifyControl.deactivate();
          var lonlat = this.map.getLonLatFromViewPortPx(e.xy);
          var url=this.wfs_server;
         var bounds, minXY, maxXY;
        var tolerance = 5;

          minXY = this.map.getLonLatFromPixel(
                          new OpenLayers.Pixel(e.xy.x-tolerance, e.xy.y+tolerance));
          maxXY = this.map.getLonLatFromPixel(
                          new OpenLayers.Pixel(e.xy.x+tolerance, e.xy.y-tolerance));

          bounds = new OpenLayers.Bounds(minXY.lon, minXY.lat, maxXY.lon, maxXY.lat);

          // now create request url for features
	  
	  //var bounds = OpenLayers.Bounds.fromSize(new OpenLayers.Size(5,5));
	
	  //bounds = bounds.scale(ratio=1,origin=lonlat);
	
          var params ={
                  SERVICE: "WFS",
                  VERSION: "1.0.0",
                  REQUEST: "GetFeature",
                  TYPENAME:"roads",
                  MAXFEATURES: 2,
                  BBOX: bounds.toBBOX()
          }
          
           var qindQ =  $(".queryIndicator");
           qindQ.css("left", (e.xy.x - 5) + 'px');
           qindQ.css("top", (e.xy.y - 5) + 'px');
           qindQ.show();

		
	var newNodeVector = new OpenLayers.Feature.Vector();
	newNodeVector.style = {strokeWidth:4,strokeColor: "cyan",strokeOpacity:0.8,pointRadius: 10,fillColor:"transparent",fillOpacity:0.3};
	
	this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
	this.newFeaturesLayer.addFeatures(newNodeVector);
	
	var tc = this;
        
	tc.aux_split_road = "";
	$.get( url,params,function(feed){
		
		$(".queryIndicator").hide();
		//no feature found ...
		if($(":ns(http://www.opengis.net/gml,null)",feed).length>0)
                            return;
                    
		var contains_selected_road = false;
		$(":ns(http://www.ttt.org/myns,roads)",feed).each(function(){
		
			var feature_id = $(this).attr('fid');
			if(feature_id!=tc.featureQueue[0])
				tc.aux_split_road = feature_id;
			else
				contains_selected_road = true;
				
		});
		
		if(!contains_selected_road)
			return;

		$("#editPanel #save_street_number:hidden").show();
		$("#editPanel #house_number_even").show();
		$("#editPanel #house_number_odd").show();
		tc.featuresLayer.removeFeatures(newNodeVector);
		newNodeVector.geometry = new OpenLayers.Geometry.Point(x=lonlat.lon,y=lonlat.lat);
		tc.featuresLayer.addFeatures(newNodeVector);
		
	}, "xml" ) ;
          
     }
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.addStreetNumber = function(){/*
     this._setToolsPanelContents("add_street_number_tools");
     $("#editPanel #save_street_number").hide();
     this.map.events.unregister("click", this, this.onclick);
     this.map.events.register("click", this, this.onAddressPick);*/
   //  this.modifyControl.deactivate();
  this._setToolsPanelContents("add_street_number_tools");
//		$("#editPanel #save_street_number:hidden").show();
//		$("#editPanel #house_number_even").show();
//		$("#editPanel #house_number_odd").show();
		
		     
     
     var feature=this.selectedFeatures[this.featureQueue[0]].details;
     var pointsArr= new Array();
     var arrowLenght=0.0005;
     var arrowHeadLenght=0.00025;
     
	var hint_point = new OpenLayers.LonLat(feature.anchor_hint_x,feature.anchor_hint_y);
	     
	pointsArr[0]=new OpenLayers.Geometry.Point(hint_point.lon,hint_point.lat);
     
   
	var arrowHead = null;
	if(this.map.getProjection()=="EPSG:900913"){
		var hint_clone = hint_point.clone();
		hint_clone.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));
		arrowHead=new OpenLayers.Geometry.Point(hint_clone.lon*1.0+Math.sin(feature.azimuth * Math.PI/ 180)*arrowLenght*1.0,
											 hint_clone.lat*1.0+Math.cos(feature.azimuth* Math.PI/ 180)*arrowLenght*1.0);
		arrowHead.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
	}
	else
		arrowHead=new OpenLayers.Geometry.Point(feature.anchor_hint_x*1.0+Math.sin(feature.azimuth * Math.PI/ 180)*arrowLenght*1.0,
										     feature.anchor_hint_y*1.0+Math.cos(feature.azimuth* Math.PI/ 180)*arrowLenght*1.0);
										     
	
		
     pointsArr[1]=(arrowHead);
  
     var directionFeatureVector= new OpenLayers.Feature.Vector();
     directionFeatureVector.geometry=new OpenLayers.Geometry.LineString(pointsArr);
     directionFeatureVector.style = {strokeWidth:6,strokeColor: "#fbe105",strokeOpacity:1,pointRadius: 5,fillColor:"#fbe105",fillOpacity:1};
     this.featuresLayer.addFeatures(directionFeatureVector);
     
     
     var leftArrowVector= new OpenLayers.Feature.Vector();
     var leftArrowPointArr=new Array();
     leftArrowPointArr[0]=arrowHead;
     
     if(this.map.getProjection()=="EPSG:900913"){
	var hint_clone = hint_point.clone();
	hint_clone.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));
	leftArrowPointArr[1]=new OpenLayers.Geometry.Point(hint_clone.lon*1.0+Math.sin(feature.azimuth * Math.PI/ 180)*arrowLenght*1.0+arrowHeadLenght*Math.sin((feature.azimuth-135)*Math.PI/180)*1.0,hint_clone.lat*1.0+Math.cos(feature.azimuth* Math.PI/ 180)*arrowLenght*1.0+arrowHeadLenght*Math.cos((feature.azimuth-135)*Math.PI/180)*1.0);
	leftArrowPointArr[1].transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
     }
     else
	leftArrowPointArr[1]=new OpenLayers.Geometry.Point(feature.anchor_hint_x*1.0+Math.sin(feature.azimuth * Math.PI/ 180)*arrowLenght*1.0+arrowHeadLenght*Math.sin((feature.azimuth-135)*Math.PI/180)*1.0,feature.anchor_hint_y*1.0+Math.cos(feature.azimuth* Math.PI/ 180)*arrowLenght*1.0+arrowHeadLenght*Math.cos((feature.azimuth-135)*Math.PI/180)*1.0);
     
     leftArrowVector.geometry= new OpenLayers.Geometry.LineString(leftArrowPointArr);
     leftArrowVector.style = {strokeWidth:6,strokeColor: "#fbe105",strokeOpacity:1,pointRadius: 5,fillColor:"#fbe105",fillOpacity:1};
     this.featuresLayer.addFeatures(leftArrowVector);
     
     
     var rightArrowVector= new OpenLayers.Feature.Vector();
     var rightArrowPointArr=new Array();
     rightArrowPointArr[0]=arrowHead;
     if(this.map.getProjection()=="EPSG:900913"){
	var hint_clone = hint_point.clone();
	hint_clone.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));
	rightArrowPointArr[1]=new OpenLayers.Geometry.Point(hint_clone.lon*1.0+Math.sin(feature.azimuth * Math.PI/ 180)*arrowLenght*1.0+arrowHeadLenght*Math.sin((feature.azimuth-225)*Math.PI/180)*1.0,hint_clone.lat*1.0+Math.cos(feature.azimuth* Math.PI/ 180)*arrowLenght*1.0+arrowHeadLenght*Math.cos((feature.azimuth-225)*Math.PI/180)*1.0);
	rightArrowPointArr[1].transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
     }
     else
	  rightArrowPointArr[1]=new OpenLayers.Geometry.Point(feature.anchor_hint_x*1.0+Math.sin(feature.azimuth * Math.PI/ 180)*arrowLenght*1.0+arrowHeadLenght*Math.sin((feature.azimuth-225)*Math.PI/180)*1.0,feature.anchor_hint_y*1.0+Math.cos(feature.azimuth* Math.PI/ 180)*arrowLenght*1.0+arrowHeadLenght*Math.cos((feature.azimuth-225)*Math.PI/180)*1.0);

     rightArrowVector.geometry= new OpenLayers.Geometry.LineString(rightArrowPointArr);
     rightArrowVector.style = {strokeWidth:6,strokeColor: "#fbe105",strokeOpacity:1,pointRadius: 5,fillColor:"#fbe105",fillOpacity:1};
     this.featuresLayer.addFeatures(rightArrowVector);
     
}
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.addNode = function(lonlat){
	
	var tc = this;
	var params = {};
	var point = lonlat.clone();    
	var start = this.map.getLonLatFromViewPortPx(new OpenLayers.Pixel(0,0));
	var end = this.map.getLonLatFromViewPortPx(new OpenLayers.Pixel(10,0));

	var buffer = new OpenLayers.LonLat(end.lon - start.lon,end.lat - start.lat);

	if(tc.map.getProjection()=="EPSG:900913")
		point.transform(tc.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));
	else
		buffer.transform(tc.map.getProjectionObject(),new OpenLayers.Projection("EPSG:900913"));

	params["metric_buffer"] = Math.abs(buffer.lon);
		  	
	params["lon"] = point.lon;
	params["lat"] = point.lat; 
	params["allow_all_turns"] = $("#editPanel [name='allow_all_turns']:checked").val()? true : false;

	this.updateActionConfirm("/KART/add_node",params,["roads","restrictions"]);
	
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.removeNode = function(lonlat){
	
	var tc = this;
	var params = {};
	var point = lonlat.clone();   
	var start = this.map.getLonLatFromViewPortPx(new OpenLayers.Pixel(0,0));
	var end = this.map.getLonLatFromViewPortPx(new OpenLayers.Pixel(10,0));
	var buffer = new OpenLayers.LonLat(end.lon - start.lon,end.lat - start.lat);
 
	if(tc.map.getProjection()=="EPSG:900913")
		point.transform(tc.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));
	else
		buffer.transform(tc.map.getProjectionObject(),new OpenLayers.Projection("EPSG:900913"));
	  	
	params["metric_buffer"] = Math.abs(buffer.lon);
	params["lon"] = point.lon;
	params["lat"] = point.lat; 

	this.updateActionConfirm("/KART/remove_node",params,["roads","restrictions"]);
	
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.markProblemAsResolved = function(mapProblemId, reason) {
		
    var tc = this;
    this.requiresLogin(this.getRequiresConfirm(function(){
				 
		var params = {};
				 
		params["map_problem_id"] = mapProblemId;
		params["reason"] = reason;
				 
		var url = "/map_edit/mark_map_problem_as_resolved.php";

		$("#editPanel #applyFixIndicator").show();
		$("#editPanel .contents").fadeTo(1, 0.3);
		var resultCallback = function(response){
		    var json = eval("("+response+")");
		    if(json.reply.error)
			tc.displayEditPanelMessage(json.reply.message,is_error=true);
		    else{
			//                       tc.exitSplitRoad();
			tc.refreshMapProblems();
			//			tc.redrawFeatureType("roads");
			//			tc.redrawFeatureType("line_roads");
			//			tc.redrawFeatureType("restrictions");
			tc.redrawFeatureType("map_problems");
			tc.deselectAll();
		    }         
		    $("#editPanel .contents").fadeTo(0.3, 1);
		    $("#editPanel #applyFixIndicator").hide();
		    tc.displayEditPanelMessage(json.reply.message,is_error=false);
				 
		}
				 
		$.get( url, params,resultCallback ) ;
	    }), revert_to_previous_contents=true, indicate=true);
		
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.saveStreetNumber = function(){
    
    	var tc = this;
   
	var params = {};
      	var point = tc.map.queryPoint.clone();//tc.featuresLayer.features[0].geometry;
      
      	if(this.map.getProjection()=="EPSG:900913")
		point.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));

	if($("#editPanel [name=id]").val())
		params["id"] = $("#editPanel [name=id]").val();
	
	
      	params["longitude"] =point.lon;
      	params["latitude"] =point.lat; 
	
      	params["right_add"]=$("#editPanel [name=right_addr]").val();
      	params["left_add"]=$("#editPanel [name=left_addr]").val();
	if(tc.selectedFeatures[tc.featureQueue[0]].details.azimuth)
      		params["azimuth"]=tc.selectedFeatures[tc.featureQueue[0]].details.azimuth;
	else
		params["azimuth"]=$("#editPanel #magvar span").text();
     
    
	//  url,params,feature_types_affected,success_msg,on_finish,on_fail
	this.updateAction("/KART/changeHouseNumber",params,"street_ranges","");
}
//--------------------------------------------------------------------------------------------------------------------

Cartouche.prototype.doProblemSuggestedFix = function(fixId) {
		
    var tc = this;
    this.requiresLogin(this.getRequiresConfirm(function(){
				 
		var params = {};
				 
		params["fix_id"] = fixId;
				 
		var url = "/map_edit/apply_suggested_map_problem_fix.php";

		$("#editPanel #applyFixIndicator").show();
		$("#editPanel .contents").fadeTo(1, 0.3);
		var resultCallback = function(response){
		    var json = eval("("+response+")");
		    if(json.reply.error)
			tc.displayEditPanelMessage(json.reply.message,is_error=true);
		    else{
			tc.refreshMapProblems();
			tc.redrawFeatureType("roads");
			tc.redrawFeatureType("line_roads");
			tc.redrawFeatureType("restrictions");
			tc.redrawFeatureType("map_problems");
			tc.deselectAll();
		    }         
		    $("#editPanel .contents").fadeTo(0.3, 1);
		    $("#editPanel #applyFixIndicator").hide();
		    tc.displayEditPanelMessage(json.reply.message,is_error=false);
				 
		}
				 
		$.get( url, params,resultCallback ) ;
	    }), revert_to_previous_contents=true, indicate=true);
		
};
//--------------------------------------------------------------------------------------------------------------------      
Cartouche.prototype.previousView = function(){
    this.navHistory.previousTrigger();
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.nextView = function(){
    this.navHistory.nextTrigger();
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.refreshView = function(){

    var layers = this.map.layers;
    $.each(layers,function(){
	    if(this.getVisibility())
		this.redraw(true);
	});
		
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.getOnViewChanged = function(){
		
    var tc = this;
		
    return function(e){
		
	var prevLink = $("#mapControlPanel #previous_view");
	if(tc.navHistory.previousStack.length < 2 && !prevLink.hasClass("disabled"))
	    prevLink.addClass("disabled");
	else
	    if(tc.navHistory.previousStack.length > 1 && prevLink.hasClass("disabled"))
		prevLink.removeClass("disabled");
			
	var nextLink = $("#mapControlPanel #next_view");    
	if(tc.navHistory.nextStack.length < 1 && !nextLink.hasClass("disabled"))
	    nextLink.addClass("disabled");
	else
	    if(tc.navHistory.nextStack.length > 0 && nextLink.hasClass("disabled"))
		nextLink.removeClass("disabled");
			
	var zoomOutLink = $("#mapControlPanel #zoom_out");        
	if(tc.map.zoom == 0 && !zoomOutLink.hasClass("disabled"))
	    zoomOutLink.addClass("disabled");
	else 
	    if(zoomOutLink.hasClass("disabled"))
		zoomOutLink.removeClass("disabled");
			
	var zoomInLink = $("#mapControlPanel #zoom_in");
	if(tc.map.zoom == tc.map.numZoomLevels-1 && !zoomInLink.hasClass("disabled"))
	    zoomInLink.addClass("disabled");
	else 
	    if(zoomInLink.hasClass("disabled"))
		zoomInLink.removeClass("disabled");
			
	var normalScreenLink = $("#mapControlPanel #normal_screen_map_mode");
	var fullScreenLink = $("#mapControlPanel #full_screen_map_mode");
	if (isInFullScreenMode) {
	    normalScreenLink.removeClass("disabled");
	    fullScreenLink.addClass("disabled");
	} else {
	    normalScreenLink.addClass("disabled");
	    fullScreenLink.removeClass("disabled");
	}

	tc.initMapProblemsView();

	if(logged_in_user_data) {
	    $("#open_archive").show();
	   
	    if (logged_in_user_data.staff && logged_in_user_data.staff == 't'){
		$("#compile_client_map").show();
		 $("#fleet").show();
	    }
	    
	}
	if (logged_in_user_data && logged_in_user_data.rank && logged_in_user_data.rank >= 3) {
	    $(".routing_related").show();
	} else {
	    $(".routing_related").hide();
	}


	//save positions in cookie
	tc.writeCookie();
    }
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.writeCookie = function(){

    var extent =  this.map.getExtent();
    if(!extent)
	extent = {left:null,right:null,top:null,bottom:null};
		
    if(this.map.getProjection()=="EPSG:900913" && extent.transform)
	extent.transform(new OpenLayers.Projection("EPSG:900913"),new OpenLayers.Projection("EPSG:4326"));
	
    var map = { 
			left:extent.left,right:extent.right,top:extent.top,bottom:extent.bottom,
			type:"WMS"
    }
			
    var layers = {};        
    $(".layersContainer .layer").each(function(){
	    if(this.id!="fleet")
		layers [this.id] = $(this).hasClass("selectedLayer");
	});
		
    var panels = {};
		
    $(".panel").each(function(){
		
	    var pid = this.id;
	    panels[pid] = {};
	    panels[pid].left = $(this).css("left").replace("px","");
		
	    //fix for IE
	    if(panels[pid].left=="auto"){
		panels[pid].right = $(this).css("right").replace("px","");
	    }
		
	    panels[pid].top = $(this).css("top").replace("px","");
		
	});
    var gpsPointsPrefs = { 
	gps_points_arrows:document.gps_points_form.gps_points_arrows.checked,
	gps_points_colors:document.gps_points_form.gps_points_colors.value,
	filter_low_weight:document.gps_points_form.filter_low_weight.checked
    };



    var boomAdditionalPrefs = { road_show_turns:document.roads_form.road_show_turns.checked};
    var mapProblemsPrefs = { 
	problem_type_filter:document.map_problems_legend_form.problem_type_filter.value,
	map_problems_colors:document.map_problems_legend_form.map_problems_colors.value,
	map_problems_show_resolved:document.map_problems_legend_form.map_problems_show_resolved.checked,
	map_problems_show_low_priority:document.map_problems_legend_form.map_problems_show_low_priority.checked
    };
    
    
    
    var contents = {map:map,layers:layers,panels:panels,version:1,gps_points_prefs:gpsPointsPrefs, boom_additional_prefs:boomAdditionalPrefs, map_problems_prefs:mapProblemsPrefs};
    
    writeMapCookie(contents);
   
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.setMapPositionFromCookie = function(){

	var json =readMapCookie();
	var map_saved = json.map;
		
	var extent = new OpenLayers.Bounds();
	extent.extend(new OpenLayers.LonLat(map_saved.left,map_saved.top));
	extent.extend(new OpenLayers.LonLat(map_saved.right,map_saved.bottom));

	if(this.map.getProjection()=="EPSG:900913")
		extent.transform(new OpenLayers.Projection("EPSG:4326"),new OpenLayers.Projection("EPSG:900913"));
	this.map.zoomToExtent(extent,true);
 
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.getLayersVisibilityFromCookie = function(){

    var json =readMapCookie();
    return json.layers;
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.getPanelsInfoCookie = function(){

    var json = readMapCookie();
    return json.panels;
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.getGPSPointsInfoCookie = function(){

    var json =readMapCookie();
    return json.gps_points_prefs;
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.getBoomAdditionalPrefsInfoCookie = function(){

    var json =readMapCookie();
    return json.boom_additional_prefs;
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.getMapProblemsPrefsInfoCookie = function(){

    var json =readMapCookie();
    return json.map_problems_prefs;
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.zoomIn = function(){
    this.map.zoomIn();
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.zoomOut = function(){
    this.map.zoomOut();
};
//================================================
Cartouche.prototype.createArchivePage = function(page_num,open_archive){

	$("#archivePanel .update_archive").hide();
    $("#open_archive").hide();
    $("#open_archive_indicator").show();
		
    $("#archivePanel tr.report").remove();
    $("#archivePanel .pager").hide();
	
	var tc = this;


	this.requiresLogin(function() {
		    

    //assumes user is logged in
		
	  
	var params_arr = $("#archivePanel .archive_staff_only").serializeArray();
	params_arr.push({name:"page",value:page_num})
	var params = {};
	$.each(params_arr,function(){
		params[this.name] = this.value;
	});
	
	$.getJSON(url="/KART/cartouche/reports_page",data=params,function(json){
		
	    $("#open_archive_indicator").hide();
	    $("#open_archive").show();
		
	    var dateMap = {
		0:"Jan",
		1:"Feb",
		2:"Mar",
		3:"Apr",
		4:"May",
		5:"Jun",
		6:"Jul",
		7:"Aug",
		8:"Sep",
		9:"Oct",
		10:"Nov",
		11:"Dec"
	    };
	    $.each(json.result.page,function(){
			
		    var report = $("<tr class='report'></tr>");
		    report.html($("#archive_report_mold").html());
		    $(report).insertBefore("#archivePanel table #archive_report_mold");
		    $(".userName",report).text(this.userName);
		   // $(".fileName a",report).text(this.fileName ? this.fileName : "none").attr("href","/map_edit/show_file.php?type=gpx&id="+this.dataFileId);
		    $(".fileName a",report).text(this.fileName ? this.fileName : "none").attr("href","/KART/gpx?id="+this.dataFileId);
		    var goolge_maps_link = "/map_edit/show_file.php?type=kml&id=";
		    $(".showRoute .google_earth",report).attr("href","/map_edit/show_file.php?type=kml&id="+this.dataFileId);
		    var measurement_system = $(".measurement_system").text();
		    if(measurement_system == "metric"){
			
			$(".newRoadsInKM",report).text(this.newRoadsInKM);
			$(".knownRoadsInKM",report).text(this.knownRoadsInKM);
		    }
		    else{
			$(".newRoadsInKM",report).text((this.newRoadsInKM / 1.609).toFixed(1));
			$(".knownRoadsInKM",report).text((this.knownRoadsInKM / 1.609).toFixed(1));
		    }    
			
		    var d = new Date(this.endDriveTimeInMillisecs);
		    var formatted = dateMap[d.getMonth()]+" "+d.getDate()+", "+d.getFullYear();
		    $(".driveEndDate",report).text(formatted);
		    $(".merged",report).text(this.merged ? $(".merged .yes",report).text() :$(".merged .no",report).text());
			
			
		    var record = this;
		    $(".gml a",report).click(function(e){
			    g_cartouche.gmlReports.showReport(record.id, record.filename , record.bounds)
				g_cartouche.gmlReports.selector.activate();
			    return false;
			
			});
			
			
		});
		
		
	    $('#archivePanel .report:even').css("background-color","#ccc");
	    //	    $('#archivePanel .pager').aqPaging({ current: json.result.pageIndex, pages: json.result.numPages, css:false,cb: Cartouche.prototype.createArchivePage });
	    $('#archivePanel .pager').aqPaging({ current: json.result.pageIndex, pages: json.result.numPages, css:false,cb: function(page) {tc.createArchivePage(page) }});
	    $("#archivePanel .pager").show();
		
		$("#archivePanel .update_archive").show();
	    if(open_archive)
		$("#archivePanel").fadeIn();
	});
	    },revert_to_previous_contents=true, true);
};
//======================================================================
Cartouche.prototype.openUpdateRequest= function(page_num,open_archive)
{
	$("#open_update_requests").hide();
	$("#open_archive_indicator").show();
	$("#updateRequestPanel tr.report").remove();
	$("#updateRequestPanel .pager").hide();
	var tc = this;
	this.requiresLogin(function() {
		    

    //assumes user is logged in
		if (!page_num)
			page_num=1;
	  
	//var params_arr ={"page":page_num};
	var params = {"page":page_num};
	/*$.each(params_arr,function(){
		params[this.name] = this.value;
	});*/
	
	$.getJSON(url="/KART/update_request_s",data=params,function(json){
		
	    $("#open_archive_indicator").hide();
	    $("#open_update_requests").show();
		
	    var dateMap = {
		0:"Jan",
		1:"Feb",
		2:"Mar",
		3:"Apr",
		4:"May",
		5:"Jun",
		6:"Jul",
		7:"Aug",
		8:"Sep",
		9:"Oct",
		10:"Nov",
		11:"Dec"
	    };
	    var statusMap = {
		0:"closed",
		1:"open",
		2:"field test required",
		3:"missing info"
	    };
	    $.each(json.page,function(){
		
		    var report = $("<tr class='report'></tr>");
		    report.html($("#update_request_report_mold").html());
		    $(report).insertBefore("#updateRequestPanel table #update_request_report_mold");
		    
		    $(".requestUserName",report).text(this.userName);
		    if (this.description.length>80)
			this.description=this.description.substr(0,80)+"...";
		    $(".requestDescription",report).text(this.description);
		       $(".requestStatus",report).text(statusMap[this.status]);
		 
			    var pj=this;
			    var showClick=function(){
			   
									tc.onclick(null, null,pj.bounds, null, null, function(feed) {tc.getOnclickCallback(true)(feed); }, true, null,null,pj.updateId);
									};
		    $(".showRequst",report).click(showClick);
			
		});
		
		
	    $('#updateRequestPanel .report:even').css("background-color","#ccc");
	    //	    $('#archivePanel .pager').aqPaging({ current: json.result.pageIndex, pages: json.result.numPages, css:false,cb: Cartouche.prototype.createArchivePage });
	    $('#updateRequestPanel .pager').aqPaging({ current: json.pageIndex, pages: json.numPages, css:false,cb: function(page) {tc.openUpdateRequest(page) }});
	    $("#updateRequestPanel .pager").show();
		
		$("#updateRequestPanel .update_archive").show();
		if (!open_archive)
		open_archive=true;
	    if(open_archive)
		$("#updateRequestPanel").fadeIn();
	});
	    },revert_to_previous_contents=true, true);
}
//================================================
Cartouche.prototype.createPendingPage = function(page_num,open_pending){

	$("#pendingPanel .update_archive").hide();
	$("#open_pending").hide();
	$("#open_archive_indicator").show();
	$("#pendingPanel tr.report").remove();
	//$("#pendingPanel .pager").hide();
	//$("#pendingPanel .pager").show();
	$("#pendingPanel .pager").empty();
	$("#pendingPanel .update_pending").show();

	//assumes user is logged in
	var params = {"getPendingDelete":page_num};
	
	var tc = this;
	$.getJSON(url="/KART/pending",data=params,function(json){
	
		$("#open_archive_indicator").hide();
		$("#open_pendingPanel").show();
		
		var dateMap = {
			0:"Jan",
			1:"Feb",
			2:"Mar",
			3:"Apr",
			4:"May",
			5:"Jun",
			6:"Jul",
			7:"Aug",
			8:"Sep",
			9:"Oct",
			10:"Nov",
			11:"Dec"
		};
		$.each(json.page,function(){
			
			var report = $("<tr class='report'></tr>");
			report.html($("#pending_report_mold").html());
			$(report).insertBefore("#pendingPanel table #pending_report_mold");
			$(".userName",report).text(this.userName);
			$(".fileNameLink",report).text("select");
			$(".markPending",report).attr("segId",this.segmentId);
			
			var pending=this;
			$(".fileName",report).click(function () { 
					$(".fileNameLink").css("color","#4169E1");
					$(".fileNameLink",report).css("color","black");
					$(".fileNameLink",report).css("font-weight","bold");
					tc.segmentSelect("/KART/pending",{"getSegment":pending.segmentId},center_on=true);
			});
			
			var ul_date = new Date(this.ts);
			$(".uploadDate",report).text(ul_date.toString().replace(/^\w{3}\b/,"").replace(/\b\d\d\:.*$/,""));
			$(".discardPending",report).click(function (){
				var params = {"discardPending": pending.segmentId};

				$.getJSON(url="/KART/pending",data=params,function(json){
				     if(!json.success)
					  tc.displayEditPanelMessage(json.reason,is_error=true);
				     else
					 tc.createPendingPage(1,false);

				
				});
			
			});
			$(".approvePending",report).click(function (){
				tc.updateAction(url="/KART/delete_segments",{ids:pending.segmentId},"roads","Road deleted",function(){
					 tc.createPendingPage(1,false);
				});
			});
		
		});
				
		$('#pendingPanel .report:even').css("background-color","#ccc");
		$('#pendingPanel .pager').aqPaging({ current: json.pageIndex, pages: json.numPages, css:false,cb: function(page) {tc.createPendingPage(page) } });
		$("#pendingPanel .pager").show();
		$("#pendingPanel .contents").show();
		
		$("#open_pending").show();
		$("#pendingPanel .update_pending").show();
		if(open_pending)
			$("#pendingPanel").fadeIn();
		
	});
}
//=======================================================================
Cartouche.prototype.openArchive= function(){
	var tc = this;
	
	if($("#archivePanel .archive_staff_only:visible").length > 0 )
	    tc.createArchivePage(1,true);
	else {
	    Login.isLoggedIn(function(is_logged_in, message, user_id, _logged_in_user_data){
		    logged_in_user_data = _logged_in_user_data;
		    logged_in_user_id = (user_id ? user_id : '');
		    
		    
		    tc.createArchivePage(1,true);
		    
		    if (is_logged_in && _logged_in_user_data.staff && _logged_in_user_data.staff == 't'){
			$("#archivePanel .archive_staff_only").show();
			$("#fleet").show();
		    }
		    
		});
	}
	
}
//================================================
Cartouche.prototype.approveAllPendingMarked = function()
{
	var segIds="";
	$.each($(".markPending:checked"),function(){
		segIds+=this.attributes["segId"].nodeValue+",";
	});
	
	
				var params = {};
				params["id"] = segIds;
				params["type"] = "roads";
				
				var url ="/map_edit/delete.php";
				
				var resultCallback = function(response){
				   
				     var json = eval("("+response+")");
				     if(json.reply && json.reply.error){
					 tc.revertEditPanelContents();
					 tc.displayEditPanelMessage(json.reply.message,is_error=true);
				     }
				     else{
					 if(!json.successful && json.reason){
					     tc.revertEditPanelContents();
					     tc.displayEditPanelMessage(json.reason,is_error=true);
					 }
					 else{
			
						var msg = json.reply ? json.reply.message : json.reason;
						tc.displayEditPanelMessage(msg,is_error=false);
						tc.redrawFeatureType("roads");
						tc.redrawFeatureType("landmarks");
						tc.redrawFeatureType("restrictions");
						tc.deselectAll();
						tc.createPendingPage(1,false);
					   
					 }
				     }
				}
}
//================================================
Cartouche.prototype.discardAllPendingMarked = function(){

	var segIds="";
	$.each($(".markPending:checked"),function(){
		segIds+=this.attributes["segId"].nodeValue+",";
	});
	var params = {"discardPending": segIds};

	$.getJSON(url="/KART/pending",data=params,function(json){
	     if(!json.success)
		  tc.displayEditPanelMessage(json.reason,is_error=true);
		  
		tc.createPendingPage(1,false);
	});
}
//================================================
Cartouche.prototype.openPending= function(){

	var tc = this;
	
	if($("#pendingPanel .archive_staff_only:visible").length > 0 )
		tc.createArchivePage(1,true);
	else
		Login.isLoggedIn(function(is_logged_in,msg,user_id,reply){
			
			tc.createPendingPage(1,true);

			if(reply.staff=="t")
				$("#pendingPanel .archive_staff_only").show();
			
			
		});
	
}
//================================================
g_init_on_login=true;
g_cartouche = null;
/*$().ready(function(){
		 
	setActiveTab("livemap");
	g_cartouche = new Cartouche(g_init_on_login);
		
    });*/
var initPage = function(){
		country = readCountryCookie();
	if (!(country == 'US' || country =='03' || country == 'LR' || country == 'GB')){
		$(".measurement_system").text("metric");
		$(".metric").show();
		$(".imperial").hide();
	} 
	else{
			$(".measurement_system").text("imperial");
		$(".metric").hide();
		$(".imperial").show();
	}
	setActiveTab("livemap");
	g_cartouche = new Cartouche(g_init_on_login);
     //setTimeout('$("#cartouche_OpenLayers_ViewPort").css("display","none");',1000);
		
    }
//================================================
Cartouche.prototype.initGPSPointsView = function(){
    this.refreshGPSPointsView();
};
//================================================
Cartouche.prototype.refreshGPSPointsView = function(){
    if (false) {
	//    } else if (document.gps_points_form.gps_points_colors.value == 5 || document.gps_points_form.gps_points_colors.value == 6 || document.gps_points_form.gps_points_colors.value == 7) {
	//    $("#filter_low_weight").show();
    } else if (document.gps_points_form.gps_points_colors.value == 4) {
	document.gps_points_form.marked_session_id.disabled = false;
	if($("#viewPanel #refresh_gps_points").hasClass("disabled")) 
		$("#viewPanel #refresh_gps_points").removeClass("disabled");
    } else {
	document.gps_points_form.marked_session_id.disabled = true;
	$("#viewPanel #refresh_gps_points").addClass("disabled");
	//    $("#filter_low_weight").hide();
    }
    if (logged_in_user_id > 0) {
	$("#user_tracks").show();
    } else {
	document.map_problems_filter_form.filter_managed_area.checked = false;
	$("#user_tracks").hide();
    };
    //    this.initGPSPointsView();

    Layers.gpsPointsLayer.mergeNewParams({ 
	    _gps_points_arrows:document.gps_points_form.gps_points_arrows.checked,
		_gps_points_colors:document.gps_points_form.gps_points_colors.value,
		_mark_session_id:document.gps_points_form.marked_session_id.value,
		_gps_points_filter_user_tracks:document.gps_points_form.filter_user_tracks.checked,
		_gps_points_filter_low_weight:document.gps_points_form.filter_low_weight.checked,
		_gps_points_user_id:logged_in_user_id
		});
		
   this.writeCookie();
};
//================================================
Cartouche.prototype.markGPSPointSession = function(sessionId) {
    document.gps_points_form.marked_session_id.value =  sessionId;
    document.gps_points_form.gps_points_colors.value = 4;
    this.refreshGPSPointsView();
};
//================================================
Cartouche.prototype.markSelectedGPSPointSession = function() {
    this.markGPSPointSession(currently_marked_gps_point['session_id']);
};




Cartouche.prototype.initMapProblemsView = function(){
    //    if (is_user_area_manager) {
    if (logged_in_user_data && logged_in_user_data.area_manager && logged_in_user_data.area_manager == 't') {
	$("#manager_managed_area").show();
    } else {
	document.map_problems_filter_form.filter_managed_area.checked = false;
	$("#manager_managed_area").hide();
    }
    if (logged_in_user_id > 0) {
	$("#next_to_user_segments").show();
    } else {
	document.map_problems_filter_form.filter_next_to_user_segments.checked = false;
	$("#next_to_user_segments").hide();
    }
    if (logged_in_user_data && logged_in_user_data.staff && logged_in_user_data.staff == 't') {
	$("#map_problems_legend .staff").show();
    } else {
	$("#map_problems_legend .staff").hide();
    }

};
//================================================
Cartouche.prototype.refreshMapProblemsView = function(){
    this.initMapProblemsView();
    document.map_problems_legend_form.map_problems_show_low_priority.checked = document.map_problems_legend_form.map_problems_show_low_priority.checked  || document.map_problems_legend_form.map_problems_show_resolved.checked;
    Layers.mapProblemsLayer.mergeNewParams({ 
	    _map_problems_colors:document.map_problems_legend_form.map_problems_colors.value,
		_map_problems_type_filter:document.map_problems_legend_form.problem_type_filter.value,
		_map_problems_city_name:document.map_problems_filter_form.city_name.value,
		_map_problems_street_name:document.map_problems_filter_form.street_name.value,
		_map_problems_filter_managed_area:document.map_problems_filter_form.filter_managed_area.checked,
		_map_problems_filter_next_to_user_segments:document.map_problems_filter_form.filter_next_to_user_segments.checked,
		_map_problems_filter_by_days:document.map_problems_filter_form.map_problems_filter_by_days.value,
		_map_problems_show_resolved:document.map_problems_legend_form.map_problems_show_resolved.checked,
		_map_problems_show_low_priority:document.map_problems_legend_form.map_problems_show_low_priority.checked ,
		_map_problems_user_id:logged_in_user_id
		});
		
   this.writeCookie();
};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.addLandmark = function(){
this.deselectAll();
   this.setEditMode("");
    $("#cartouche").css("cursor","crosshair");
    Layers.landmarksLayer.setVisibility(true);
    $("#landmarks").addClass("selectedLayer");
    $("#landmarks_view").show();
    $("#editPanel .contents a").removeClass("selected");
    $("#editPanel .contents a#add_landmark").addClass("selected");
		
    this.drawLandmarkControl.activate();
};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.addLasso = function(){
this.deselectAll();
   this.setEditMode("");
    $("#cartouche").css("cursor","crosshair");
    $("#lasso_tools").show();
    $("#add_lasso").css("font-weight","bold");
    //Layers.lassoLayer.setVisibility(true);
   /* $("#landmarks").addClass("selectedLayer");
    $("#landmarks_view").show();
    $("#editPanel .contents a").removeClass("selected");
    $("#editPanel .contents a#add_landmark").addClass("selected");
	*/	
    this.drawLassoControl.activate();
};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.addLandmarkFreehand = function(){
    Layers.landmarksLayer.setVisibility(true);
    $("#landmarks").addClass("selectedLayer");
    $("#landmarks_view").show();
    $("#editPanel .contents a").removeClass("selected");
    $("#editPanel .contents a#add_landmark_freehand").addClass("selected");
		
    this.drawLandmarkFreehandControl.activate();
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.exitEditLandmarkGeometry =  function(){

    if(this.landmarkModifyControl.feature){
		
	this.landmarkModifyControl.layer.eraseFeatures(this.landmarkModifyControl.feature);
	this.landmarkModifyControl.feature.geometry = this.landmarkModifyControl.originalGeometry;
	this.landmarkModifyControl.layer.drawFeature(this.landmarkModifyControl.feature);
    }
		
    this.landmarkModifyControl.deactivate();
    this.updateToolsPanel();
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.editLandmarkDetails = function(){
	  
    var count = this._countFeatures();
    //    if(count.nodes !=0)
    //        throw "ERROR - edit landmark only roads are selected or no features at all"
		
    if(count.landmarks==0){
	this._setToolsPanelContents("edit_landmark_details_tools_no_landmarks");
	return;
    }

    this._setToolsPanelContents("edit_landmark_details_tools");

    //    if(count.landmarks > 1)
    //        $("#editPanel .selectedFeatures").append(" (" + count.landmarks+ " " + $("#landmark_noun .plural").text() +" )");
		
    var details =  this.factory.mergeDetails(this.selectedFeatures,"landmarks");
    this.updateEditPanelForm(details);
    var contentsQ =  $("#editPanel .contents");

    this.addAutoComplete("editPanel");


    //replace some text with correct values 
    //    $("#cross_time span",contentsQ).eq(0).text(time);
    $("#user span a",contentsQ).text(details["user_name"]);
    $("#update_user span a",contentsQ).prepend(details["update_user"]);
    $("#area_in_meters span a",contentsQ).prepend(details["area_in_meters"]);
    
  

};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.exitEditLandmarkDetails = function(){
    this.updateToolsPanel();
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.getOnLassoAdded = function()
{
	var tc = this;
   return function(){
	tc.drawLassoControl.deactivate();
	
	$("#add_lasso").css("font-weight","normal");
	$("#lasso_tools").hide();
	var str_rep = "";
	var geom=tc.newFeaturesLayer.features[0].geometry;
	if(tc.map.getProjection()=="EPSG:900913")
		geom.transform(this.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));	
	var points = geom.components[0].components;
	for(var i in points)
	    str_rep+=points[i].x+","+points[i].y+" ";
	    tc.deselectAll();
		
	//	if ($("#lasso_segments").is(':checked'))
			tc.segmentSelect("/KART/lasso",{"geom":str_rep,"seg":"Y"});
	//	if ($("#lasso_nodes").is(':checked'))
	//		tc.segmentSelect("/KART/lasso",{"geom":str_rep,"node":"Y"});
    }


};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.getOnLandmarkAdded = function(){
		
    var tc = this;
    return function(){
	tc.drawLandmarkControl.deactivate();
	tc.drawLandmarkFreehandControl.deactivate();
	tc._setToolsPanelContents("edit_landmark_details_tools");
	$("#edit_landmark_details").hide();
	$("#new_landmark_details").show();
	$("#editPanel .contents .stats").hide();

	tc.addAutoComplete("editPanel");

	$("#editPanel .contents form input[name=id]").val("-1");
		
	var str_rep = "";
	var points = tc.newFeaturesLayer.features[0].geometry.components[0].components;
	for(var i in points)
	    str_rep+=points[i].x+","+points[i].y+" ";
		
	$("#editPanel .contents #landmarkCoordinates textarea").val(str_rep);
	$("#editPanel .contents #landmarkCoordinates").show();
    }
};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.saveNewLandmark =function(){
		
	var geom = this.newFeaturesLayer.features[0].geometry.clone();
	if(this.map.getProjection()=="EPSG:900913")
		geom.transform(this.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));	
		
	var polyline = "";
	for(var i in geom.components[0].components){
		var p = geom.components[0].components[i];
		polyline+=p.x+","+p.y+" ";
	}
	
	var additionalParams = {"the_geom":polyline, success_message:$('#saveLandmarkTxt').html()};
	this.saveEditLandmarkDetails(additionalParams);

};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.saveEditLandmarkDetails = function(additionalParams){
    this.uploadEditPanelForm("/map_edit/update_landmark.php", $("#editPanel form input[name=update_property]").val(),deselect_on_success=true,additionalParams);    
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.editLandmarkGeometry = function(){

    this.landmarkModifyControl.activate();
    this._setToolsPanelContents('edit_landmark_geometry_tools');
    count = this._countFeatures();
    if(count.landmarks==1) {
	//	var obj = {};
	var feature = this.selectedFeatures[this.featureQueue[0]].vector;
	this.landmarkModifyControl.originalGeometry =feature.geometry.clone();
	this.landmarkModifyControl.selectFeature(feature);
    }
	   
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.saveEditLandmarkGeometry = function(){ 
	   
    var tc = this;
    this.requiresLogin(function(){

	    var type = "landmarks"; 
	    var params = "";
	    var details = tc.selectedFeatures[tc.featureQueue[0]].details;
	    var vector = tc.selectedFeatures[tc.featureQueue[0]].vector;
			  
	    for(var next in details)
		params+=next+"="+details[next]+"&";
			
	    //now append the geographic data
	    var geom =vector.geometry.clone();
		
	    if(tc.map.getProjection()=="EPSG:900913")
		geom.transform(tc.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));
		
	    var polyline = "";
	    for(var i in geom.components){
		var p = geom.components[i];
		polyline+=p.x+","+p.y+" ";
	    }
			 
	    params+= "the_geom="+encodeURI(polyline);
			
	    var url = "/map_edit/update_landmark.php";
			
	    $("#editPanel #applyFixIndicator").show();
	    $("#editPanel .contents").fadeTo(1, 0.3);
	    var saveResult = function(response){
		$("#editPanel .contents").fadeTo(0.3, 1);
		$("#editPanel #applyFixIndicator").hide();
		var json = eval("("+response+")");
		if(json.reply.error)
		    tc.displayEditPanelMessage(json.reply.message,is_error=true);
		else{
		    tc.displayEditPanelMessage(json.reply.message,is_error=false);
		    tc.landmarkModifyControl.deactivate();
		    tc.redrawFeatureType(type);
		    tc.deselectAll();
		}
	    }

	    $.post( url, params,saveResult ) ;
	},revert_to_previous_contents=true);
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.deleteLandmark = function(){

    var tc = this;
    var del_id = tc.featureQueue[0].replace("landmarks.","");
    this.roadManipulation("/map_edit/delete_landmark.php",function(){
		
	    //add undo delete option 
	    if (false) $("#editPanel .contents #undo_delete").show().css("fontWeight","bold").click(function(){
		
		    tc.requiresLogin(function(){

			    var params = {id:del_id};
			    var url ="/map_edit/undo.php";
			
			    $("#editPanel #applyFixIndicator").show();
			    $("#editPanel .contents").fadeTo(1, 0.3);
			    var resultCallback = function(response){
				$("#editPanel .contents").fadeTo(0.3, 1);
				$("#editPanel #applyFixIndicator").hide();
				var json = eval("("+response+")");
				if(json.reply.error)
				    tc.displayEditPanelMessage(json.reply.message,is_error=true);
				else{
				    $("#editPanel .contents #undo_delete").remove();
				    tc.displayEditPanelMessage(json.reply.message,is_error=false);
				    tc.redrawFeatureType("roads");
				    tc.redrawFeatureType("restrictions");
				}
			    }
			
			    $.post( url, params,resultCallback ) ;
			
			});
			
		    return false;

		});
	}, null, null, true);
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.onAddLandmarkPoint = function(e){
		 
    this.landmarkModifyControl.deactivate();
    var lonlat = this.map.getLonLatFromViewPortPx(e.xy);
    //          var url='/wms/israel_wfs2';
    var url=this.wfs_server;
    var url='/wms/israel_wfs_boom'; // ????
    var bounds, minXY, maxXY;
    var tolerance = 1;

    minXY = this.map.getLonLatFromPixel(
					new OpenLayers.Pixel(e.xy.x-tolerance, e.xy.y+tolerance));
    maxXY = this.map.getLonLatFromPixel(
					new OpenLayers.Pixel(e.xy.x+tolerance, e.xy.y-tolerance));

    bounds = new OpenLayers.Bounds(minXY.lon, minXY.lat, maxXY.lon, maxXY.lat);
    
    
    if(this.map.getProjection()=="EPSG:900913")
		bounds.transform(this.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));

    // now create request url for features
		  
    //var bounds = OpenLayers.Bounds.fromSize(new OpenLayers.Size(5,5));
		
    //bounds = bounds.scale(ratio=1,origin=lonlat);
  
    var params ={
	SERVICE: "WFS",
	VERSION: "1.0.0",
	REQUEST: "GetFeature",
	TYPENAME:"landmarks",
	MAXFEATURES: 2,
	BBOX: bounds.toBBOX(),
	WIDTH: Layers.gpsPointsLayer.tileSize.w,
	_LANDMARKS_ADD_BUFFER:1
    }
		  
    var qindQ =  $(".queryIndicator");
    qindQ.css("left", (e.xy.x - 5) + 'px');
    qindQ.css("top", (e.xy.y - 5) + 'px');
    qindQ.show();

		
    var newPointVector = new OpenLayers.Feature.Vector();
    newPointVector.style = {strokeWidth:3,strokeColor: "orange",strokeOpacity:1,pointRadius: 5,fillColor:"blue",fillOpacity:1};
		
    this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
    this.newFeaturesLayer.addFeatures(newPointVector);
		
    var tc = this;
		
    tc.aux_add_landmark_point = "";
    $("#editPanel #applyFixIndicator").show();
    $("#editPanel .contents").fadeTo(1, 0.3);
    $.get( url,params,function(feed){
	    $("#editPanel .contents").fadeTo(0.3, 1);
	    $("#editPanel #applyFixIndicator").hide();
			  
	    $(".queryIndicator").hide();
	    //no feature found ...
	    if($(":ns(http://www.opengis.net/gml,null)",feed).length>0)
		return;
				
	    var contains_selected_point = false;
	    $(":ns(http://www.ttt.org/myns,landmarks)",feed).each(function(){
		
		    var feature_id = $(this).attr('fid');
		    if(feature_id!=tc.featureQueue[0])
			tc.aux_landmark_point = feature_id;
		    else
			contains_selected_point = true;
			
		});
		
	    if(!contains_selected_point)
		return;

	    $("#editPanel #save_add_landmark_point:hidden").show();
	    tc.featuresLayer.removeFeatures(newPointVector);
	    newPointVector.geometry = new OpenLayers.Geometry.Point(x=lonlat.lon,y=lonlat.lat);
	    tc.featuresLayer.addFeatures(newPointVector);
		
	}, "xml" ) ;
		  
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.addLandmarkPoint = function(){
		
    this._setToolsPanelContents("landmark_point_tools");
    $("#editPanel #save_landmark_point").hide();
    this.map.events.unregister("click", this, this.onclick);
    this.map.events.register("click", this, this.onAddLandmarkPoint);
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.AAAsaveAddLandmarkPoint = function(){
		
		
    var tc = this;
		
    var params = {separator:"false",locked:"false"};//init checkbox fields with false since otherwise they will not be sent when their value is false
    $.each($("#editPanel form").serializeArray(),function(){

	    if(this.name == "update_property")
		params["update_type"]=this.value;
	    else
		params[this.name]=this.value;
	});
		
	  
    //add additional params if any ...
    if(additionalParams)
	for(var key in additionalParams)
	    params[key] = additionalParams[key];
		
		
    this.requiresLogin(function(){

	    var type = feature_type_affected;
	    var url =upload_url;
			
	    var saveResult = function(response){
		
		var json = eval("("+response+")");
		if(json.reply.error)
		    tc.displayEditPanelMessage(json.reply.message,is_error=true);
		else{
			
		    tc.exitAddLandmarkPoint();
		    tc.redrawFeatureType(type);
		    if(deselect_on_success)
			tc.deselectAll();    
				
		    tc.displayEditPanelMessage(json.reply.message,is_error=false);
		}
	    }

	    $.get( url, params,saveResult );
	},revert_to_previous_contents=deselect_on_success);

}
    Cartouche.prototype.OLDsaveAddLandmarkPoint = function(){
	var tc = this;
	this.requiresLogin(function(){

		var params = {};
		var point = tc.newFeaturesLayer.features[0].geometry;
		  
		if(tc.aux_add_landmark_point.length>0)
		    params["id"] = tc.featureQueue[0].replace("landmark_point.","")+","+tc.aux_add_landmark_point.replace("landmark_point.","");
		else
		    params["id"] = tc.featureQueue[0].replace("landmarks_point.","");

		//          if(tc.aux_add_landmark.length>0)
		//            params["landmark_id"] = tc.featureQueue[0].replace("landmarks.","")+","+tc.aux_add_landmark.replace("landmarks.","");
		//          else
		//            params["landmark_id"] = tc.featureQueue[0].replace("landmarks.","");
		
		params["longitude"] = point.x;
		params["latitude"] = point.y; 
			  

		//          params["type"] = "add_point";

		var url = "/map_edit/update_landmark.php";
			
		var resultCallback = function(response){
		    var json = eval("("+response+")");
		    if(json.reply.error)
			tc.displayEditPanelMessage(json.reply.message,is_error=true);
		    else{
			tc.exitAddLandmarkPoint();
			tc.redrawFeatureType("landmarks");
			tc.deselectAll();
		    }
		}

		$.get( url, params,resultCallback ) ;
	    },revert_to_previous_contents=true);
    };
//--------------------------------------------------------------------------------------------------------------------

Cartouche.prototype.exitEditLandmarkPointDetails = function(handleRegistration){
		
    if (handleRegistration) {
	this.map.events.unregister("click", this, this.onAddLandmarkPoint);
	this.map.events.register("click", this, this.onclick);
    }
    this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
    this.updateToolsPanel();
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.exitAddLandmarkPoint = function(){
		
    this.map.events.unregister("click", this, this.onAddLandmarkPoint);
    this.map.events.register("click", this, this.onclick);
    this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
    this.updateToolsPanel();
};
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.editLandmarkPointDetails = function(){
	  
    var tc = this;
    var count = this._countFeatures();
    var details = {};

    if(count.landmark_points==0){

	$("#edit_landmark_point_details").hide();
	$("#new_landmark_point_details").show();
	$("#editPanel .contents .stats").hide();

	this._setToolsPanelContents("edit_landmark_point_details_tools");

	tc.addAutoComplete("editPanel");

	$("#editPanel .contents form input[name=id]").val("-1"); // need to reset since the currently selected featureis the landmark
	$("#editPanel .contents form input[name=name]").val("");
	$("#editPanel .contents form input[name=type]").val("1");
		
	for(var id in this.selectedFeatures){
	    $("#editPanel .contents form input[name=landmark_id]").val(this.selectedFeatures[id].details.id);
			
	}

		

    } else {
	$("#edit_landmark_point_details").show();
	$("#new_landmark_point_details").hide();
	$("#editPanel .contents .stats").show();
	this._setToolsPanelContents("edit_landmark_point_details_tools");
	details =  this.factory.mergeDetails(this.selectedFeatures,"landmark_points");
    };
    //    if(count.landmarks > 1)
    //        $("#editPanel .selectedFeatures").append(" (" + count.landmarks+ " " + $("#landmark_noun .plural").text() +" )");
		
    this.updateEditPanelForm(details);
    var contentsQ =  $("#editPanel .contents");

    this.addAutoComplete("editPanel");


    //replace some text with correct values 
    //    $("#cross_time span",contentsQ).eq(0).text(time);
    $("#user span a",contentsQ).text(details["user_name"]);
    $("#update_user span a",contentsQ).prepend(details["update_user"]);

};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.saveNewLandmarkPoint =function(){
		
		
    var geom = this.newFeaturesLayer.features[0].geometry.clone();
		
     if(this.map.getProjection()=="EPSG:900913")
		geom.transform(this.map.getProjectionObject(),new OpenLayers.Projection("EPSG:4326"));
		
    var point = geom.x + "," + geom.y;
    var additionalParams = {"the_geom":point};
    this.saveEditLandmarkPointDetails(additionalParams, true);

};
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.saveEditLandmarkPointDetails = function(additionalParams, shouldExitEditPointDetails){
  	
    var tc = this;
    var upload_url = "/map_edit/update_landmark.php";
		
    var params = {separator:"false",locked:"false"};//init checkbox fields with false since otherwise they will not be sent when their value is false
    $.each($("#editPanel form").serializeArray(),function(){

	    if(this.name == "update_property")
		params["update_type"]=this.value;
	    else
		params[this.name]=this.value;
	});
		
	  
    //add additional params if any ...
    if(additionalParams)
	for(var key in additionalParams)
	    params[key] = additionalParams[key];
		
		
    this.requiresLogin(function(){

	    //        var type = feature_type_affected;
	    var url =upload_url;
			
	    $("#editPanel #applyFixIndicator").show();
	    $("#editPanel .contents").fadeTo(1, 0.3);
	    var saveResult = function(response){
		$("#editPanel .contents").fadeTo(0.3, 1);
		$("#editPanel #applyFixIndicator").hide();
		
		var json = eval("("+response+")");
		if(json.reply.error)
		    tc.displayEditPanelMessage(json.reply.message,is_error=true);
		else{
			
		    //                if (shouldExitEditPointDetails)
		    tc.exitEditLandmarkPointDetails(shouldExitEditPointDetails);
		    tc.redrawFeatureType("landmarks");
		    tc.deselectAll();    
			
		    tc.displayEditPanelMessage(json.reply.message,is_error=false);
		}
	    }

	    $.get( url, params,saveResult );
	},revert_to_previous_contents=true);
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.deleteLandmarkPoint = function(){

    var tc = this;
    var del_id = tc.featureQueue[0].replace("landmark_points.","");
    this.roadManipulation("/map_edit/delete_landmark.php",function(){
		
	    //add undo delete option 
	    if (false) $("#editPanel .contents #undo_delete").show().css("fontWeight","bold").click(function(){
		
		    tc.requiresLogin(function(){

			    var params = {id:del_id};
			    var url ="/map_edit/undo.php";
			
			    $("#editPanel #applyFixIndicator").show();
			    $("#editPanel .contents").fadeTo(1, 0.3);
			    var resultCallback = function(response){
				$("#editPanel .contents").fadeTo(0.3, 1);
				$("#editPanel #applyFixIndicator").hide();
				var json = eval("("+response+")");
				if(json.reply.error)
				    tc.displayEditPanelMessage(json.reply.message,is_error=true);
				else{
				    $("#editPanel .contents #undo_delete").remove();
				    tc.displayEditPanelMessage(json.reply.message,is_error=false);
				    tc.redrawFeatureType("roads");
				    tc.redrawFeatureType("restrictions");
				}
			    }
			
			    $.post( url, params,resultCallback ) ;
			
			});
			
		    return false;

		});
	});
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.bezierizeRoad = function(){
    tc = this;
    var vector = tc.selectedFeatures[tc.featureQueue[0]].vector;
		
		
    //now append the geographic data
    var geom =vector.geometry;
		
    //    var polyline = "";
    //    for(var i in geom.components){
    //    var p = geom.components[i];
    //    polyline+=p.x+","+p.y+" ";
    //    };
    //    CurveHelper.make([{x:1, y:1}, {x:2, y:2}, {x:3, y:2}, {x:4, y:1}]);
    CurveHelper.make(geom.components);
    var coordinates = CurveHelper.getSplinePoints();
    var pline = new OpenLayers.Geometry.LineString();
    for(var i in coordinates){
	var point = coordinates[i];
	pline.addPoint(new OpenLayers.Geometry.Point(x=point.x,y=point.y));
    }
    polyline_vector = new OpenLayers.Feature.Vector(geometry=pline);
    tc.featuresLayer.addFeatures(polyline_vector);
    this.selectedFeatures[this.featureQueue[0]].vector = polyline_vector;
    var g = 1;
};

Cartouche.prototype.compileClientMap = function(){
    var bounds = this.map.getExtent();
    this.roadManipulation("/map_edit/compile_client_map.php", null, {left: bounds.left, top:bounds.top, right:bounds.right, bottom:bounds.bottom}, true);
};


//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.changeLayerOpacity = function(layerName, byOpacity) {
  
    var opacity = $(".layersContainer .layer#" + layerName + " input").get(0).value;
   
    var newOpacity = (parseFloat(opacity) + byOpacity).toFixed(1);
    newOpacity = Math.min(1,
			  Math.max(0.2, newOpacity));
    $(".layersContainer .layer#" + layerName + " input").get(0).value = newOpacity;
    
    this.map.getLayersByName($(".layersContainer #" + layerName).text())[0].setOpacity(newOpacity);
}

//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.fullScreenMapMode = function() {
    var tc = this;
    var w = window.innerWidth;
    var h = window.innerHeight;
    var width = w - 40;
    var height = h - 240;
    if (width > 1300) width = 1300;
    $("#content_wrapper").width(width);
    $("#cartouche").height(height);
    tc.map.updateSize();
    isInFullScreenMode = 1;
    this.getOnViewChanged()();
}
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.normalScreenMapMode = function() {
    var tc = this;
    $("#content_wrapper").width(defaultContentWrapperWidth);
    $("#cartouche").height(defaultCartoucheHeight);
    tc.map.updateSize();
    isInFullScreenMode = 0;
    this.getOnViewChanged()();
};


//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.initHotKeys = function() {
    HotKeys.add('g', function() {g_cartouche.G_hotKey();}, {disable_in_input:true});
    HotKeys.add('e', function() {g_cartouche.E_hotKey();}, {disable_in_input:true});
    HotKeys.add('c', function() {g_cartouche.C_hotKey();}, {disable_in_input:true});
    HotKeys.add('s', function() {g_cartouche.S_hotKey();}, {disable_in_input:true});
    HotKeys.add('l', function() {g_cartouche.L_hotKey();}, {disable_in_input:true});
    HotKeys.add('delete', function() {g_cartouche.Delete_hotKey();}, {disable_in_input:true});
    HotKeys.add('insert', function() {g_cartouche.Insert_hotKey();}, {disable_in_input:true});
    HotKeys.add('esc', function() {g_cartouche.Esc_hotKey();}, {disable_in_input:true});
};

//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.preHotKey = function() {
    this.modifyControl.deactivate();
    this.moveModifyControl.deactivate();
    this.landmarkModifyControl.deactivate();
};

//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.G_hotKey = function() {
    if (this.featureQueue.length == 1) {
	this.preHotKey();
	var id = this.featureQueue[0];
	var type = id.split(".")[0];
	if (type == 'roads') this.editRoadGeometry();
	if (type == 'landmarks') this.editLandmarkGeometry();
	if (type == 'nodes') this.moveNode();
    } else { /* error */ }
};


//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.E_hotKey = function() {
    if (this.featureQueue.length >= 1) {
	this.preHotKey();
	var id = this.featureQueue[0];
	var type = id.split(".")[0];
	if (type == 'roads') this.editRoadDetails();
	if (type == 'landmarks') this.editLandmarkDetails();
    } else { /* error */ }
};


//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.Delete_hotKey = function() {
    if (this.featureQueue.length >= 1) {
	this.preHotKey();
	var id = this.featureQueue[0];
	var type = id.split(".")[0];
	if (type == 'roads') this.deleteRoad();
	if (type == 'landmarks') this.deleteLandmark();
	if (type == 'landmark_points') this.deleteLandmarkPoint();
    }
};


Cartouche.prototype.Insert_hotKey = function() {
    if (this.featureQueue.length == 0) {
	this.addNewFeature();
	this.addRoad();
    }
};


//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.C_hotKey = function() {
    if (this.featureQueue.length == 2) {
	this.preHotKey();
	for(var i in this.featureQueue){
	    var id = this.featureQueue[i];
	    var type = id.split(".")[0];
	    if (type != 'roads') return;
	}
	this.connectRoads();
    } else { /* error */ }
};

//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.L_hotKey = function() {    
    alert("Position:\n" + g_cartouche.map.getLonLatFromPixel(g_cartouche.mousePositionControl.lastXy));
};


//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.Esc_hotKey = function() {
    //    this.modifyControl.deactivate();
    this.preHotKey();

    HotKeys.remove('y');
    HotKeys.remove('n');

    this.drawRoadFreehandControl.deactivate();
    this.drawRoadControl.deactivate();
    this.drawLandmarkFreehandControl.deactivate();
    this.drawLandmarkControl.deactivate();
    //    this.selectedFeatures = {};
    //    this.featureQueue = [];
    //    this.featuresLayer.removeFeatures(this.featuresLayer.features); //remove all features
    //    this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
    this.deselectAll();
    //this.modifyControl.deactivate();
    //    this.landmarkModifyControl.deactivate();
};



//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.getUrlParam = function (url, name) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( url );
    if( results == null )
	return "";
    else
	return results[1];
};


//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.getUrlParamNames = function (url) {
    var url = url;
    if (url.contains('?')) url = url.split('?')[1];
    var names = url.split('&');
    for (var i in names) {
	names[i] = names[i].replace(/=.*/,'');
    }
    return names;
};



//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.selectObjectsByUrl = function (url) {
    var tc = this;
    var names = this.getUrlParamNames(url);
    var cb = function(url, names) {
	if (names.length == 0) return;
	var name = names.shift();
	var type = name.split('-')[0];
	var id = tc.getUrlParam(url, name);
	if (id!=undefined && id.length > 1) {
	    var bounds = tc.map.getExtent();
	     if(!bounds)
			return;
	    bounds.left -= 0.1;
	    bounds.bottom -= 0.1;
	    bounds.top += 0.1;
	    bounds.right += 0.1;
	    var coords = bounds.toBBOX();
	    if (type == 'seg') tc.onclick(null, id, coords, null, null, function(feed) {tc.getOnclickCallback(true)(feed); cb(url, names);}, true)
		else if (type == 'map_problem') tc.onclick(null, null, coords, id, null, function(feed) {tc.getOnclickCallback(true)(feed); cb(url, names);}, true)
		    else if (type == 'node') tc.onclick(null, null, coords, null, null, function(feed) {tc.getOnclickCallback(true)(feed); cb(url, names);}, true, id)
				else if (type == 'update_request') tc.onclick(null, null, coords, null, null, function(feed) {tc.getOnclickCallback(true)(feed); cb(url, names);}, true, null,null,id)
					else if (type == 'gps_point') tc.onclick(null, null, coords, null, null, function(feed) {tc.getOnclickCallback(true)(feed); cb(url, names);}, true, null, id)
						else if (type == 'seg_coords') {
							var x = id.split(',')[0];
							var y = id.split(',')[1];
							tc.onclick(null, 'ANY', new OpenLayers.Bounds((x*1) - 0.000001, (y*1) - 0.000001, (x*1) + 0.000001, (y*1) + 0.000001).toBBOX(), null, null, function(feed) {tc.getOnclickCallback(true)(feed); cb(url, names);}, true);
						}
						else cb(url, names);
	} else cb(url, names);
    };

    cb(url, names);
};
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.useUrlBBox = function (url) {
    var tc = this;

    var bbox = tc.getUrlParam(url, 'BBOX');
    if (bbox && bbox.length > 1) {
	var bounds = OpenLayers.Bounds.fromString(bbox);
	var lonlat = bounds.getCenterLonLat();
	var zoom = Math.min(tc.map.getZoomForExtent(bounds),tc.MAX_AERIAL_PHOTO_ZOOM);
	tc.map.setCenter(lonlat,zoom);
    }
};


//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.useUrlArchiveData = function (url) {
    var tc = this;

    var session_id = tc.getUrlParam(url, 'archive_session_id');
    var user_id = tc.getUrlParam(url, 'archive_user_id');
    
    if (session_id && session_id.length > 1) {
	if (user_id && user_id.length > 1) {
	    $('.archive_user_ids').val(user_id);
	}
	tc.openArchive(); 
	tc.gmlReports.showReport(session_id, '', tc.map.getExtent()); 
	g_cartouche.gmlReports.selector.activate();
    }

}


//-------------------------------------------------------------------------------------------------------------------	
Cartouche.prototype.routingIconClicked = function(which){
    $(".routing_icon").each(function() {
	    this.style.border="none";
	    this.style.padding="2px";
	});
    if (which == routingClickStatus) {
	routingClickStatus = 0;
    } else {
	routingClickStatus = which;
    }
    var element = null;
    if (routingClickStatus == 1) element = "#routing_from_icon";
    if (routingClickStatus == 2) element = "#routing_to_icon";
    if (element != null) {
	$(element).get(0).style.border="2px solid black";
	$(element).get(0).style.padding="0px";
    }
};


//-------------------------------------------------------------------------------------------------------------------	
Cartouche.prototype.showRoute = function(){
    
    var tc = this;
    this.requiresLogin(function(){
	    
	    
	    
	    var id1 = tc.featureQueue[0];
	    var id2 = tc.featureQueue[1];
	    g_route_from.seg_id =  id1.replace("roads.","");
	    g_route_to.seg_id =  id2.replace("roads.","");
	    
	    g_route_from.st_id = tc.selectedFeatures[id1].details.street_id;
	    g_route_to.st_id = tc.selectedFeatures[id2].details.street_id;
	    
	    g_route_from.location = new OpenLayers.LonLat(lon=parseFloat(tc.selectedFeatures[id1].details.anchor_hint_x),lat=parseFloat(tc.selectedFeatures[id1].details.anchor_hint_y));
	    g_route_to.location = new OpenLayers.LonLat(lon=parseFloat(tc.selectedFeatures[id2].details.anchor_hint_x),lat=parseFloat(tc.selectedFeatures[id2].details.anchor_hint_y));
	    
	    g_route_from.is_from_click = true;
	    g_route_to.is_from_click = true;
	    
	    
	    var gd = $("#tab_route");
	    
	    $(".find_tab").removeClass("find_tab_selected");
	    $(gd).addClass("find_tab_selected");
	    
	    $(".query_form").hide();
	    var form_id = $(gd).attr("id").replace("tab","form")
		$("#"+form_id).show();
	    $("#"+form_id+" :input:first").focus();
	    
	    $("#form_route :input[name=from]").eq(0).val(tc.selectedFeatures[id1].details.street_name + ", " + tc.selectedFeatures[id1].details.city_name);
	    $("#form_route :input[name=to]").eq(0).val(tc.selectedFeatures[id2].details.street_name + ", " + tc.selectedFeatures[id2].details.city_name);
	    
	    $("#editPanel #applyFixIndicator").show();
	    $("#editPanel .contents").fadeTo(1, 0.3);
	    navigate(true, "/map_edit/routing_request.php", function() {
		    var list =  g_map.getLayersByName("routes");
		    nav_layer = list[0];
		    
		    g_map.markersLayer.clearMarkers();
		    nav_layer.removeFeatures(nav_layer.features);
		    g_cartouche.refreshFeaturesNumbering();
		}
		, function() {
		    $("#editPanel .contents").fadeTo(0.3, 1);
		    $("#editPanel #applyFixIndicator").hide();
		    g_cartouche.refreshFeaturesNumbering();
		}
		);
	},revert_to_previous_contents=true,indicate=true);
    
};
//----------------------------------------------------------------------------------------------------------------------------------------------------
/*
Cartouche.prototype.addCityStreet = function(params,add_city){ 

	var name = "";
	if(city)
		name=$("input[name=city_name]").val();
	else
		name=$("input[name=street_name]").val();
		
	
	var count = this._countFeatures();
	if(count.nodes !=0)
		throw "ERROR - add city only roads are selected"

	if(count.roads==0  && this.newFeaturesLayer.features.length == 0){
		this._setToolsPanelContents("edit_road_details_tools_no_roads");
		return;
	}

	this.new_segment_params = params;
	
	if(add_city){
		this._setToolsPanelContents("add_city_details_tools");
		$("input[name=city_name]").val(name);
	}
	else{
		this._setToolsPanelContents("add_street_details_tools");
		$("input[name=street_name]").val(name);
	}

}*/
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.saveNewCity = function(){ 

	var tc = this;
	var type = "roads"; 
	var vector = null;
	var params = null;
        var geom = null;
	    
	/*
	if(tc.featureQueue.length > 0){
	     
		if(tc.new_segment_params)
			params = tc.new_segment_params;
		else
			params = tc.selectedFeatures[tc.featureQueue[0]].details;
			
		vector = tc.selectedFeatures[tc.featureQueue[0]].vector;
	}
	else{
*/
	//this is a new road
	if(tc.featureQueue.length == 0){
		params = tc.new_segment_params;
		geom = vector = tc.newFeaturesLayer.features[0].geometry;
	}
	else
		if(tc.new_segment_params)
			params = tc.new_segment_params;
		else
			params = tc.selectedFeatures[tc.featureQueue[0]].details;

	      
	params["city_name"] = $("input[name=city_name]").val() ;
             
	var url = "/KART/add";

	this.editSegmentAction(url,params,geom,"City added",function(){
		$("#editPanel .save_link").hide();
		$("#editPanel .link_ajax_indicator").show();
		tc.saveNewStreet(true,geom);
	});

}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.saveNewStreet = function(is_from_save_new_city,the_geom){ 

	var tc = this;
	var type = "roads"; 
	var params = tc.new_segment_params;
	var geom = null;
	
	
	if(is_from_save_new_city)
		geom = the_geom;
	else{
		params["street_name"] = $("input[name=street_name]").val() ;
		if(tc.featureQueue.length == 0)//this is a new road
			geom = tc.newFeaturesLayer.features[0].geometry;
	}
              
	var url = "/KART/add";
		
	this.editSegmentAction(url,params,geom,is_from_save_new_city ? "City and street added" : "Street added",function(){
		$("#editPanel .save_link").hide();
		$("#editPanel .link_ajax_indicator").show();
		tc.editSegmentAction("/KART/update",params,geom,is_from_save_new_city ? "City and street added" : "Street added");
	});
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.moveRoadsGeometryMulti = function(){
    this.hideFeaturesNumbering();

    this.moveModifyControl.activate();
    this._setToolsPanelContents('move_roads_geometry_multi_tools', null, ' (' + this.selectedFeatures[this.featureQueue[0]].details.street_name + ')');
    count = this._countFeatures();
    if(count.roads!=0) {
	var megaGeometry = new OpenLayers.Geometry.Collection;
	var clonedMegaGeometry = new OpenLayers.Geometry.Collection;
	for(var i in this.featureQueue){
	    var feature = this.selectedFeatures[this.featureQueue[i]].vector;	    
	    this.selectedFeatures[this.featureQueue[i]].originalGeometry = feature.geometry.clone();
	    megaGeometry.addComponent(feature.geometry);
	    clonedMegaGeometry.addComponent(feature.geometry.clone());
	}
	var megaFeature = new OpenLayers.Feature.Vector(geometry=megaGeometry);
	
	
	megaFeature.style=this.selectedFeatures[this.featureQueue[0]].vector.style;
	
	this.moveModifyControl.originalGeometry = clonedMegaGeometry.clone();
	this.moveModifyControl.selectFeature(megaFeature);
    }
	   
}; 
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.exitMoveRoadsGeometryMulti =  function(){

    if(this.moveModifyControl.feature){
		
	this.moveModifyControl.layer.eraseFeatures(this.moveModifyControl.feature);
	this.moveModifyControl.feature.geometry = this.moveModifyControl.originalGeometry;
	//	this.moveModifyControl.layer.drawFeature(this.moveModifyControl.feature);
    }
    this.moveModifyControl.deactivate();
		
    this.featuresLayer.removeFeatures(this.featuresLayer.features); //remove all features
    this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
    for (var feature_id in this.selectedFeatures) {
	this.selectedFeatures[feature_id].vector.geometry = this.selectedFeatures[feature_id].originalGeometry;
	var features = this.selectedFeatures[feature_id]["vector"];
	this.featuresLayer.addFeatures(features);
    }


    this.doSelectionUpdates();
    this.updateToolsPanel();
};


//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.saveMoveRoadsGeometryMulti = function(){ 
    this.roadManipulation("/map_edit/update_multiple_roads_geometry.php", null, {}, null, null, false, null, null, true);
};

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.OLDsaveMoveRoadsGeometryMulti = function(){ 
	   
    var tc = this;
    this.requiresLogin(function(){

	    var type = "roads"; 
	    var params = "";
	    var details = tc.selectedFeatures[tc.featureQueue[0]].details;
	    var vector = tc.selectedFeatures[tc.featureQueue[0]].vector;
			  
	    for(var next in details)
		params+=next+"="+details[next]+"&";
			
	    //now append the geographic data
	    var geom =vector.geometry;
			 
	    var polyline = "";
	    for(var i in geom.components){
		var p = geom.components[i];
		polyline+=p.x+","+p.y+" ";
	    }
			 
	    params+= "the_geom="+encodeURI(polyline);
			
	    var url = "/KART/update";
			
	    $("#editPanel #applyFixIndicator").show();
	    $("#editPanel .contents").fadeTo(1, 0.3);
	    var saveResult = function(response){
		$("#editPanel .contents").fadeTo(0.3, 1);
		$("#editPanel #applyFixIndicator").hide();
		var json = eval("("+response+")");
		if(json.reply.error)
		    tc.displayEditPanelMessage(json.reply.message,is_error=true);
		else{
		    tc.displayEditPanelMessage(json.reply.message,is_error=false);
		    tc.moveModifyControl.deactivate();
		    tc.redrawFeatureType(type);
		    tc.deselectAll();
		}
	    }

	    $.post( url, params,saveResult ) ;
	},revert_to_previous_contents=true);
};
//----------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.initSimplifiedPanel = function(userName)
{
	if (!userName){
		$("#simplifiedPanel").hide();
		return;
	}
	
	$("#simplifiedPanel #name").html("Hello  "+ userName+" <div class='show'></div><div class='close'></div>");
	$(".sActiveContent").hover(function () {
									$(this).css({'background-color':'rgb(176,213,4)'});
									$(this).next().css({'left':this.parentNode.offsetLeft+272+"px",'top':this.parentNode.offsetTop+5+'px'});
									$(this).next().show();
									}
						 ,function () {
									$(this).css({'background-color':'white'});
									$(this).next().hide();
									});
};
 //----------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.skipURL =  function(){
	var dynamic_wms_layers = this.map.getLayersByClass("DynamicWMS");
	if(dynamic_wms_layers.length==0)
		return;

	dynamic_wms_layers[0].skipCurrentURL();
}
//----------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.addAlias = function(){
	
	var alias = $("<tr></tr>");
	$("#editPanel .street_name_row:last").after(alias);
	alias.html($("#alt_street_name_row_mold").html());
	alias.addClass("street_name_row");
	$("input",alias).attr("name","street_name_"+$("#editPanel .street_name_row").length);
	$("th",alias).css("width","57px");
	$(".removeAliasStreet",alias).click(function(){
				$(alias).remove();
				
			});
			$(".removeAliasStreet",alias).hover(function(){
			
				$(this).css("cursor","hand");
				
			},function(){
				$(this).css("cursor","pointer");
			});

/*
<tr class="street_name">
                                                    		<th>Street:</th>
												<td>  
													<input class="street_name" type="text" name="street_name" maxlength="100"></input>	
												</td>
                                                   </tr>
*/
}
//----------------------------------------------------------------------------------------------------------------------
var togglePanel = function(name){

	$("#"+name+"Panel").toggle();

}
