/**
	Class for editing maps
        @requires FeatureFactory
*/
function Cartouche(init_on_login){
	
	if(!init_on_login){
		this._init();
		return;
	}
	
	var tc = this;
	Login.isLoggedIn(function(is_logged_in){
	
		if(is_logged_in){
			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){
			
				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 = 10;
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._init = function(){

	this.map = new OpenLayers.Map.IsraelMap($('#cartouche').get(0));
	
	var layers = Layers.make();
	this.layers_loading = 0;
	var tc = this;
	for(var i in layers){
	
		this._addLoadingIndication(layers[i]);
		this.map.addLayer(layers[i]);	
	}
	
	this.aerialLayer = this.map.baseLayer;
		
        if(document.URL.indexOf("lat=") == -1 && document.URL.indexOf("lon=") == -1 && document.URL.indexOf("zoom=") == -1)
		$.getJSON(url="/geo_targeting",data={},callback=function(json){
		
			
			
			var lon = parseFloat(json.lon);
			var lat = parseFloat(json.lat);
			var lonlat = new OpenLayers.LonLat(lon=lon,lat=lat);
			if(tc.map.getMaxExtent().containsLonLat(lonlat))
				tc.map.setCenter(lonlat=lonlat,zoom=6);
			else
				if (!tc.map.getCenter()) 
					tc.map.zoomToMaxExtent();
					
			
		});		
		
        this.edit_panel_contents_stack = [];

        var queryInd = document.createElement("div");
        $(queryInd).addClass("queryIndicator");
        this.map.viewPortDiv.appendChild(queryInd);
	
        this.featureQueue = [];
        this.selectedFeatures = {};
	this.aux_split_road = "";						
	
	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.map.addLayer(this.newFeaturesLayer);
	
	this.markersLayer = new OpenLayers.Layer.Markers("locations");
        this.map.addLayer(this.markersLayer);
	
	
        this._initMapControls();
	$(".olControlPermalink a").text($("#name_permalink").text());
		
	var overview_layer = new OpenLayers.Layer.WMS( "Overview", 
			"http://www.freemap.co.il/wms/israel_edit2",
			{layers: 'roads', format: 'image/png'},{singleTile:true});
		
	var options = {
			layers: [overview_layer],
			minRatio: 4,
			maxRatio: 8,
			resolutionFactor:5,
			size: new OpenLayers.Size(130, 90)
	};
	var overview_control = new OpenLayers.Control.OverviewMap(options);
	this.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();
        
         if(this.map.zoom > this.MAX_AERIAL_PHOTO_ZOOM){//max zoom for the aerial map tiles
		$("#cartouche").css("backgroundImage","url(/cartouche/no-photo.png)");
		this.map.baseLayer.setVisibility(false);
		  
		//ie no loadend event for invisible base layer fix - will fool loading indication without thid
		if($.browser["msie"] && this.layers_loading > 0)
			this.layers_loading--;
          }
              
        this.map.events.register("click", this, this.onclick);
	
	
        this.map.events.register("moveend",this,function(e){
            
              if(this.map.zoom > 10){//max zoom for the aerial map tiles
                  $("#cartouche").css("backgroundImage","url(/cartouche/no-photo.png)");
                  this.map.baseLayer.setVisibility(false);
		  
		  //ie no loadend event for invisible base layer fix - will fool loading indication without this
		  if($.browser["msie"] && this.layers_loading > 0)
			this.layers_loading--;
              }
              else{
                   $("#cartouche").css("backgroundImage","");
			tc.map.baseLayer.setVisibility(true);
					
              }
	      
        });
	
	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") {
		this.markersLayer.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(params.lon,  params.lat)));
	}
}
//-------------------------------------------------------------------------------------------------------------------
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();
				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();
			}
		}
		
		layer.events.register("loadend",this,layerDone);
		layer.events.register("loadcancel",this,layerDone);
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._initPanels = function(){
    
        $(".panel").fadeTo(0, 0.85);
    
      //create the modal edit panel
        $(".panel").draggable({
          /*  handle:".frame",
            containment:"#cartouche",*/
             opacity:0.6
         });
         $("#editPanel .contents").html($('#initial_tools').html());
         
	 Login.isLoggedIn(function(is_logged_in,user_name){
	
			if(!is_logged_in)
				return;
				
			 $("#editPanel .out").hide();	
			 $("#editPanel .in a").text(user_name);
			 $("#editPanel .in").show();
			 $("#editPanel #login").hide();
			 $("#editPanel #logout").show();
	});
	 
         var thisCartouche = this;
         $("#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 =  thisCartouche.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();
			$(this).toggleClass("expand");    
		});
		
	 });
	 
	this.addAutoComplete("viewPanel");
        
	var tc = this;
	$("#viewPanel #findForm").keypress(function(e){
		if(e.which==13){//enter key
			  tc.find();
			  return false;
		}
        });
	
        this._initLayersPanel();
	
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._initLayersPanel = function(){
      
	var utility_layer_names = {locations:"true","add features":true,"edit features":true};
   
	var tc = this;
	$(".layersContainer .layer").each(function(){
		
		var layer = tc.map.getLayersByName($(this).text())[0];
		if(layer.getVisibility()){
		      $(this).addClass("selectedLayer");
		      if(this.id=="map_problems")
				$("#map_problems_legend").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=="map_problems"){
			
				Login.isLoggedIn(function(is_logged_in){
	
					if(is_logged_in)
						$(".layersContainer .layer#map_problems a").toggle();
				});
			
				$("#map_problems_legend").slideToggle("slow");
			}
			
			if(this.id=="shade" ){
			
				if($("#shade").hasClass("selectedLayer")){
					tc.map.setBaseLayer(tc.map.getLayersByName($(".layersContainer #shade").text())[0]);
					tc.map.removeLayer(tc.aerialLayer);
				}
				else{
					tc.map.addLayer(tc.aerialLayer);
					tc.map.setBaseLayer(tc.aerialLayer);
				}
			}
			
		    
		});
	
	});
	
	
	$(".layersContainer .layer#map_problems a").click(function(){
	
		tc.refreshMapProblems();
		return false;
	});
	
	Login.isLoggedIn(function(is_logged_in){
	
		if(is_logged_in &&  $("#map_problems").hasClass("selectedLayer"))
			$(".layersContainer .layer#map_problems a").toggle();
	});
	

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

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

		var url = "/map_edit/map_problems.php";
		
		var coords = tc.map.getExtent().toBBOX().split(",");
		extentStr = coords[0]+" "+coords[1]+","+coords[2]+" "+coords[3];
		var params = {"bbox":extentStr};
		var resultCallback = function(response){
		
			window.clearInterval(tc.refreshMapProblemsInterval);
			$(".layersContainer .layer#map_problems a").css("color","#a4cfff");
			$(".layersContainer .layer#map_problems a").show();
			var json = eval("("+response+")");
			var map_problems_layer = tc.map.getLayersByName($(".layersContainer #map_problems").text())[0];
			map_problems_layer.redraw(true);
		}
		
		tc.refreshMapProblemsInterval = window.setInterval ( function(){
				
			$(".layersContainer .layer#map_problems a").animate({ color: "#777777" }, 500);
			$(".layersContainer .layer#map_problems a").animate({ color: "#a4cfff"},500);
					
		}, 1000 );
		
		$.post( url, params,resultCallback );
		
	},revert_to_previous_contents=true,indicate=true);
	
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._initMapControls = function(){
       //modify control
     
	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.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.deactivate();
        
        //draw controls
        this.drawRoadControl = new OpenLayers.Control.DrawFeature(layer=this.newFeaturesLayer,handler=OpenLayers.Handler.Path,{featureAdded:this.getOnRoadAdded()});
	this.drawRoadControl.handler.style = {strokeWidth:5,strokeColor: "black",strokeOpacity:0.8,pointRadius: 3,fillColor:"white"};
	
	
	this.map.addControl(this.drawRoadControl);
	this.drawRoadControl.deactivate();
        
        //drag node control
        this.dragNodeControl = new OpenLayers.Control.DragFeature(this.featuresLayer,{geometryTypes:["OpenLayers.Geometry.Point"],doneDragging:this.onNodeMoved});
	this.map.addControl(this.dragNodeControl);
	this.dragNodeControl.deactivate();
     
        this.map.addControl(new OpenLayers.Control.Navigation());
	this.map.addControl(new OpenLayers.Control.PanZoomBar());
	 
        this.map.addControl(new OpenLayers.Control.ScaleLine());
	
        this.map.addControl(new OpenLayers.Control.MousePosition(
              {
                formatOutput:function(lonlat){
                            var digits = parseInt(this.numDigits);
                            return "lon: "+lonlat.lon.toFixed(digits)+" , lat:"+lonlat.lat.toFixed(digits);
                  }
              }
        ));
     
        //permalink
        var permalink = new OpenLayers.Control.Permalink();
        this.map.addControl(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);

}
//-------------------------------------------------------------------------------------------------------------------
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._setToolsPanelContents("edit_road_details_tools");
		$("#edit_road_details").hide();
		$("#editPanel form select[name=direction]").val(2);
		$("#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)
			str_rep+=points[i].x+","+points[i].y+" ";
		
		$("#editPanel .contents #roadCoordinates textarea").val(str_rep);
		$("#editPanel .contents #roadCoordinates").show();
      }
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.addAutoComplete= function(panel){
	$("#"+panel+" .contents input[name=city_name]").autocomplete("/libs/jcomplete.new.php",{extraParams:{name:"city_name"}});
	$("#"+panel+" .contents input[name=street_name]").autocomplete("/libs/jcomplete.new.php",
		{
			extraParams:{
				name:"street_name",
				city_name:function(){
					return $("#"+panel+" .contents input[name=city_name]").val();
				}
			},
			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;
	
        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.indexOf(type)>-1)
			layersWithType.push(next);
	}

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

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


      $("#editPanel .contents").hide();
       //revert to normal width
      $("#editPanel").width("220px");
      
      var q =  $("#editPanel .contents").html($('#'+contents_id).html());
      
      if(prepended_features_info)
            $(".selectedFeatures",q).prepend(prepended_features_info);
      
      if(displayFilters[contents_id])
          displayFilters[contents_id]();
      
      $("#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;

}
//-------------------------------------------------------------------------------------------------------------------
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;

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

      this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
         
      var count = this._countFeatures();
      
      if(count.roads==0 && count.nodes==0 && count.overall > 0){
          this.editFeature(count);
          return;
      }
      
      if(count.roads==0 && count.nodes==0)
         this._setToolsPanelContents("initial_tools");
          
      if(count.roads==1 && count.nodes==0){
            if(this.selectedFeatures[this.featureQueue[0]].details["direction"]=="1")
                this._setToolsPanelContents("one_two_way_road_tools");
            else
                this._setToolsPanelContents("one_road_tools");
      }
  
      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+" ");
         
      if(count.roads>2 && count.nodes==0)
         this._setToolsPanelContents("multi_roads_tools",count.roads+" ");
     
      if(count.roads==0 && count.nodes>1)
           this._setToolsPanelContents("multi_intersections_tools",count.nodes+" ");
	   
      if(count.roads>0 && count.nodes>0)
           this._setToolsPanelContents("mixed_selection_tools");
}
//-------------------------------------------------------------------------------------------------------------------
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(){

      this.modifyControl.activate();
      this._setToolsPanelContents('edit_road_geometry_tools');
      count = this._countFeatures();
      if(count.roads==1) {
		var obj = {};
		obj.feature = this.selectedFeatures[this.featureQueue[0]].vector;
		this.modifyControl.originalGeometry =obj.feature.geometry.clone();
		this.modifyControl.selectFeature(obj);
      }
   
}
//-------------------------------------------------------------------------------------------------------------------
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.updateToolsPanel();
}
//-------------------------------------------------------------------------------------------------------------------
/* 
        Deselect (or unselect) all selected map features
*/
Cartouche.prototype.deselectAll = function() {
        this.selectedFeatures = {};
        this.featureQueue = [];
        this.featuresLayer.removeFeatures(this.featuresLayer.features); //remove all features
        this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
          
        this.updateToolsPanel();
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype._isEditDetailsMode = function(){
      return  $("#editPanel .contents span").hasClass("editRoadDetailsMode");//ugly hack but this will work
}
//-------------------------------------------------------------------------------------------------------------------
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();
}

//-------------------------------------------------------------------------------------------------------------------
  /*
          Callback, used for ajax request for features where mapped was clicked by the user
  */
  Cartouche.prototype.getOnclickCallback = function(){
      
          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)
				return;
			    
			    tc.deselectFeature(tc.featureQueue[tc.featureQueue.length-1]);
				return;
			}

			var features = null
			
			$(":ns(http://www.opengis.net/gml,featureMember)",feed).each(function(){
				$(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);
						return;
					}
					 
					 var type = feature_id.split(".")[0];
					
					if(type!="roads" && type!="nodes"){
					 
						tc._deselectFeatureTypes([type]);
						tc._deselectOtherFeaturesTypes([type]);
						
					}
					else//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(feature){
					       tc.featuresLayer.addFeatures(feature.vector);
					       tc.selectedFeatures[feature_id] =feature;
					 }
					
					  tc.featureQueue.push(feature_id);

					  var count = tc._countFeatures();
					  if(tc._isEditDetailsMode() && count.roads == count.overall)
						  tc.editRoadDetails();
					  else
						   tc.updateToolsPanel();
						   
				});
			 
			});

          }
      
          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())
               if(this.layerNameToType(next.name))
                 str = this.layerNameToType(next.name) + ","+str;
       }
       
        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){

         this.modifyControl.deactivate();
          var lonlat = this.map.getLonLatFromViewPortPx(e.xy);
          var url='/wms/israel_wfs2';
          var bounds, minXY, maxXY;
          var tolerance = 7;

          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);

          // now create request url for features
          var params ={
                  SERVICE: "WFS",
                  VERSION: "1.0.0",
                  REQUEST: "GetFeature",
                  TYPENAME:this._getFeatureTypeString(),
                  MAXFEATURES: 1,
                  BBOX: bounds.toBBOX()
          }

          var qindQ =  $(".queryIndicator");
          qindQ.css("left", (e.xy.x - 5) + 'px');
          qindQ.css("top", (e.xy.y - 5) + 'px');
          qindQ.show();

          $.get( url,params,this.getOnclickCallback(), "xml" ) ;
  }
 //-------------------------------------------------------------------------------------------------------------------
 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.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";
	$("#road_speed span",contentsQ).eq(0).text(Math.round(parseInt(details["road_speed"])*3.6));
	$("#update_user span a",contentsQ).prepend(details["update_user"]);

 }
  //-------------------------------------------------------------------------------------------------------------------
 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(){
	$("#editPanel .contents a").removeClass("selected");
	$("#editPanel .contents a#add_road").addClass("selected");
    
	this.drawRoadControl.activate();
     
}
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.addIntersection = function(){
     $("#editPanel .contents a").removeClass("selected");
     $("#editPanel .contents a#add_node").addClass("selected");
     //this.drawNodeControl.activate();
}
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.exitAddFeature = function(){
  
     this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
     this.drawRoadControl.deactivate();
     //this.drawNodeControl.deactivate();
     this.updateToolsPanel();
}
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.logout = function(){
  
     var tc = this;
     var  onLogout = function(response){
         
         var json = eval("("+response+")");
         if(!json.reply.login){
		tc.updateToolsPanel();
	
		$(".user").show();
		$("#editPanel .in").hide();
		$("#editPanel .out").show();
		$("#editPanel #login").show();
		$("#editPanel #logout").hide();
           
      
		$(".layersContainer .layer#map_problems a").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";
	$("#editPanel .contents").prepend("<div class='"+class_name+"'>"+message+"</div>");
}
//------------------------------------------------------------------------------------------------------------------- 

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

	if(is_error){
		if($("#viewPanel form .error").length == 0)
			$("#viewPanel form").prepend("<div class='error'>"+message+"</div>");
		else
			$("#viewPanel form .error").text(message); 
	}
	else
		$("#viewPanel form .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.saveEditDetails = function(additionalParams){


	this.uploadEditPanelForm("/map_edit/update.php", $("#editPanel form input[name=update_property]").val(),deselect_on_success=true,additionalParams);
	
}
//-------------------------------------------------------------------------------------------------------------------  
Cartouche.prototype.saveNewRoundabout = function(){
   
    this.uploadEditPanelForm("/map_edit/create_rndabt.php","roads",deselect_on_success=true);
}
//-------------------------------------------------------------------------------------------------------------------
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];
	
		
	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.redrawFeatureType(type);
				if(deselect_on_success)
					tc.deselectAll();	
					
				tc.displayEditPanelMessage(json.reply.message,is_error=false);
			}
		}

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

//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.saveEditRoadGeometry = 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 = "/map_edit/update.php";
            
             var saveResult = function(response){
                 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.modifyControl.deactivate();
			tc.redrawFeatureType(type);
			tc.deselectAll();
                 }
             }

             $.post( url, params,saveResult ) ;
    },revert_to_previous_contents=true);
}
//------------------------------------------------------------------------------------------------------------------- 
Cartouche.prototype.saveUpdateRequest = function(){
    
	var tc = this;
	var params = $("#editPanel form").serialize();
	var type = $("#editPanel form input[name=update_property]").val(); 
	var url = "/map_edit/update_request.php";
	
	var map_url = $(".olControlPermalink a").get(0).href;
	params+="&url="+map_url;
	
	this.requiresLogin(function(){

		var saveResult = function(response){
		 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.redrawFeatureType(type);
		 }
		}

		$.post( url, params,saveResult );
	},revert_to_previous_contents=true);
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.deleteFeatures = function(){
    
	var tc = this;
	
	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.requiresConfirm(
		this.getRequiresLogin(function(){

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

			$.post( url, params,saveResult ) ;
		},revert_to_previous_contents=true)
	);
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.redrawFeatureType = function(type){
          
           var layers =this.typeToLayers(type);
	   for(var i in layers)
		layers[i].redraw(true);
         
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.requiresLogin = function(operation,revert_to_previous_contents,indicate){
    
    var tc = this;
    
    Login.isLoggedIn(function(logged_in){
        
	if(logged_in)
		operation();
	else{
		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.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){
    
     this.showConfirm(operation);
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.showConfirm = function(operation){
	
	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");
        
        var tc = this;
       
	$("#editPanel #yes").click(function(e){
		tc.revertEditPanelContents();
		operation();
		return false;
         });

}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.revertEditPanelContents = function(){
    
	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){
		if(result){
			if(onLoginSuccess){
			
				if(revert_to_previous_contents)
					tc.revertEditPanelContents();
				
				onLoginSuccess();
			}
			else
				tc.updateToolsPanel();
				
			$(".user").show();
			$("#editPanel .out").hide();
			$("#editPanel .in a").text(message);
			$("#editPanel .in").show();
			
			$("#editPanel #login").hide();
			$("#editPanel #logout").show();
				
			if($("#map_problems").hasClass("selectedLayer"))
				$(".layersContainer .layer#map_problems a").show();
		}
		else
			tc.showLoginForm(onLoginSuccess,revert_to_previous_contents,message);
	}

	Login.formLogin("loginForm",onLogin);
  }

//--------------------------------------------------------------------------------------------------------------------
//Assumes this.featureQueue contains two elements
Cartouche.prototype.mergeRoads = function(){
         this.roadManipulation("/map_edit/merge_segments.php");
}
//--------------------------------------------------------------------------------------------------------------------
//Assumes this.featureQueue contains two elements
Cartouche.prototype.connectRoads = function(){
        this.roadManipulation("/map_edit/connect_segments.php");
}
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.oneWayToTwoWay = function(){
        this.roadManipulation("/map_edit/split_directions.php");
}
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.deleteRoad = function(){

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

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

		});
	});
}
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.roadManipulation = function(manipulation_url,onSuccess){
   
      var tc = this;
     
	this.requiresConfirm(
		this.getRequiresLogin(function(){

		      var params = {};
		      if(tc.featureQueue.length==1)
			  params["id"] =  tc.featureQueue[0].replace("roads.","");
		      else
			  for(var i in tc.featureQueue){
			      var seg_num = parseInt(i)+1;
			      params["seg"+seg_num] = tc.featureQueue[i].replace("roads.","");
			  }
		      
		      var url = manipulation_url;
		    
		     var resultCallback = function(response){
			 var json = eval("("+response+")");
			 if(json.reply.error){
				tc.revertEditPanelContents();
				tc.displayEditPanelMessage(json.reply.message,is_error=true);
			}
			 else{
			       tc.displayEditPanelMessage(json.reply.message,is_error=false);
			       tc.redrawFeatureType("roads");
			       tc.redrawFeatureType("restrictions");
			       tc.deselectAll();
			       if(onSuccess)
					onSuccess();
			 }
		     }

		     $.post( url, params,resultCallback ) ;
		})
	);
}
//--------------------------------------------------------------------------------------------------------------------
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);
	}
	
}
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.updateRoundaboutDisplay = function(){

	var tc = this;
	var params = $("#editPanel form").serialize();
	var url = "/map_edit/draw_circle.php";
	$.post( url, params,tc.getParseRoundabout()) ;
}
//--------------------------------------------------------------------------------------------------------------------
/**
 * assumes feature queue has one feature init - a node
 */
Cartouche.prototype.createRoundabout = function(){
    
	var tc = this;
	var node = tc.selectedFeatures[tc.featureQueue[0]];
	var point = node.vector.geometry;
	var params =  { "longitude": point.x,
					"latitude": point.y
	}


	var url = "/map_edit/draw_circle.php";
	
	var resultCallback = function(response){
	 
		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);
			if (character.match(/[\d\s\b]/g)) {
				return true;
			}
			 else {
				return false;
			}

		});
		
	  
	}

	$.post( url, params,resultCallback ) ;
   
}
//-------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.cancelCreateRoundabout = function(){

	//restore node display
	var feature =this.selectedFeatures[this.featureQueue[0]].vector;
	this.featuresLayer.addFeatures(feature);
	this.updateToolsPanel();
}
//-------------------------------------------------------------------------------------------------------------------
/**
	Assumes only one node is selected
*/
Cartouche.prototype.saveMoveNode = function(){

	var tc = this;
      
	this.requiresLogin(function(){
		    
		var node = tc.selectedFeatures[tc.featureQueue[0]];
		var point = node.vector.geometry;
		var params =  { "id":node.details.id,"longitude": point.x, "latitude": point.y };
		
		var type ="nodes";
		var url = "/map_edit/move_node.php";
		    
		var saveResult = function(response){
			
			var feature = tc.selectedFeatures[tc.featureQueue[0]].vector;
			
			var json = eval("("+response+")");
			if(json.reply.error){
				tc.displayEditPanelMessage(json.reply.message,is_error=true);
				tc.featuresLayer.removeFeatures(feature);
				feature.geometry = tc.dragNodeControl.originalGeometry.clone();
				tc.featuresLayer.addFeatures(feature);
			}
			else{
				tc.displayEditPanelMessage(json.reply.message,is_error=false);
				tc.dragNodeControl.originalGeometry =feature.geometry.clone();
				tc.redrawFeatureType(type);
			}
		}

		$.post( url, params,saveResult ) ;
	},revert_to_previous_contents=true);
}
//-------------------------------------------------------------------------------------------------------------------
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.onSplitRoad = function(e){
         
          this.modifyControl.deactivate();
          var lonlat = this.map.getLonLatFromViewPortPx(e.xy);
          var url='/wms/israel_wfs2';
         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);
	//console.log(bounds);
          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_split_road:hidden").show();
		tc.featuresLayer.removeFeatures(newNodeVector);
		newNodeVector.geometry = new OpenLayers.Geometry.Point(x=lonlat.lon,y=lonlat.lat);
		tc.featuresLayer.addFeatures(newNodeVector);
		
	}, "xml" ) ;
          
     }
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.splitRoad = function(){
    
     this._setToolsPanelContents("split_road_tools");
     $("#editPanel #save_split_road").hide();
     this.map.events.unregister("click", this, this.onclick);
     this.map.events.register("click", this, this.onSplitRoad);
}
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.saveSplitRoad = function(){
    
     var tc = this;
     this.requiresLogin(function(){

              var params = {};
              var point = tc.newFeaturesLayer.features[0].geometry;
	      
	      if(tc.aux_split_road.length>0)
			params["id"] = tc.featureQueue[0].replace("roads.","")+","+tc.aux_split_road.replace("roads.","");
	      else
			params["id"] = tc.featureQueue[0].replace("roads.","");
		
              params["longitude"] = point.x;
              params["latitude"] = point.y; 
              
              var url = "/map_edit/do_split.php";
            
             var resultCallback = function(response){
                 var json = eval("("+response+")");
                 if(json.reply.error)
                      tc.displayEditPanelMessage(json.reply.message,is_error=true);
                 else{
                       tc.exitSplitRoad();
                       tc.redrawFeatureType("roads");
                       tc.redrawFeatureType("restrictions");
		       tc.deselectAll();
                 }
             }

             $.post( url, params,resultCallback ) ;
    },revert_to_previous_contents=true);
}
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.exitSplitRoad = function(){
    
       this.map.events.unregister("click", this, this.onSplitRoad);
       this.map.events.register("click", this, this.onclick);
       this.newFeaturesLayer.removeFeatures(this.newFeaturesLayer.features);
       this.updateToolsPanel();
}
//--------------------------------------------------------------------------------------------------------------------      
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 = $("#viewPanel #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 = $("#viewPanel #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 = $("#viewPanel #zoom_out");		
		if(tc.map.zoom == 0 && !zoomOutLink.hasClass("disabled"))
			zoomOutLink.addClass("disabled");
		else 
			if(zoomOutLink.hasClass("disabled"))
				zoomOutLink.removeClass("disabled");
			
		var zoomInLink = $("#viewPanel #zoom_in");
		if(tc.map.zoom == tc.map.numZoomLevels-1 && !zoomInLink.hasClass("disabled"))
			zoomInLink.addClass("disabled");
		else 
			if(zoomInLink.hasClass("disabled"))
				zoomInLink.removeClass("disabled");
			
	}
}
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.zoomIn = function(){
	this.map.zoomIn();
}
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.zoomOut = function(){
	this.map.zoomOut();
}
//--------------------------------------------------------------------------------------------------------------------
Cartouche.prototype.find = function(){
	 
	 var url = "/libs/lookup.php";
	 var params = $("#viewPanel form").serialize();
	 
	 var tc = this;
	 var findResult = function(response){
	 
	     var json = eval("("+response+")");
	     if(json.reply.found){
	     
			var x = parseFloat(json.reply.point.split(" ")[0]);
			var y = parseFloat(json.reply.point.split(" ")[1]);
			var lonlat = new OpenLayers.LonLat(lon=x,lat=y);
			
			var left = parseFloat(json.reply.extent.split(" ")[0]);
			var top = parseFloat(json.reply.extent.split(" ")[1]);
			var right = parseFloat(json.reply.extent.split(" ")[2]);
			var bottom = parseFloat(json.reply.extent.split(" ")[3]);
			
			var zoom = Math.min(tc.map.getZoomForExtent(new OpenLayers.Bounds(left=left,top=top,right=right,bottom=bottom)),tc.MAX_AERIAL_PHOTO_ZOOM);
			tc.map.setCenter(lonlat,zoom);
			
			tc.markersLayer.clearMarkers();
			var marker = new OpenLayers.Marker(lonlat,OpenLayers.Marker.defaultIcon());
			tc.markersLayer.addMarker(marker);
			tc.displayViewPanelMessage("",is_error=false);
	     }
	     else
			tc.displayViewPanelMessage(json.reply.message,is_error=true);
	     
	 }

	 $.post( url, params,findResult );
	
}
//================================================
      
g_init_on_login=false;
g_cartouche = null;
$().ready(function(){
         
	
	if(window.screen.height <= 800){
		
		$("body").css("margin-top","0px");
		$("body").css("margin-bottom","0px");
		$("body").css("padding-top","0px");
		$("body").css("padding-bottom","0px");
		$("html").css("height","100%");
		$("body").css("height","100%");
		$("#cartouche").css("height","98%");
		
	}
	g_cartouche = new Cartouche(g_init_on_login);

});