// global vars for main, some holding fragments of json data e.g. for pois

var hariGeo  = {province: {lon:0,lat:0,bbox:[0,0,0,0], zoom: 10}, 
city:     {lon:0,lat:0,bbox:[0,0,0,0], zoom: 12}, 
district: {lon:0,lat:0, bbox:[0,0,0,0], zoom: 14},
area: {lon:0,lat:0,bbox:[0,0,0,0], zoom: 14},
brick: {lon:0,lat:0,bbox:[0,0,0,0], zoom: 14},
visible:  {bbox:[0,0,0,0]}, 
bboxString: "0,0,0,0"};

var hariJson = {
provinces:[], cities:[], districts:[], 
app:{}, cats:[], subcats:[], pois:[], adr2geo:[], geo2adr:[], poiRouter:[], router:[], contextMenu:[], mapMenu:[], areas:[] ,bricks:[]
};

var mapLeft          = "320px";
var mapLeftIfPoiEdit = "700px";

var allowPoiEdit = false;      
var lastCatId = 0;		
var poiLastId = 0;
var poiOffset = 0;
var poiLimit  = 15;
var poiCount  = 0;
var leftWidth = 320;
var routingFeatures = [];
var routfeat1 = null;
var routfeat2 = null;
var routvias = []; 
var gpxLayer  = null;
var menuItemId = 0;
var lastGeo = {};
var ctxRouteMode = "car";

// new: extending this for a further menu instead of the permalinks 
function addContextMenuItem(json) {
  addMenuItem(json, "contextMenu");
}
function addMapMenuItem(json) {
  addMenuItem(json, "mapMenu");
}

// json format {"label": "<string>",  "enabled":<boolean>, "handler":"functionName"}
function addMenuItem(json, menu) {
  if (typeof menu == 'undefined') menu = "contextMenu";
  menuItemId++;
  json.nr = menuItemId;

//if (typeof json.id == "undefined") json.id = json.nr;
//if (typeof hariJson[menu] == "undefined") hariJson[menu] = [];

  hariJson[menu].push(json);
  return menuItemId;
}

function NOdisableContextMenuItem(name) {
}

function setContextMenuItemState(id, state) {
  var len = hariJson.contextMenu.length;
  for (var i=0; i<len; i++) {
    if (hariJson.contextMenu[i].id == id) {
      hariJson.contextMenu[i].enabled = state;
    }
  }
  
  rebuildContextMenu();
}

function ctxSetRouteMode(mode) {
  ctxRouteMode = mode;
}

function ctxExample(e) {
  alert('Trigger was '+e.id+'\nAction was Open');
}

function ctxRouteClear() {
  stopInteractiveRoute();
  clearLine();
  
//  setContextMenuItemState("ctxRouteVia", false);
//  setContextMenuItemState("ctxRouteTo", false);
//  setContextMenuItemState("ctxRouteAgain", false);
//  setContextMenuItemState("ctxRouteClear", false);
 
  /*  
  removeMarker("ctxRoute1");  
  removeMarker("ctxRouteN");   
*/  
}

function removeRoutingFeatures(list) {

  $.each(list, function(i, item) {
    if (typeof item != "undefined") {
    //if (typeof item.name != "undefined") {
      try { removeMarker(item.name); } catch (e) {}
    //}
    try { vector_layer.removeFeatures([item]); } catch (e) {}
    }
  });

}

function ctxRouteFrom(e) {
  hariJson.router = [];
  hariJson.router.push(lastGeo);  

  removeRoutingFeatures([routfeat1]);
  if (routfeat1 != null) vector_layer.removeFeatures([routfeat1]);          
  
  ctxRouteClear();
  stopInteractiveRoute();
  
  //addLocationMarkers([{"name":"ctxRoute1","icon":"marker1.png", "lon":lastGeo.lon,"lat":lastGeo.lat}]);
  setStartFlagToGeo("markerA.png", lastGeo.lon, lastGeo.lat, false);
  setContextMenuItemState("ctxRouteVia", true);    
  setContextMenuItemState("ctxRouteTo", true);  
}

function ctxRouteVia(e) {
  hariJson.router.push(lastGeo);  
  
  setViaFlagToGeo("marker2.png", lastGeo.lon, lastGeo.lat, false);
  
  setContextMenuItemState("ctxRouteClear", true);
}

function ctxRouteTo(e) {
  hariJson.router.push(lastGeo);  
  
  //addLocationMarkers([{"name":"ctxRouteN","icon":"marker2.png", "lon":lastGeo.lon,"lat":lastGeo.lat}]);  
  setStopFlagToGeo("marker2.png", lastGeo.lon, lastGeo.lat, false);
  ctxRoute();
  //route(hariJson.router[0].lon, hariJson.router[0].lat, hariJson.router[1].lon, hariJson.router[1].lat);  
  
  setContextMenuItemState("ctxRouteAgain", true);
  setContextMenuItemState("ctxRouteClear", true);
  
}

function ctxRoute() {
  doInteractiveRoute("ctx");
}

function nwtxRoute() {
  doInteractiveRoute2("ctx");
}

function nwtxRouteFrom(e) {
	  if (typeof(hariJson.router) == 'undefined'){
	    hariJson.router = [];
	  }
	  hariJson.router.push(lastGeo);  

	  removeRoutingFeatures([routfeat1]);
	  if (routfeat1 != null) vector_layer.removeFeatures([routfeat1]);          

	  nwsetStartFlagToGeo(lastGeo.lon, lastGeo.lat, false);
	  if (routfeat2 != null)  nwtxRoute();
}

function nwtxRouteTo(e) {
	  if (typeof(hariJson.router) == 'undefined'){
		hariJson.router = [];
	  }
	  hariJson.router.push(lastGeo);
	  
	  removeRoutingFeatures([routfeat2]);
	  if (routfeat2 != null) vector_layer.removeFeatures([routfeat2]);  
	  
	  nwsetStopFlagToGeo(lastGeo.lon, lastGeo.lat, false);
	  if (routfeat1 != null)  nwtxRoute();

}

function initPointSearch(){
    if (!window.PointSearch) {
    	window.PointSearch = new OpenLayers.Layer.Vector("PointSearch",{displayInLayerSwitcher: false});
    	map.addLayer(window.PointSearch);
    }
    if (!window.PointSearchDrag) {
    	window.PointSearchDrag = new OpenLayers.Control.DragFeature(PointSearch);
    	window.PointSearchDrag.onComplete = dragPoiComplete;
    	map.addControl(window.PointSearchDrag);
    }
}

function closePointSearch(){
    if (window.PointSearchDrag) {
    	window.PointSearchDrag.deactivate();
    	map.removeControl(window.PointSearchDrag);
    	delete PointSearchDrag;
    }
    if (window.SearchPoint) {
    	//if (SearchPoint.marker){
    	//	SearchPoint.marker.destroy();
    	//}
    	SearchPoint.destroy();
    	delete SearchPoint;
    }    
    if (window.PointSearch) {
    	map.removeLayer(PointSearch);
    	window.PointSearch.destroy();
    	delete PointSearch;
    }


}

function ctxCenterPointClear() {
	while (1){
	  	var p  = PointSearch.getFeatureBy("name","SearchPoint")
		if (!p){
			break;	  
		}
		if (p.marker) removeMarker("SearchPoint");
		p.destroy();
	}  
	window.PointSearchDrag.deactivate();
	map.removeControl(window.PointSearchDrag);
}

function nwtxCenterPoint(e) {
	  ctxCenterPointClear()
	  
	  //var lonlat1 = map.getLonLatFromViewPortPx(e.xy).clone().transform(map.projection, map.displayProjection);   
	  
	  var lonlat = new OpenLayers.LonLat(parseFloat(lastGeo.lon), parseFloat(lastGeo.lat));
	  
	  lonlat = lonlat.transform(map.displayProjection, map.projection);
	  
	  var point = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);

	  SearchPoint = new OpenLayers.Feature.Vector(point);
	  SearchPoint.marker = null;
	  SearchPoint.lon = lastGeo.lon;
	  SearchPoint.lat = lastGeo.lat;
	  SearchPoint.name = "SearchPoint";

	  //removeMarker   ("SearchPoint");
	  var image_url = "/images/marker_yellow.png";
	  addImageMarker ("SearchPoint", image_url, lastGeo.lon, lastGeo.lat, 20, 34, -10, -34);
	  var marker = markers["SearchPoint"];
	  if (marker){
		  SearchPoint.marker = marker;
		  SearchPoint.name   = "SearchPoint";
	  }

	  $('#ptaddr').val(''+lastGeo.lon+','+lastGeo.lat+'');
	  PointSearch.addFeatures([SearchPoint]);
	  PointSearchDrag.activate();
	  
}

function saveGeo(e) {
  if (!e) e = window.event;    
  //if (OpenLayers.Event.isRightClick(e)) {  
  var lonlat = map.getLonLatFromViewPortPx(e.xy);      		
  lonlat = lonlat.transform(map.projection, map.displayProjection); 
  lastGeo = lonlat; //hariJson.router.push(lonlat);
  //alert(lonlat.lon +"#"+ lonlat.lat);
  //}
}


function rebuildMenus() {
  rebuildContextMenu();
  rebuildMapMenu();  
}

// http://www.trendskitchens.co.nz/jquery/contextmenu/
function rebuildContextMenu() {
  map.events.includeXY = true;
  OpenLayers.Events.includeXY = true;

  $.contextMenu.defaults({
    menuStyle : {
      width : "200px"
    } 
  });

  var domObj = $('#contextMenu');
  domObj.remove();
  
  domObj = $('<div class="contextMenu" id="contextMenu" style="display:none;"></div>');
  domObj.empty(); // maybe this is a rebuild of changed functions!  
  var ulObj = $('<ul style="list-style-type:none"></ul>');
  ulObj.empty();
  domObj.append(ulObj);

  var binds = {};
  $.each(hariJson.contextMenu, function(i,item) { 
    if (typeof item.enabled == 'undefined' || item.enabled == true) {

      var imgStr = "";
      if (item.id == "nwtxRouteFrom" || item.id == "nwtxRouteTo"){
	      if (item.icon) imgStr = '<img src="'+ Sensus.urlMake('images/'+item.icon+'.png') +'" />';
	      ulObj.append('<li id="'+item.id+'"><nobr>'+imgStr+' '+item.label+' </nobr></li>');
	      binds[item.id] = item.handler;
      }else if(item.id == "ctxCreatePoi"){
		  if (allowPoiEdit == true){
			  if (item.icon) imgStr = '<img src="'+ Sensus.urlMake('images/'+item.icon+'.png') +'" />';
		      ulObj.append('<li id="'+item.id+'"><nobr>'+imgStr+' '+Sensus.tr(item.label)+'</nobr></li>');
		      binds[item.id] = item.handler;
		  }
      }else{
	      if (item.icon) imgStr = '<img src="'+ Sensus.urlMake('images/'+item.icon+'.png') +'" />';
	      ulObj.append('<li id="'+item.id+'"><nobr>'+imgStr+' '+Sensus.tr(item.label)+'</nobr></li>');
	      binds[item.id] = item.handler;
      }
      
    }
  });
  
  $('#rootBody').append(domObj);
  
  $('#map div').contextMenu('contextMenu', {
onContextMenu: function (e) {  
      if (!e) e = window.event;      
      e.xy = map.events.getMousePosition(e); //map.events.handleBrowserEvent(e);        
      saveGeo(e);
      return true; // else no ctxMenu
    },
bindings:  binds
  });    
};

// ex permalinks now as easy understandable clickable icons on the map
function rebuildMapMenu() {
  var domObj = $('<div class="mapMenu" id="mapMenu"></div>');
  domObj.empty(); // maybe this is a rebuild of changed functions!  
  var ulObj = $('<ul style="list-style-type:none; font-size:9px;"></ul>');
  domObj.append(ulObj);

  var binds = {};
  $.each(hariJson.mapMenu, function(i,item) { 
    if (typeof item.enabled == 'undefined' || item.enabled == true) {
      var domLi  = $('<img src="' + Sensus.urlMake('images/'+item.icon+'.png') + '" title="'+Sensus.tr(item.label)+'" hspace="16" /> ');
      //var domLi = $('<li id="'+item.id+'">'+imgStr+' '+Sensus.tr(item.label)+'</li>');
      domLi.click(item.handler);
      ulObj.append(domLi);
      binds[item.id] = item.handler;
    }
  });
  
  $('#rootBody').append(domObj);

}

function navGoHome()
{
	setBoxState('normal');
//	if (ValueKeeper.lon_base && ValueKeeper.lat_base && ValueKeeper.zoom_base){
//    	map.setCenter(new OpenLayers.LonLat(ValueKeeper.lon_base,ValueKeeper.lat_base).transform(new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject()),ValueKeeper.zoom_base);
//	}
}
var activebox="";
function slideAuto(boxFeatureName) { // jquery object
  if ( boxFeatureName == activebox) return;
  $.each(boxFeatureNames, function(i,val) {
    $('#box_'+val+'_content').slideUp(200);
    if (val=="route"){
    	ctxRouteClear();
    	setContextMenuItemState("nwtxRouteFrom", false);
    	setContextMenuItemState("nwtxRouteTo", false);
    }else if (val=="pointSearch"){
    	setContextMenuItemState("nwtxCenterPoint", false);
    	closePointSearch();    	
    }
  });
  $('#box_'+boxFeatureName+'_content').slideToggle(200);
  if (boxFeatureName=="route"){
	setContextMenuItemState("nwtxRouteFrom", true);
	setContextMenuItemState("nwtxRouteTo", true);
  }else if (boxFeatureName=="pointSearch"){
	initPointSearch();
	setContextMenuItemState("nwtxCenterPoint", true);
  }
  activebox=boxFeatureName;  
}


function multislideAuto(argBoxFeatureNames) {
  $.each(boxFeatureNames, function(i,val) {
    if(argBoxFeatureNames[val])
    {
      $('#box_'+val+'_content').slideDown(200);
    }
    else
    {
      $('#box_'+val+'_content').slideUp(200);
    }
  });
  //$('#box_'+boxFeatureName+'_content').slideToggle(200);
}

// toggle in adr2geo box the routing feature, if checkbox changed and update image markers
function chkAdrRouting() {
  if ($('#adrrouting').is(':checked')) { 
    $('tr.adrroute').show(); 
  } else { 
    $('tr.adrroute').hide();    
  }
  // update markers, e.g. remove or add target marker
  var geos = adr2geoGetAndMarkSelectedGeos();  
}

function chkRegionPins() {
  if ($('#regionpins').is(':checked')) { 
    addRegionPins("provinces");
  } else { 
    removeRegionPins("provinces");  
  }
}

var hasRegionPins = false;
function toggleRegionPins(region, state) {
  if (typeof state == 'undefined') state = -1;
  if ( (!hasRegionPins && state!=0) || state==1) {
    addRegionPins(region);   
    hasRegionPins = true;    
  } else {
    removeRegionPins(region);   
    hasRegionPins = false;    
  }
}

// init: hide masks for poi result list and poi edit form, add event togglers,  init categories + provinces + bbox
function initMain()
{
  var opts = {   
    
type: "POST", 
    
error: function(object,text,error){
      alert(object.status + " # " + text  + " # " + error);
    },

beforeSubmit: function(a,f,o) {
      $('#gpxmsg').html('<div align=center><img src="' + Sensus.urlMake('images/progress-100ms.gif') + '" vspace=4><br/>' 
      + Sensus.tr('uploading and map matching file...') + '</div>');        },
    
success: function(data) {
      // alert("success handler - never called under IE width dataType json - but text/html works!");    
      // an evil russian hack, as unfort. the jquery form plugin answers always with <pre> tags wrapped in case of success (WTF?)              
      data = data.replace(/<\/?pre>/ig, '');        
      eval(data); // due nasty ie6 behaviour we now get it back as text, not as json, but the text ist evaluable, or should be :)
      
      if (data.success == true) {      
        $('#gpxmsg').html(Sensus.tr('map matched gpx on the map now!'));
        if (gpxLayer != null) map.removeLayer(gpxLayer); // remove old gpx layer before

        // bugs in ie6 ?
        var url = Sensus.urlMake('data/gpx/'+parseInt(data.gid));
        gpxLayer = new OpenLayers.Layer.GML("GPX", url, {
format: OpenLayers.Format.GPX,
style: {strokeColor: "green", strokeWidth: 8, strokeOpacity: .5},
projection: new OpenLayers.Projection("EPSG:4326")
        });

        map.addLayer(gpxLayer);

        gpxLayer.events.register("loadend", gpxLayer.events, function() {
          try {          
            setmapextent (data.minlon, data.minlat, data.maxlon, data.maxlat);          
            if (typeof extent != 'undefined') {
              map.zoomToExtent(extent);
            }
          } catch (e) {
            alert(Sensus.tr("bounding box of the gpx data could not be retrieved"));
          }
        });
      } else {
        $('#gpxmsg').html(Sensus.tr('gpx upload or processing error'));      
      }
    }
  }

  $('#ajaxgpxform').ajaxForm(opts);


  if(Sensus.getUserId() > 0 && Sensus.getUserLvl() > 1)
  {
    allowPoiEdit = true;
    $('#createNewPoi').show();
  }

	if ($('#map').css('left') == "0px") {
	  resizeLeft(0); 
	  $('#leftcontent').hide();
	  correctMapHeight(); 
	} else {
	  resizeLeft();
	}
  
	initCats();
	initRegions();
	updateRegionBbox();
	//initArea();
	//slideAuto('categories');
  
	chkAdrRouting();

  // right click context menu items
//20100113 - Bener & Ömer   addContextMenuItem(  {"id": "ctxRouteFrom", "label": "route from",  "handler": function(e) { ctxRouteFrom(e);  }, "icon":"flag-green" } );
//  addContextMenuItem(  {"id": "ctxRouteVia", "label": "route via",  "handler": function(e) { ctxRouteVia(e); }, "icon":"flag-red", "enabled":true } );
//  
//  addContextMenuItem(  {"id": "ctxRouteTo", "label": "route to",  "handler": function(e) { ctxRouteTo(e); }, "icon":"flag-red", "enabled":true } );
//  addContextMenuItem(  {"id": "ctxRouteAgain", "label": "route again",  "handler": function() { ctxRoute(); }, "enabled":false, "icon":"edit-redo"});   
//  addContextMenuItem(  {"id": "ctxRouteClear", "label": "clear route",  "handler": function() { ctxRouteClear(); }, "enabled":false, "icon":"trash-empty" });
//20100113 - omer  addContextMenuItem(  {"id": "ctxRouteModeCar", "label": "set car route mode",  "handler": function() { ctxSetRouteMode('car'); },  "icon":"preferences-system-performance" });
//20100113 - omer  addContextMenuItem(  {"id": "ctxRouteModePedestrian", "label": "set pedestrian route mode",  "handler": function() { ctxSetRouteMode('pedestrian'); },  "icon":"preferences-desktop-accessibility" });

  addContextMenuItem(  {"id": "nwtxRouteFrom", "label": "Başlangıç Noktası",  "handler": function(e) { nwtxRouteFrom(e); }, "icon":"markerA", "enabled":false } );  
  addContextMenuItem(  {"id": "nwtxRouteTo",   "label": "Varış Noktası",  "handler": function(e) { nwtxRouteTo(e); }, "icon":"markerB", "enabled":false } );
  addContextMenuItem(  {"id": "nwtxCenterPoint",   "label": "Nokta Yakınında Ara",  "handler": function(e) { nwtxCenterPoint(e); }, "icon":"marker_yellow", "enabled":false } );
//  addContextMenuItem(  {"id": "nwtxRouteFrom", "label": "Buradan yol tarifi",  "handler": function(e) { nwtxRouteFrom(e); }, "icon":"markerA", "enabled":false } );  
//  addContextMenuItem(  {"id": "nwtxRouteTo",   "label": "Bu noktaya yol tarifi",  "handler": function(e) { nwtxRouteTo(e); }, "icon":"markerB", "enabled":false } );
//
  if (allowPoiEdit){
	  addContextMenuItem(  {"id": "ctxCreatePoi", "label": "create new POI",  "handler": function(e) { ctxCreatePoi(e); }, "icon":"flag-green" } );
  }
  addContextMenuItem(  {"id": "ctxGeo2Adr", "label": "get address",  "handler": function(e) { geo2adr(e); }, "icon":"user-identity" } );


//  // replacing the old perma links on the map menu
  addMapMenuItem (  {"id": "mmuToggleHome", "label": "Goto home",  "handler": function() { 
	navGoHome();
	toggleLeftPanel();
	toggleLeftPanel();
	if (ValueKeeper.lon_base && ValueKeeper.lat_base && ValueKeeper.zoom_base){
    	map.setCenter(new OpenLayers.LonLat(ValueKeeper.lon_base,ValueKeeper.lat_base).transform(new OpenLayers.Projection("EPSG:4326"),map.getProjectionObject()),ValueKeeper.zoom_base);
	}  
  },  "icon":"home48" } );
//  //addMapMenuItem (  {"id": "mmuToggleCameraImages", "label": "toggle camera",  "handler": function() { if(HaritaCameras){HaritaCameras.toggle();} },  "icon":"cameras" } );
//  addMapMenuItem (  {"id": "mmuToggleLeftPanel", "label": "toggle panel",  "handler": function() { toggleLeftPanel(); },  "icon":"edit-undo" } );
//  //addMapMenuItem (  {"id": "mmuToggleRegionPins", "label": "toggle region pins",  "handler": function() { toggleRegionPins('provinces'); },  "icon":"format-stroke-color" } );
//  addMapMenuItem (  {"id": "mmuJpgExport", "label": "JPG",  "handler": function() { mapExport ('jpg'); }, "icon":"jpg" } );
//  addMapMenuItem (  {"id": "mmuPrint", "label": "Print",  "handler": function() { mapPrint(true); }, "icon":"printer" } );
  // replacing the old perma links on the map menu
  //addMapMenuItem (  {"id": "mmuToggleCameraImages", "label": "toggle camera",  "handler": function() { if(HaritaCameras){HaritaCameras.toggle();} },  "icon":"cameras" } );
  addMapMenuItem (  {"id": "mmuToggleLeftPanel", "label": "toggle panel",  "handler": function() { toggleLeftPanel(); },  "icon":"ico_tamekran" } );
  //addMapMenuItem (  {"id": "mmuToggleRegionPins", "label": "toggle region pins",  "handler": function() { toggleRegionPins('provinces'); },  "icon":"format-stroke-color" } );
  addMapMenuItem (  {"id": "mmuJpgExport", "label": "JPG",  "handler": function() { mapExport ('jpg'); }, "icon":"ico_kaydet" } );
  addMapMenuItem (  {"id": "mmuPrint", "label": "Print",  "handler": function() { mapPrint(true); }, "icon":"ico_yazdir" } );
  // rebuildMenus()  is now called at the end of configureMap in mosaic ...  map is available as object then            
  
}

/*** Im truly afraid this might be called from somewhere. It's a typical A1 Minefunction. Just waiting here. Sitting. Waiting. Scaring the hell out of everybody. ***/
function quiek() {
  alert("quiek");
}

// center to a region from current select of provinces, or cities, or districts
function centerToRegion(region) {
  if (hariGeo[region].bbox) {
	 map.zoomToExtent(new OpenLayers.Bounds(hariGeo[region].bbox[0],hariGeo[region].bbox[1],hariGeo[region].bbox[2],hariGeo[region].bbox[3]).transform(new OpenLayers.Projection('EPSG:4326'),map.getProjectionObject()));  
  }else if (hariGeo[region].zoom) {
    setMapCenter(parseFloat(hariGeo[region].lon), parseFloat(hariGeo[region].lat), hariGeo[region].zoom);  
  } else {
    setMapCenter(parseFloat(hariGeo[region].lon), parseFloat(hariGeo[region].lat));
  }
}
//center to a area
function centerToArea(area) {
  if (hariGeo[area].bbox) {
	  map.zoomToExtent(new OpenLayers.Bounds(hariGeo[area].bbox[0],hariGeo[area].bbox[1],hariGeo[area].bbox[2],hariGeo[area].bbox[3]).transform(new OpenLayers.Projection('EPSG:4326'),map.getProjectionObject()));  
  }else if (hariGeo[area].zoom) {
    setMapCenter(parseFloat(hariGeo[area].lon), parseFloat(hariGeo[area].lat), hariGeo[area].zoom);  
  } else {
    setMapCenter(parseFloat(hariGeo[area].lon), parseFloat(hariGeo[area].lat));
  }
}

//center to a area
function centerToBrick(brick) {
  if (hariGeo[brick].bbox) {
	  map.zoomToExtent(new OpenLayers.Bounds(hariGeo[brick].bbox[0],hariGeo[brick].bbox[1],hariGeo[brick].bbox[2],hariGeo[brick].bbox[3]).transform(new OpenLayers.Projection('EPSG:4326'),map.getProjectionObject()));  
  }else if (hariGeo[brick].zoom) {
    setMapCenter(parseFloat(hariGeo[brick].lon), parseFloat(hariGeo[brick].lat), hariGeo[brick].zoom);  
  } else {
    setMapCenter(parseFloat(hariGeo[brick].lon), parseFloat(hariGeo[brick].lat));
  }
}

// not used anymore?
function centerToPoi(lon, lat) {
  setMapCenter(lon, lat, 14);
}

// returns a bbox as json array[4] if set, else false
function getRegionBbox() {
  // if visible bbox checkbox checked return its visible bbox 
  if ($('#regionSearchVisBbox').is(':checked')) {
    var visgeo = getCurrentMapExtent();
    hariGeo.visible.bbox[0] = visgeo.left;
    hariGeo.visible.bbox[1] = visgeo.bottom;
    hariGeo.visible.bbox[2] = visgeo.right;
    hariGeo.visible.bbox[3] = visgeo.top;
    return hariGeo.visible;
  }
  // else return smallest set region
  if (hariGeo.district.lon != 0) return hariGeo.district;
  if (hariGeo.city.lon     != 0) return hariGeo.city;
  if (hariGeo.province.lon != 0) return hariGeo.province;
  // tell if no region set at all
  return false;
}

// gets bbox if set and builds up a bbox string for search requests  
function updateRegionBbox() {
  var json = getRegionBbox();
  var bbox = "NO REGION BBOX SELECTED";
  if (json != false) {
    hariGeo.bboxString = json.bbox[0] + ',' + json.bbox[1] + ',' + json.bbox[2] + ',' + json.bbox[3];
  } else {
    hariGeo.bboxString = "0,0,0,0";
  }
  $('#regionBbox').text(hariGeo.bboxString); // if debug
}

// helper func
function arrayToOptions(ar, selectedValue) {
  
  var options = '';
  var len = ar.length;
  if (len == 0) return '<option value="0"></option>';
  for (i = 0; i < len; i++) {
    var item = ar[i];
    options += '<option ';
    if (typeof selectedValue != "undefined" && item[0] == selectedValue) {
      options += ' selected="selected" ';
    }
    options += ' value="' + item[0] + '">' + item[1] + '</option>';
  }
  return options;
}

// issue 50: hide or show left panel, give map full width
function toggleLeftPanel() {
  var cur = parseInt(document.getElementById('map').style.left);

  if (cur == 0) {
    resizeLeft(leftWidth);
    $('#header').show();
    document.getElementById('map').style.top = 75 + 'px';
    $('#leftcontent').show();
  } else {
    resizeLeft(0); 
    $('#leftcontent').hide();
    $('#header').hide();
    document.getElementById('map').style.top = 0 + 'px';
  }
  //mapUpdateSize();   
  correctMapHeight();
}

// for poi edit  we need left more space than in normal search view
function resizeLeft(w) {
  //var width = w || leftWidth;
  var width = w;
  if (typeof width == "undefined") width = leftWidth;
  $('#leftcontent').css('width', width + 'px');
  document.getElementById('map').style.left = width + 'px';  
  mapUpdateSize();
}

// link from poi result list back to search UI page
function backToInitPage()
{
  document.getElementById('map').style.left = mapLeft;
  correctMapHeight();
  stopPoiPosEdit();
  marker_layer.clearMarkers();
  resizeLeft();
  if (poiMode == 2) toggleRegionPins('provinces', 1);  
  forceRepaint();
}

// ie7 (and maybe ie8, but NOT ie6) needs a force repaint here, else its a game of luck whether poi results are shown
function forceRepaint() {
  $('#rootBody').addClass('fake');
  $('#rootBody').removeClass('fake');  
}


// get and display sub categories for a category id, if none jump over to getPois(id)
function getSubCats(id) {
  // clear last opened category first
  if (lastCatId != 0)
  {
    var oldContainer = $('#cat-' + lastCatId).next();
    oldContainer.slideUp('fast');
  }
  // remember last cat id for clearing it next time	
  lastCatId = id;

  // fetch sub cats
  $.getJSON(Sensus.urlMake("data/categories/" + id),
  function(data) {
    hariJson.subcats = data;
    var ar = new Array();
    var container = $('#cat-' + id).next();
    container.empty().hide();
    if (data.length > 0) {
      // if sub categories found, build them up
      $.each(data,
      function(key, val) {
        var id = val.cid;
        var name = val.name;
        var div = $('<div id="subcat-' + id + '" class="subcat clickable"></div>').attr('id', 'cat-' + id).css('cursor', 'pointer').text(name).click(          function() {
          getPois(id);
          return false;
        })
        addHover(div);
        container.append(div);
      });
      container.slideDown('fast');
    } else {
      // if no sub category found, jump over and fetch pois directly
      getPois(id);
    }
  });
}

// helper func
function addHover(domobj) {
  domobj.hover(function() {
    $(this).addClass('hover');
  },
  function() {
    $(this).removeClass('hover');
  });
}

function triggerMultiSelect(json, selVal, loadVal, triggerNext) { 
  //alert(json.domid + " # "+selVal + " # " + loadVal);
  if (typeof triggerNext == 'undefined') {
    triggerNext = true;
  }
  if (typeof loadVal == 'undefined') {
    loadVal = json.loadVal; 
  }
  json.loadVal = loadVal;
  json.selVal = selVal;
  if (loadVal < 0) {
    $('#'+json.domid).empty();
  } else {
    $.getJSON(json.url + loadVal,
    function(data) {
      var ar = new Array();
      $.each(data,
      function(i, item) {
        if (typeof item.rid != "undefined") ar.push([item.rid, item.name]); // first have to be id|rid|cid ;)
        if (typeof item.cid != "undefined") ar.push([item.cid, item.name]); // first have to be id|rid|cid ;)
      });
      var options = "";
      if (ar.length > 0) {
        ar.unshift([0, Sensus.tr("meta_select")]);
        options = arrayToOptions(ar, selVal); // workaround for ie6
      } 
      $('#'+json.domid).html(options); 
      
      document.getElementById(json.domid).value = selVal; // does not work in ie6          
      if (selVal != 0) {          
        if (triggerNext && json.next) triggerMultiSelect(json.next, 0, selVal);
      } else {
        if (triggerNext && typeof json.next != 'undefined') {
          triggerMultiSelect(json.next, 0, -1);
          if (typeof json.next.next != 'undefined') triggerMultiSelect(json.next.next, 0, -1);
        }
      }
    }
    );
    
  }
}

function createMultiSelect(owner, par, json, callback) {
  $.each(json, function(key, item) {
    var dom = $('<select id="'+item.domid+'" name="multiselect-'+owner+key+'" style="width:170px;"></select>'); // necessary hack for ie6 else width nearly 0px :(

    /* alternative waere: (geht nicht via (inner)html, nur so:)
    var option = document.createElement("option");
    option.text = 'my long text value to change stuff';
    option.value = '0';
*/
    dom.appendTo(par);
    
    if (key > 0)           item.prev = json[key-1];
    if (key < json.length) item.next = json[key+1];
    item.owner = owner;   
    //item.val = 0;
    dom.change(function() {        
      if (item.next) {
        //triggerMultiSelect(item, item.val, this.value);
        triggerMultiSelect(item, this.value);
      } 
      
    }); 
    //if (item.loadval)     triggerMultiSelect(item, 0, item.loadval);
  });  
  //triggerMultiSelect(json[0], 16);
  //if (typeof callback != 'undefined') callback.apply();  
}

//onload = function() {
function addRegionCatSelects(regDomId, catDomId, regStruct, catStruct) {
  var par   = $('#'+regDomId); 
//  window.regionJson  = 
//  [{"textdata":"select province", "domid":"r0", "url":Sensus.urlMake("data/regions/"), "loadVal":0 }, 
//  {"textdata":"select city",     "domid":"r1", "url":Sensus.urlMake("data/regions/"), "loadVal":-1 }, 
//  {"textdata":"select district", "domid":"r2", "url":Sensus.urlMake("data/regions/"), "loadVal":-1 } ];
  window.regionJson  = 
	  [{"textdata":"select province", "domid":"r0", "url":Sensus.urlMake("data/nregions/province/"), "loadVal":0 }, 
	  {"textdata":"select city",     "domid":"r1", "url":Sensus.urlMake("data/nregions/city/"), "loadVal":-1 }, 
	  {"textdata":"select district", "domid":"r2", "url":Sensus.urlMake("data/nregions/district"), "loadVal":-1 } ];
  
  createMultiSelect("region", par, window.regionJson);    // , regionCallback


  var par   = $('#'+catDomId); //catDomId$('#poiSearch'); // parent 
  window.categoryJson  = 
  [{"textdata":"select main cat", "domid":"c0", "url":Sensus.urlMake("data/categories/"), "loadVal":0}, 
  {"textdata":"select sub cat",  "domid":"c1", "url":Sensus.urlMake("data/categories/"), "loadVal":-1},
  {"textdata":"select detail cat",  "domid":"c2", "url":Sensus.urlMake("data/categories/"), "loadVal":-1}];
  
  createMultiSelect("category", par, window.categoryJson);   

  // preselect from db -- ie6 bugs here
  var ridLast=0;
  var i=0;
  while (regStruct.length > 0) { 
    var item = regStruct.pop();
    triggerMultiSelect(window.regionJson[i], item.rid, ridLast, false);  
    ridLast = item.rid;
    i++;
  }
  
  // preselect from db -- ie6 bugs here
  var cidLast=0;
  var i=0;
  while (catStruct.length > 0) { 
    var item = catStruct.pop();
    triggerMultiSelect(window.categoryJson[i], item.cid, cidLast, false);  
    cidLast = item.cid;
    i++;
  }

}

function addCatSelects(catDomId, catStruct) {

  var par   = $('#'+catDomId); //catDomId$('#poiSearch'); // parent 
  window.categoryJson  = 
  [{"textdata":"select main cat", "domid":"c0", "url":Sensus.urlMake("data/categories/"), "loadVal":0}, 
  {"textdata":"select sub cat",  "domid":"c1", "url":Sensus.urlMake("data/categories/"), "loadVal":-1},
  {"textdata":"select detail cat",  "domid":"c2", "url":Sensus.urlMake("data/categories/"), "loadVal":-1}];
  
  createMultiSelect("category", par, window.categoryJson);   
  
  // preselect from db -- ie6 bugs here
  var cidLast=0;
  var i=0;
  while (catStruct.length > 0) { 
    var item = catStruct.pop();
    triggerMultiSelect(window.categoryJson[i], item.cid, cidLast, false);  
    cidLast = item.cid;
    i++;
  }

}

function addImageMarker (name, image_url, lon, lat, width, height, offset_x, offset_y) {
	if (map == null) {
		markers[name] = {
			'image_url' : image_url,
			'width' : width,
			'height' : height,
			'offset_x' : offset_x,
			'offset_y' : offset_y,
			'lon' : lon,
			'lat' : lat
		};
		return;
	}
	var size;
	if (typeof (width) != 'undefined' && typeof (height) != 'undefined')
		size = new OpenLayers.Size(width, height);
	var offset;
	if (typeof (offset_x) != 'undefined'
			&& typeof (offset_y) != 'undefined')
		offset = new OpenLayers.Pixel(offset_x, offset_y);
	var icon = new OpenLayers.Icon(image_url, size, offset);
	addIconMarker(name, icon, lon, lat);
}

function addIconMarker (name, icon, lon, lat) {
	var marker = markers[name];
	if (marker && marker.CLASS_NAME)
		return;
	if (marker_layer == null) {
		marker_layer = new OpenLayers.Layer.Markers("POIMarkers");
		map.addLayer(marker_layer);
	}
	var lonlat = new OpenLayers.LonLat(lon, lat);
	lonlat = lonlat.transform(map.displayProjection,map.projection);
	marker = new OpenLayers.Marker(lonlat, icon);
	markers[name] = marker;
	marker_layer.addMarker(marker);
}

function addLocationMarkers(json) { //  20, 34, -10, -34);
  $.each(json, function(i,item) {
    var icon = Sensus.urlMake("images/"+item.icon);
    addImageMarker(item.name, icon, item.lon, item.lat, 32, 32, -5, -30 );
  });
}

function addRegionPins(region) {
  region = "provinces";

  $.getJSON(Sensus.urlMake("data/poi-regions/0"), function(data) 
  {
    
    $.each(data, function(k, poiregion) {
      var rid = parseInt(poiregion.rid);
      var item = getJsonById('provinces', rid);
      
      
      //$.each(hariJson[region], function(i,item) {
      var rid = item.rid;
      var lon = item.base_lon;
      var lat = item.base_lat;
      //var icon = Sensus.urlMake("images/pin.gif");
      var icon = Sensus.urlMake("pins/region.png");
      addImageMarker("rid_"+rid, icon, lon, lat, 64, 80); //, 35, 43);
      //
      marker = markers["rid_"+rid];
      marker.icon.setOpacity(1.0);    
      marker.rid = rid;
      marker.events.register('click', marker, function(evt) { 
        var rid = this.rid;
        var json = getJsonById(region, rid);
        setmapextent (json.bound_lon_min, json.bound_lat_min, json.bound_lon_max, json.bound_lat_max);     
        map.zoomTo(hariGeo.province.zoom);    
        getPois(-1, 0, "", rid);    
      });                                   
    });
    
  });

}

function setmapextent (bound_lon_min, bound_lat_min, bound_lon_max, bound_lat_max){
	
	 map.zoomToExtent(new OpenLayers.Bounds(bound_lon_min,bound_lat_min,bound_lon_max,bound_lat_max).transform(new OpenLayers.Projection('EPSG:4326'),map.getProjectionObject()));  
	
}

function removeMarker (name) {
	var old = markers[name];
	delete markers[name];
	if (old && old.CLASS_NAME == "OpenLayers.Marker") {
		marker_layer.removeMarker(old);
		old.destroy();
	}
}


function removeRegionPins(region) {
  region = "provinces";

  $.each(hariJson[region], function(i,item) {
    removeMarker("rid_"+item.rid);
  });
}

function saveCoords() {

}
function contextMenuRouteStart() {
  this.divSelect = document.getElementById("imageboxexport_selection");
  
  this.mosControl = new OpenLayers.Control();
  
  OpenLayers.Util.extend(this.mosControl,
  {
    
draw: function()
    {
      this.box = new OpenLayers.Handler.Click(FeatureImageBoxExport.mosControl, {"done": FeatureImageBoxExport.eventBbox});
      this.box.activate();
    }
    
  });
  
  var ll = map.getLonLatFromPixel(new OpenLayers.Pixel(argBbox.left, argBbox.bottom));
  var ur = map.getLonLatFromPixel(new OpenLayers.Pixel(argBbox.right, argBbox.top));
  
  ll = ll.transform(map.projection, map.displayProjection);            
  ur = ur.transform(map.projection, map.displayProjection);            
  
  FeatureImageBoxExport.bbox = [ll.lon, ll.lat, ur.lon, ur.lat];

}
function contextMenuRouteStop() {
}


function nwsetStartFlagToGeo(lon, lat, mode) {

	  var lonlat = new OpenLayers.LonLat(parseFloat(lon), parseFloat(lat));
	  lonlat = lonlat.transform(map.displayProjection, map.projection);
	  var point = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);

	  if (routfeat1 != null) vector_layer.removeFeatures([routfeat1]); 
	  removeRoutingFeatures([routfeat1]);
	  routfeat1 = new OpenLayers.Feature.Vector(point);
	  routfeat1.marker = null;
	  routfeat1.lon = lon;
	  routfeat1.lat = lat;
	  routfeat1.name = "routfeat1";

	  removeMarker   ("routfeat1");
	  var image_url = Sensus.urlMake("images/markerA.png");
	  addImageMarker ("routfeat1", image_url, lon, lat, 24, 38, -12, -38);
	  var marker = markers["routfeat1"];
	  if (marker){
	    routfeat1.marker = marker;
	    routfeat1.name   = "routfeat1";
	  }
	  if (!vector_layer.map){
	    map.addLayer(vector_layer);
	  }
	  $('#staddr').val(''+lon+','+lat+'');
	  vector_layer.removeFeatures([routfeat1]);    
	  vector_layer.addFeatures([routfeat1]);
	  map.addControl(drag_control);
	  drag_control.activate();

}

function nwsetStopFlagToGeo(lon, lat, mode) {

	  var lonlat = new OpenLayers.LonLat(parseFloat(lon), parseFloat(lat));
	  lonlat = lonlat.transform(map.displayProjection, map.projection);   
	  var point = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);

	  if (routfeat2 != null) vector_layer.removeFeatures([routfeat2]);  
	  removeRoutingFeatures([routfeat2]);  
	  routfeat2 = new OpenLayers.Feature.Vector(point);
	  routfeat2.marker = null;
	  routfeat2.lon = lon;
	  routfeat2.lat = lat;
	  routfeat2.name = "routfeat2";

	  removeMarker   ("routfeat2");
	  var image_url = Sensus.urlMake("images/markerB.png");
	  addImageMarker ("routfeat2", image_url, lon, lat, 24, 38, -12, -38);
	  var marker = markers["routfeat2"];
	  if (marker){
		routfeat2.marker = marker;
		routfeat2.name   = "routfeat2";
	  }
	  if (!vector_layer.map){
		map.addLayer(vector_layer);
	  }
	  $('#toaddr').val(''+lon+','+lat+'');
	  vector_layer.removeFeatures([routfeat2]);
	  vector_layer.addFeatures([routfeat2]);
	  map.addControl(drag_control);
	  drag_control.activate();

}


function setStartFlagToGeo(icon, lon, lat, mode) {
  if (!vector_layer.map){
	 map.addLayer(vector_layer);
  }

  //if (mode != "contextMenu") {
  var lonlat = new OpenLayers.LonLat(parseFloat(lon), parseFloat(lat));
  lonlat = lonlat.transform(map.displayProjection, map.projection);   


  var point = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);

  if (routfeat1 != null) vector_layer.removeFeatures([routfeat1]); 
  removeRoutingFeatures([routfeat1]);
  routfeat1 = new OpenLayers.Feature.Vector(point);
  routfeat1.marker = null;
  routfeat1.lon = lon;
  routfeat1.lat = lat;
  routfeat1.name = "routfeat1";

  //removeMarker   ("markerA");    
  //addLocationMarkers([{"name":"markerA","icon":icon, "lon":lon,"lat":lat}]);

  removeMarker   ("routfeat1");
  var image_url = Sensus.urlMake("images/markerA.png");
  addImageMarker ("routfeat1", image_url, lon, lat, 24, 38, -12, -38);
	var marker = markers["routfeat1"];
	if (marker){
		routfeat1.marker = marker;
		routfeat1.name   = "routfeat1";
	} 
  vector_layer.removeFeatures([routfeat1]);
  vector_layer.addFeatures([routfeat1]);
  map.addControl(drag_control);
  drag_control.activate();
  
  if(HaritaStroer)
  {
    HaritaStroer.setRoute([]);
  }    
}


function setViaFlagToGeo(icon, lon, lat, mode) {

  var lonlat = new OpenLayers.LonLat(parseFloat(lon), parseFloat(lat));
  lonlat = lonlat.transform(map.displayProjection, map.projection);   
  var point = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);

  var nr = routvias.length;
  var viafeat = new OpenLayers.Feature.Vector(point);
  viafeat.marker = null;
  viafeat.lon = lon;
  viafeat.lat = lat;
  viafeat.name = "via"+nr;
  
  removeMarker(viafeat.name); 
  addLocationMarkers([{"name":viafeat.name,"icon":icon, "lon":lon,"lat":lat}]);
  
  vector_layer.addFeatures([viafeat]);  
  
  routvias.push(viafeat);
}

function setStopFlagToGeo(icon, lon, lat, mode) {

  var lonlat = new OpenLayers.LonLat(parseFloat(lon), parseFloat(lat));
  lonlat = lonlat.transform(map.displayProjection, map.projection);   
  var point = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);

  if (routfeat2 != null) vector_layer.removeFeatures([routfeat2]);  
  removeRoutingFeatures([routfeat2]);  
  routfeat2 = new OpenLayers.Feature.Vector(point);
  routfeat2.marker = null;
  routfeat2.lon = lon;
  routfeat2.lat = lat;
  routfeat2.name = "routfeat2";
  
//  removeMarker   ("markerB"); 
//  addLocationMarkers([{"name":"markerB","icon":icon, "lon":lon,"lat":lat}]);
  removeMarker   ("routfeat2");
  var image_url = Sensus.urlMake("images/markerB.png");
  addImageMarker ("routfeat2", image_url, lon, lat, 24, 38, -12, -38);
  var marker = markers["routfeat2"];
  if (marker){
	routfeat2.marker = marker;
	routfeat2.name   = "routfeat2";
  }
  if (!vector_layer.map){
	  map.addLayer(vector_layer);
  }
  
  vector_layer.addFeatures([routfeat2]);
  map.addControl(drag_control);
  drag_control.activate();
/*  
  if(HaritaStroer)
  {
    HaritaStroer.setRoute([]);
  }  
*/  
}


function startInteractiveRoute() { 
  ctxRouteClear();

  $('#routemsg').html(Sensus.tr('place the markers to your wished end points, then click route'));

  // iff zoom level too low to see where roads are, increase zoom level
  if (map.zoom < 6) map.zoomTo(6);
  
  if (routfeat1 != null) stopInteractiveRoute();
  
  var bounds = getCurrentMapExtent();
  var center = bounds.getCenterLonLat();
  var lon = center.lon;
  var lat = center.lat; 

  var diffLon = (bounds.right - lon) / 10;
  var diffLat = (bounds.top - lat) / 10;
  
  setStartFlagToGeo("marker1.png", parseFloat(lon), parseFloat(lat), "leftPanel");
  setStopFlagToGeo("marker2.png", parseFloat(lon) + diffLon, parseFloat(lat) + diffLat, "leftPanel");
  /*    
    var lonlat = new OpenLayers.LonLat(parseFloat(lon), parseFloat(lat));
    lonlat = lonlat.transform(map.displayProjection, map.projection);            
    var point = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);
    routfeat1 = new OpenLayers.Feature.Vector(point);
    routfeat1.marker = null;
    routfeat1.lon = lon;
    routfeat1.lat = lat;
    routfeat1.name = "marker1";

  
    var lonlat = new OpenLayers.LonLat(parseFloat(lon)+diffLon, parseFloat(lat)+diffLat);
    lonlat = lonlat.transform(map.displayProjection, map.projection);            
    var point = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);
    routfeat2 = new OpenLayers.Feature.Vector(point);
    routfeat2.marker = null;
    routfeat2.lon = lon+diffLon;
    routfeat2.lat = lat+diffLat;    
    routfeat2.name = "marker2";

    addLocationMarkers([{"name":"marker2","icon":"marker2.png", "lon":lon+diffLon,"lat":lat+diffLat}, {"name":"marker1","icon":"marker1.png", "lon":lon,"lat":lat}]);
    
    map.addLayer(vector_layer);
    vector_layer.addFeatures([routfeat1, routfeat2]);
    map.addControl(drag_control);
    drag_control.activate();
    if(HaritaStroer)
    {
      HaritaStroer.setRoute([]);
    }
*/    
}

function doInteractiveRoute(mode) {
  mode = mode || "panel";
  
  if (routfeat1 != null) {
    //route(routfeat1.lon, routfeat1.lat, routfeat2.lon, routfeat2.lat, 1000, true, mode);
    route_old(routfeat1.lon, routfeat1.lat, routfeat2.lon, routfeat2.lat, 1000, true, mode);
  } else {
    alert(Sensus.tr("routing impossible as endpoints are not defined"));
  }
}

function doInteractiveRoute2(mode) {
	  mode = mode || "panel";
	  
	  if (routfeat1 != null) {
	    //route2(routfeat1.lon, routfeat1.lat, routfeat2.lon, routfeat2.lat, 1000, true, mode);
	    route_old(routfeat1.lon, routfeat1.lat, routfeat2.lon, routfeat2.lat, 1000, true, mode);
	  } else {
	    alert(Sensus.tr("routing impossible as endpoints are not defined"));
	  }
}

function doInteractiveRouteColor(color,isclear) {
	  var point1 = $('input[name="point1"]').val();
	  var point2 = $('input[name="point2"]').val();
	  
	  $('#routemsg').html('<div align=center><img src="'+Sensus.urlMake("images/progress-100ms.gif") + '" vspace=4><br/>' + Sensus.tr('routing... please wait...') + '</div>');
	  reqJSON("/TwoPointsApi/pointPathFinder.php?point1="+point1+"&point2="+point2,{Method:'GET'},
	  function(json) {      
	    if (json.success) { 
	      newRoute = json.viastr;
	      drawgeojsonLineColor(newRoute,color,false);
	      $('#routemsg').html('');
	    } else {
	      $('#routemsg').html(Sensus.tr('no road segment found - maybe your endpoints are too far from roads'));
	    }    
	  },
	  function(x,y,z) {
		  $('#routemsg').html(x.responseText);
	  }	  
	  );
}

function drawgeojsonLineColor(geojson,color,isclear){
	var linecolor = color || "#B0B000";
	var lineclear = isclear || false;
	var normalStyle = OpenLayers.Util.extend( {}, OpenLayers.Feature.Vector.style["default"] );
	normalStyle.strokeColor = linecolor;
	normalStyle.strokeOpacity = .7;
	normalStyle.strokeWidth = 8;
	var geojsonformat = new OpenLayers.Format.GeoJSON();
	var geometry = geojsonformat.parseGeometry(geojson);
	if (lineclear == true){ 
		clearLine();
	}
	lineFeature = new OpenLayers.Feature.Vector(geometry, null, normalStyle );
	var bounds;
	if(lineFeature) {
	  if(lineFeature.constructor != Array) {
		  lineFeature = [lineFeature];
	  }
	  for(var i=0; i<lineFeature.length; ++i) {
	      if (!bounds) {
	          bounds = lineFeature[i].geometry.getBounds();
	      } else {
	          bounds.extend(lineFeature[i].geometry.getBounds());
	      }
	  }
	  route_layer.addFeatures(lineFeature);
	  map.zoomToExtent(bounds);
	}
}


function stopInteractiveRoute() {
  $('#routemsg').html('');

removeRoutingFeatures(routvias);    
routvias = [];
  
  try {
    clearLine();
    removeMarker("routfeat1");
    $('#staddr').val('');
    removeMarker("routfeat2");
    $('#toaddr').val('');
    if (drag_control.active) {
      drag_control.deactivate();
      map.removeControl(drag_control);
    }
    removeRoutingFeatures([routfeat1, routfeat2]);

    vector_layer.removeFeatures([routfeat1, routfeat2]);
    if(HaritaStroer)
    {
      HaritaStroer.setRoute([]);
    }
  } catch (e) {};

  routfeat1 = null;
  routfeat2 = null;
}

function route_old(lon1,lat1,lon2,lat2,tolerance,zoomToExtent,mode) {
  var zoomTo = zoomToExtent || false;
  var tol = tolerance || 1000;
  
  var routeMode = $('input[name="routemode"]:checked').val();
  if (mode == "ctx") routeMode = ctxRouteMode;

  // in ff it routes from dest to start, now it shall route from start to dest as before... so we have to rerechange again ;-)
  tmplon1 = lon1;
  tmplat1 = lat1;
  lon1 = lon2;
  lat1 = lat2;
  lon2 = tmplon1;
  lat2 = tmplat1;

  $('#routemsg').html('<div align=center><img src="'+Sensus.urlMake("images/progress-100ms.gif") + '" vspace=4><br/>' + Sensus.tr('routing... please wait...') + '</div>');
  $.getJSON(Sensus.urlMake("data/route/?lon1="+lon1+"&lat1="+lat1+"&lon2="+lon2+"&lat2="+lat2+"&tol="+tol+"&mode="+routeMode),
  function(json) {      
    if (json.success) { 
      newRoute = new Array();
      newRoute = json.via;
      //newRoute.unshift(json.dest.longitude, json.dest.latitude); // insert before via
      //newRoute.push(json.start.longitude, json.start.latitude); // add after via      
      if(HaritaStroer)
      {
        var sendRoute = [];
        for(var elm in newRoute)
        {
          sendRoute.push(newRoute[elm]);
        }
        HaritaStroer.setRoute(sendRoute);
      }
      drawLine( newRoute );
      $('#routemsg').html('');
    } else {
      // do sth in case of error
      $('#routemsg').html(Sensus.tr('no road segment found - maybe your endpoints are too far from roads'));
    }    
  }
  );   

  og = orderGeoPair(lon1,lat1,lon2,lat2);
  var extent = setmapextent(og[0], og[1], og[2], og[3]);                      
  //if (zoomTo) map.zoomToExtent(extent);
}

function reqJSON(url, params, success, error) {
	var CallParams = {};
	CallParams.type = params.Method || "POST";
	CallParams.url = url;
	CallParams.processData = true;
	CallParams.data = params;
	CallParams.dataType = "json";
	CallParams.success = success;
	if (error) {
	    CallParams.error = error;
	}
	$.ajax(CallParams);

}


//reqJSON(
// "url of request",
//  { Parameters },
//  function(json) {    //Successful call
//	       //Do stuff with the JSON
//	      HideMessage();
//  },
//  function(x,y,z) {   //Some sort of error
//	       ShowMessageText(x.responseText);
//  }
//); 

function route(lon1,lat1,lon2,lat2,tolerance,zoomToExtent,mode) {
	  var zoomTo = zoomToExtent || false;
	  var tol = tolerance || 1000;
	  
	  var routeMode = $('input[name="routemode"]:checked').val();
	  if (mode == "ctx") routeMode = ctxRouteMode;

	  // in ff it routes from dest to start, now it shall route from start to dest as before... so we have to rerechange again ;-)
	  tmplon1 = lon1;
	  tmplat1 = lat1;
	  lon1 = lon2;
	  lat1 = lat2;
	  lon2 = tmplon1;
	  lat2 = tmplat1;

	  $('#routemsg').html('<div align=center><img src="'+Sensus.urlMake("images/progress-100ms.gif") + '" vspace=4><br/>' + Sensus.tr('routing... please wait...') + '</div>');
	  reqJSON(Sensus.urlMake("data/route/?lon1="+lon1+"&lat1="+lat1+"&lon2="+lon2+"&lat2="+lat2+"&tol="+tol+"&mode="+routeMode),{Method:'GET'},
	  function(json) {      
	    if (json.success) { 
	      newRoute = json.viastr;
	      drawgeojsonLine( newRoute );
	      $('#routemsg').html('');
	    } else {
	      $('#routemsg').html(Sensus.tr('no road segment found - maybe your endpoints are too far from roads'));
	    }    
	  },
      function(x,y,z) {   //Some sort of error
		  $('#routemsg').html(x.responseText);
	  }	  
	  );
}


function route2(lon1,lat1,lon2,lat2,tolerance,zoomToExtent,mode) {
	  var zoomTo = zoomToExtent || false;
	  var tol = tolerance || 1000;
	  
	  var routeMode = $('input[name="routemode"]:checked').val();
	  if (mode == "ctx") routeMode = ctxRouteMode;
	  var rtol = $('input[name="kaddr"]').val();
	  
	  // in ff it routes from dest to start, now it shall route from start to dest as before... so we have to rerechange again ;-)
	  tmplon1 = lon1;
	  tmplat1 = lat1;
	  lon1 = lon2;
	  lat1 = lat2;
	  lon2 = tmplon1;
	  lat2 = tmplat1;

	  $('#routemsg').html('<div align=center><img src="'+Sensus.urlMake("images/progress-100ms.gif") + '" vspace=4><br/>' + Sensus.tr('routing... please wait...') + '</div>');
	  reqJSON(Sensus.urlMake("data/route/?lon1="+lon1+"&lat1="+lat1+"&lon2="+lon2+"&lat2="+lat2+"&tol="+tol+"&mode="+routeMode+"&rtol="+rtol),{Method:'GET'},
	  function(json) {
	    if (json.success) { 
	      newRoute = json.viastr;
	      drawgeojsonLine2( newRoute );
	      $('#routemsg').html('');
	    } else {
	      // do sth in case of error
	      $('#routemsg').html(Sensus.tr('no road segment found - maybe your endpoints are too far from roads'));
	    }
	  },
      function(x,y,z) {   //Some sort of error
		  $('#routemsg').html(x.responseText);
	  }
	  );

}

function clearLine() {
  if (lineFeature != null) {
	  route_layer.removeFeatures(lineFeature);
	  lineFeature = null;
  }
}

var lineFeature = null;
function drawLine(geos) { 
  clearLine();
  var normalStyle = OpenLayers.Util.extend( {}, OpenLayers.Feature.Vector.style["default"] );
  normalStyle.strokeColor = "#00B000";
  normalStyle.strokeOpacity = .7;
  normalStyle.strokeWidth = 8;

  var pointList = [];
  
  while (geos.length > 0) {
    var lon = geos.shift();          
    var lat = geos.shift();
    var lonlat = new OpenLayers.LonLat(parseFloat(lon), parseFloat(lat));
    lonlat = lonlat.transform(map.displayProjection, map.projection);        
    pointList.push( new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat) );
  }
  
  lineFeature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(pointList), null, normalStyle ); 
  route_layer.addFeatures(lineFeature);             
}

function drawgeojsonLine(geojson) { 
	  
	  var normalStyle = OpenLayers.Util.extend( {}, OpenLayers.Feature.Vector.style["default"] );
	  normalStyle.strokeColor = "#00B000";
	  normalStyle.strokeOpacity = .7;
	  normalStyle.strokeWidth = 8;
      var geojsonformat = new OpenLayers.Format.GeoJSON();
      var geometry = geojsonformat.parseGeometry(geojson);
      clearLine();
      lineFeature = new OpenLayers.Feature.Vector(geometry, null, normalStyle );
      var bounds;
      if(lineFeature) {
          if(lineFeature.constructor != Array) {
        	  lineFeature = [lineFeature];
          }
          for(var i=0; i<lineFeature.length; ++i) {
              if (!bounds) {
                  bounds = lineFeature[i].geometry.getBounds();
              } else {
                  bounds.extend(lineFeature[i].geometry.getBounds());
              }

          }
          route_layer.addFeatures(lineFeature);
          map.zoomToExtent(bounds);
      }
}
function drawgeojsonLine2(geojson) { 
	  
	  var normalStyle = OpenLayers.Util.extend( {}, OpenLayers.Feature.Vector.style["default"] );
	  normalStyle.strokeColor = "#B0B000";
	  normalStyle.strokeOpacity = .7;
	  normalStyle.strokeWidth = 8;
    var geojsonformat = new OpenLayers.Format.GeoJSON();
    var geometry = geojsonformat.parseGeometry(geojson);
    clearLine();
    lineFeature = new OpenLayers.Feature.Vector(geometry, null, normalStyle );
    var bounds;
    if(lineFeature) {
        if(lineFeature.constructor != Array) {
      	  lineFeature = [lineFeature];
        }
        for(var i=0; i<lineFeature.length; ++i) {
            if (!bounds) {
                bounds = lineFeature[i].geometry.getBounds();
            } else {
                bounds.extend(lineFeature[i].geometry.getBounds());
            }

        }
        route_layer.addFeatures(lineFeature);
        map.zoomToExtent(bounds);
    }
}

function routePois() {
  clearLine();
  var poiRouter = hariJson.poiRouter;
  if (poiRouter.length != 2) {
    alert(Sensus.tr('you need to select two end points first'));
  } else {        
    var poi1 = poiRouter[0];
    var poi2 = poiRouter[1];
    route(parseFloat(poi1.lon), parseFloat(poi1.lat), parseFloat(poi2.lon), parseFloat(poi2.lat));
  }
}

// orders geo pair e.g. to be used for zoom to extent
function orderGeoPair(lon1,lat1,lon2,lat2) {
  var ar = [];
  if (lon2 < lon1) {
    tmp = lon1; lon1 = lon2; lon2 = tmp;
  }
  if (lat2 < lat1) {
    tmp = lat1; lat1 = lat2; lat2 = tmp;
  }
  return [lon1,lat1,lon2,lat2];
}

// pretty prints multiple choice of locations
function locs2human(nr) {
  //var subsets = [ "county", "state", "city", "streetName", "zip"]; // "country",
  var str = "";
  var i=0;

  var locs = hariJson.adr2geo[nr][0];
  $.each(locs, function (i, loc) { 
    if (typeof loc.location.name != 'undefined'){
        str += '<li><input type="radio" onchange="var geos=adr2geoGetAndMarkSelectedGeos();" name="adr2geosel'+nr+'" value="'+i+'" style="visibility:hidden;"';
        if (i==0) str += ' checked="checked" ';
        str += '>';
//    	str += '<br/>';
        var zoom = 10;
        //if (typeof adr['city'] != 'undefined') zoom = hariGeo.city.zoom;
        var adsrcek = '';
        if (loc.location.adm_level == 3){ zoom = 10; adsrcek = 'adrsrcrid=\'province/'+loc.location.rid+'\';';}
        if (loc.location.adm_level == 4){ zoom = 12; adsrcek = 'adrsrcrid=\'city/'+loc.location.rid+'\';';}
        if (loc.location.adm_level == 7){ zoom = 12; adsrcek = 'adrsrcrid=\'semt/'+loc.location.rid+'\';';}
        if (loc.location.adm_level == 8){ zoom = 14; adsrcek = 'adrsrcrid=\'district/'+loc.location.rid+'\';';}
        if (loc.location.adm_level == 9){ zoom = 16; adsrcek = 'adrsrcrid=\'street/'+loc.location.rid+'/'+loc.location.name+'\';';}
        
        if (loc.location.adm_level < 10){
        	str += ' <a href="javascript:'+adsrcek+'map.zoomToExtent(new OpenLayers.Bounds('+loc.location.bound_lon_min+','+loc.location.bound_lat_min+','+loc.location.bound_lon_max+','+loc.location.bound_lat_max+').transform(new OpenLayers.Projection(\'EPSG:4326\'),map.getProjectionObject()));">'+loc.location.dispname+'</a> ';
        }else{
        	str += ' <a href="javascript:'+adsrcek+'map.setCenter(new OpenLayers.LonLat('+loc.location.base_lon+','+loc.location.base_lat+').transform(new OpenLayers.Projection(\'EPSG:4326\'),map.getProjectionObject()),'+zoom+');">'+loc.location.dispname+'</a> ';	
        }
       // str +=  ": "+loc.location.name+"; "; // Sensus.tr(detail)+": "+
    }
    i++;
  });
  
  return '<div class="small"><ul>'+str+'</ul></div>';
}

function removeLocationMarkers() {
  try {
    removeMarker("adr2geomarker1");  
    removeMarker("adr2geomarker2");  
  } catch (e) {}
}

function adr2geoGetAndMarkSelectedGeos() {
  removeLocationMarkers();
  if (hariJson.adr2geo.length == 0) return false;
  var i=0;
  var geos=[];
  var len=1;
  if (adr2geoIsRouting()) len=2;
  for (i=1; i<=len; i++) {
    var val= $('input[name="adr2geosel'+(i-1)+'"]:checked').val();  
    if (typeof hariJson.adr2geo[(i-1)] != 'undefined') {
      var location = hariJson.adr2geo[(i-1)][0][val].location ;
      geos.push(location);
      addLocationMarkers([{"name":"adr2geomarker"+i,"icon":"marker"+i+".png", "lon":location.lon_base,"lat":location.lat_base}]);
    }
  } 
  return geos;
}

// routes between two locations retrieved from address2geo
function adr2georoute() {
  try { stopInteractiveRoute(); } catch (e) {}
  var geos = adr2geoGetAndMarkSelectedGeos();
  route(geos[0].longitude, geos[0].latitude, geos[1].longitude, geos[1].latitude, 10000);  
  $('#box_route_content').slideDown();  //   // show whats going on in the routing tab, should be reordered below the address search for that?
}

function adr2geoIsRouting() {
  var routing = false;
  if ($('#adrrouting').is(':checked')) {
    routing = true;
  }
  return routing;
}

function adr2geo(province, city, district, street, zip, province2, city2, district2, street2, zip2, state, state2) {

  var geo1 = [];
  var geo2 = [];

  hariJson.adr2geo = [];
  $('#adr2georesult1').html("");
  $('#adr2georesult2').html("");

  try {  
    removeMarker("adr2geomarker1");  
    removeMarker("adr2geomarker2");  
  } catch (e) {}
  
  var isRouting = adr2geoIsRouting();

  if ($.trim(province) == "" && $.trim(city) == "" && $.trim(district) == "" && $.trim(street) == "" && $.trim(zip) == ""
      || (isRouting && $.trim(province2) == "" && $.trim(city2) == "" && $.trim(district2) == "" && $.trim(street2) == "" && $.trim(zip2) == "" )) {
    alert(Sensus.tr("nothing to search or too less data"));
  } else {
    // due async behavior this is really ugly code, sorry :(
    $.getJSON(Sensus.urlMake("data/adr2geo/?province="+province+"&city="+city+"&district="+district+"&street="+street+"&zip="+zip+"&state="+state),
    function(json) {
      if (json.success && json.locations.length > 0) { 
        hariJson.adr2geo.push([json.locations]);
        $('#adr2georesult1').html(locs2human(0));
        if (!isRouting) {
          adr2geoGetAndMarkSelectedGeos();
        } else {
          // routing with target location
          $.getJSON(Sensus.urlMake("data/adr2geo/?province="+province2+"&city="+city2+"&district="+district2+"&street="+street2+"&zip="+zip2+"&state="+state2),
          function(json) {
            if (json.success && json.locations.length > 0) { 
              hariJson.adr2geo.push([json.locations]);
              $('#adr2georesult2').html(
              locs2human(1) + '<p/><div class="small"><a href="javascript:adr2georoute();">'+Sensus.tr("route between selected locations")+'</a></div>'
              );
              adr2geoGetAndMarkSelectedGeos();
            } else {
              $('#adr2georesult2').html(Sensus.tr("no match results for target address search"));
            }                                
          }
          );
        }          
      } else {
        $('#adr2georesult1').html(Sensus.tr("no match results for source address search"));                                       
      }    
    }
    ); 
  }

}

function geo2adr(e) {
  var lon=lastGeo.lon;
  var lat=lastGeo.lat;
  $.getJSON(Sensus.urlMake("data/geo2adr/?lon="+lon+"&lat="+lat), function(json) {
    if (json.success = false) { 
      alert(Sensus.tr("no matching address found"));
    } else {
      var adr = json.address;
      var str = "\n";
      $.each(adr, function(key, val) {
        str += Sensus.tr(key) + ": " + val + "<br/>\n";
      });
      
      //alert(str);

		var geopoint = new OpenLayers.LonLat(lastGeo.lon, lastGeo.lat);
		//geopoint = geopoint.transform(map.projection, map.displayProjection);
		
		var poptext = 'Longitude: ' + String.substr(geopoint.lon, 0, 11)
				+ '<br />Latitude: ' + String.substr(geopoint.lat, 0, 10)
				+ '<br />';
		poptext = poptext + str;
		
		var displonlat = new OpenLayers.LonLat(geopoint.lon, geopoint.lat);
		displonlat = geopoint.transform(map.displayProjection, map.projection);
		
		popup = new OpenLayers.Popup.Anchored("floatingmenu", displonlat, new OpenLayers.Size(200, 200),
				"<div id='floatingmenuitem' style='font-size:12px;'>" + poptext + "</div>", null, true, null);
		map.addPopup(popup, true);
   
      
      /*
{"address" : {"city" : "Özgürlük", "country" : "TÜRKIYE", "county" : "ALTINDAG", "houseNumber" : "181-1"
, "state" : "ANKARA", "streetName" : "Isimsiz S", "zip" : "06080"}, "distance" : 1.00000000, "success"
: true}
*/
    }
  });
  
}

//init region provinces
function initArea() {

  $.getJSON(Sensus.urlMake("data/areas"),
  function(data) {
	hariJson.areas = data;
    var ar = new Array();
    ar.push([0, "Tüm Bölgeler"]);
    $.each(data,
    function(i, item) {
      ar.push([item.rid, item.name]);
    });
    var options = arrayToOptions(ar);
    $('#selectArea').html(options);

    $('#selectArea').change(function() {
    	selectArea(this.value);
    });
    //$('#areaSearch').show(); // slideDown(500);
    
    
  });
}

function selectArea(id) {
	  if (id == 0) {
	    hariGeo.area.lon = 0;
	    hariGeo.area.lat = 0;
	  } else {
	    var json = getJsonById('areas', id);
	    hariGeo.area.lon = json.base_lon;
	    hariGeo.area.lat = json.base_lat;
	    hariGeo.area.bbox = [json.bound_lon_min, json.bound_lat_min, json.bound_lon_max, json.bound_lat_max];
	    centerToArea('area');
//	    $('#centerArea').click(function() {
//	      centerToArea('area');
//	    });
	    //$('#centerArea').show();
	  }
	  updateRegionBbox();
}

//init region provinces
function initBricks() {

  $.getJSON(Sensus.urlMake("data/bricks"),
  function(data) {
	hariJson.bricks = data;
    var ar = new Array();
    ar.push([0, "Tüm Brickler"]);
    $.each(data,
    function(i, item) {
      ar.push([item.rid, item.name]);
    });
    var options = arrayToOptions(ar);
    $('#selectBrick').html(options);
    $('#selectBrick').change(function() {
    	selectBrick(this.value);
    });
    //$('#areaSearch').show(); // slideDown(500);
    
    
  });
}

function selectBrick(id) {
	  if (id == 0) {
	    hariGeo.brick.lon = 0;
	    hariGeo.brick.lat = 0;
	  } else {
	    var json = getJsonById('bricks', id);
	    hariGeo.brick.lon = json.base_lon;
	    hariGeo.brick.lat = json.base_lat;
	    hariGeo.brick.bbox = [json.bound_lon_min, json.bound_lat_min, json.bound_lon_max, json.bound_lat_max];
	    centerToBrick('brick');
//	    $('#centerArea').click(function() {
//	      centerToArea('area');
//	    });
	    //$('#centerArea').show();
	  }
	  updateRegionBbox();
}


// init region provinces
function initRegions() {

  //$.getJSON(Sensus.urlMake("data/regions/0"),
  
  $.getJSON(Sensus.urlMake("data/nregions/province/0"),		  
  function(data) {
    hariJson.provinces = data;
    var ar = new Array();
    ar.push([0, Sensus.tr("select state")]);
    $.each(data,
    function(i, item) {
      ar.push([item.rid, item.name]);
    });
    var options = arrayToOptions(ar);
    $('#selectProvince').html(options);

    $('#selectProvince').change(function() {
      updateCitiesForm(this.value);
    });
    $('#regionSearch').show(); // slideDown(500);
    $('#resetRegion').click(function() {

      //setMapCenter(Sensus.lon_base, Sensus.lat_base, Sensus.zoom_base);
      
      $('#selectProvince').val(0);
      updateCitiesForm(0);
    }); 
    
  });
}

// build up main categories
function initCats() {

	var catreg = $('#selectCatOfRegionSearch');

	if (catreg) {
		$.getJSON(Sensus.urlMake("data/category-leafs/"),		
		function(data) {			
			var ar = new Array();
//			ar.push([0, Sensus.tr("Category selection")]);
			ar.push([0, "Tüm Kategoriler"]);
			$.each(data, function(i, item) {
				var ekstr ='';
				for (var i=0;i<item.level;i++) {
					if (i+1 == item.level){
						ekstr +='';
					}else{
						ekstr +='&nbsp; ';
					}
				}
				ar.push([item.cid, ekstr + item.name]);
			});
			var options = arrayToOptions(ar);
			catreg.html(options);		
		});
	}



//  $.getJSON(Sensus.urlMake("data/categories/0"),
//  function(data) {
//    var container = $('#poiCats');
//    container.empty();
//    container.hide();
//
//    $.each(data,
//    function(key, val) {
//      var id = val.cid;
//      var name = val.name;
//      var div = $("<div class='clickable'></div>").attr('id', 'cat-' + id).css('cursor', 'pointer').html('<img src="' + Sensus.urlMake("images/right.gif") + '"> ' + name).click(function() {
//        getSubCats(id);
//        return false;
//      })
//      addHover(div);
//      var div2 = $("<div></div>");
//      container.append(div);
//      container.append(div2);
//    });
//    container.slideDown('fast');
//    container.fadeIn('slow');
//  });
}

// get cities for a province id
function updateCitiesForm(id) {
  hariGeo.province.lon = 0;
  hariGeo.province.lat = 0;
  hariGeo.city.lon = 0;
  hariGeo.city.lat = 0;
  hariGeo.district.lon = 0;
  hariGeo.district.lat = 0;
  $('#centerProvince').hide();
  $('#centerCity').hide();
  $('#trSelectDistrict').hide();
  if (id == 0) {
    if(HaritaStroer)
    {
      HaritaStroer.setRegion(id);
    }
    $('#selectCity').html(arrayToOptions([]));
    $('#selectDistrict').html(arrayToOptions([]));
    $('#trSelectCity, #trSelectDistrict, #regionCenterButton').hide();
  }
  else {
    //$.getJSON(Sensus.urlMake("data/regions/" + id),
	$.getJSON(Sensus.urlMake("data/nregions/city/" + id),
    function(data) {
      hariJson.cities = data;
      var ar = new Array();
      ar.push([0, Sensus.tr("County selection")]);
      $.each(data,
      function(i, item) {
        ar.push([item.rid, item.name]);
      });
      var options = arrayToOptions(ar);
      $('#selectCity').html(options);
    });
    $('#trSelectCity').show();

    var json = getJsonById('provinces', id); //getProvinceJson(id);     
    
    if(HaritaStroer)
    {
      HaritaStroer.setRegion(id);
    }
    
    /*
    hariGeo.province.lon = json[3];
    hariGeo.province.lat = json[2];
    hariGeo.province.bbox = [json[4], json[5], json[6], json[7]];
    */
    hariGeo.province.lon = json.base_lon;
    hariGeo.province.lat = json.base_lat;
    hariGeo.province.bbox = [json.bound_lon_min, json.bound_lat_min, json.bound_lon_max, json.bound_lat_max];
    centerToRegion('province');
    $('#centerProvince').click(function() {
      centerToRegion('province');
    });
    $('#centerProvince').show();
  }
  $('#selectCity').change(function() {
    updateDistrictsForm(this.value);
  });
  updateRegionBbox();
}

// get districts for a city id
function updateDistrictsForm(id) {
  hariGeo.city.lon = 0;
  hariGeo.city.lat = 0;
  hariGeo.district.lon = 0;
  hariGeo.district.lat = 0;
  $('#centerDistrict').hide();  
  $('#trSelectDistrict, #selectDistrict').hide();  
  if (id == 0) {
    if(HaritaStroer)
    {
      HaritaStroer.setRegion(id);
    }
    $('#centerCity').hide();
    $('#selectDistrict').html(arrayToOptions([]));
  }
  else {
    var json = getJsonById('cities', id);
    hariGeo.city.lon = json.base_lon;
    hariGeo.city.lat = json.base_lat;
    hariGeo.city.bbox = [json.bound_lon_min, json.bound_lat_min, json.bound_lon_max, json.bound_lat_max];
    centerToRegion('city');
    if(HaritaStroer)
    {
      HaritaStroer.setRegion(id);
    }
    $('#centerCity').click(function() {
      centerToRegion('city');
    });
    $('#centerCity').show();
    //$.getJSON(Sensus.urlMake("data/regions/" + id),
    $.getJSON(Sensus.urlMake("data/nregions/district/" + id),
    function(data) {
      hariJson.districts = data;
      var ar = new Array();
      $.each(data,
      function(i, item) {
        ar.push([item.rid, item.name]);
      });
      if (ar.length > 0) { // at least the "select" and 1 district          
        ar.unshift([0, Sensus.tr("District selection")]);      
        var options = arrayToOptions(ar);      
        $('#selectDistrict').html(options);
        $('#selectDistrict').hide(); // special need for shitty ie6
        $('#trSelectDistrict, #selectDistrict').show();
        $('#selectDistrict').change(function() {
          selectDistrict(this.value);
        });          
      }
    });
  }
  updateRegionBbox();
}

function selectDistrict(id) {
  if (id == 0) {
    //$('#centerDistrict').hide();  
    //$('#trSelectDistrict').hide();  
    hariGeo.district.lon = 0;
    hariGeo.district.lat = 0;
  } else {
    var json = getJsonById('districts', id);
    if(HaritaStroer)
    {
      HaritaStroer.setRegion(id);
    }
    hariGeo.district.lon = json.base_lon;
    hariGeo.district.lat = json.base_lat;
    hariGeo.district.bbox = [json.bound_lon_min, json.bound_lat_min, json.bound_lon_max, json.bound_lat_max];
    centerToRegion('district');
    $('#centerDistrict').click(function() {
      centerToRegion('district');
    });
    $('#centerDistrict').show();
  }
  updateRegionBbox();
}

function getJsonById(subset, id) {
  var ar = hariJson[subset];
  if (subset == 'pois') {
    ar = hariJson.pois.results;
  }
  if (typeof ar != 'undefined') {
    var len = ar.length;
    for (var i = 0; i < len; i++) {
      var item = ar[i];
      if (subset != 'pois') {
        if (item.rid == id) return item;
      } else {
        if (item.pid == id) return item;
      }
    }
  }
  return false;
}

function hoverPoiResult(id, isOver) {
  //id = parseInt(id);
  var poiData = getJsonById('pois', id);
  if (isOver) {
    // when hover IN    : SHOW poi info window on map
    openPOITooltip(id, true, true);
  } else {
    // when hover OUT : HIDE poi info window on map
    closeCurrentPOITooltip();
  }
  return false;
}

function clickPoiResult(id) {
  goToPOI(id);
}

function editPoi(id)
{
  removeLocationMarkers();
  stopInteractiveRoute();
  
  document.getElementById('map').style.left = mapLeftIfPoiEdit;
  setBoxState("poiedit");
  correctMapHeight();
  
  if (id != 0) {
    $('#poi-edit-holder').load(Sensus.urlMake("data/poi-edit?id="+id));
    goToPOI(id, true);  
    startPoiPosEdit(id);
  } else {
    $('#poi-edit-holder').load(Sensus.urlMake("data/poi-create?lon="+lastGeo.lon+"&lat="+lastGeo.lat+""));  
    startPoiPosCreate();

  }
}

function clearPoiRouter() {
  hariJson.poiRouter=[];
  // todo: clear visible route on map
}


function chkPoiRouter(id) {
  var poiRouter = hariJson.poiRouter;  
  if ($('#poirouter-'+id).is(':checked')) { 
    if (poiRouter.length >= 2) {    
      $('#poirouter-'+id).attr('checked', false);
      alert(Sensus.tr("for routing you may select not more than two pois"));
    } else {
      var json = getJsonById('pois',id);
      poiRouter.push({'id':id, 'lon':json.lon, 'lat':json.lat});    
    }            
  } else {
    // simple delete
    if (poiRouter[0].id == id) {
      poiRouter.shift(); // del first elem
    } else {
      poiRouter.pop(); // del last elem
    }
  }
  
}

// show poi result list for an overgiven json poi object
function showPois(json) {
  toggleRegionPins('provinces', 0);

  var container = $('#poiResults');

  container.fadeOut('fast');
  container.empty().hide();
  container.append('<p/>'); // '+ data.numOfRows+' Results
  $('#poiRows').html('<b>' + poiCount + '</b> ' + 'Sonuç');
  var i=0;  
  $.each(json.results,
  function(key, val) {
    var id = val.pid;
    var name = val.name;
    if (name.length > 32) name = name.substr(0, 32) + "...";
    
    //var editstr =  "<div style='float:right; display:inline;' onclick='editPoi("+id+");'>&nbsp;[edit]&nbsp;</div>"; 
    var editstr =  "<img src=\"" + Sensus.urlMake("images/edit.png") + "\" onclick='editPoi("+id+");' align=right>"; 
    
    if (!allowPoiEdit) editstr = "";

    var poino = poiOffset + key + 1;    
    var poinostr = "<span class='poinr' nostyle='display:inline;position:relative;top:-2px;'>&nbsp;" + (poino) + "&nbsp;</span>";
    val.no = poino;    
    var div = $("<div></div>").addClass('clickable').attr('id', 'poi-' + id).css('cursor', 'pointer').html("<div class='poi' style='float:left;'>" + poinostr + name + "</div>").click(function() {
      clickPoiResult(id)
    }).hover(
    function() {
      $(this).addClass('hover');
      hoverPoiResult(id, true);
    },
    function() {
      $(this).removeClass('hover');
      hoverPoiResult(id, false)
    });

    var router = $("<input type='checkbox' style='float:right;' class='poirouter' id='poirouter-"+id+"' onclick='chkPoiRouter("+id+")' />");
    
    container.append(div);
    container.append(editstr);
    //container.append(router);
    container.append($("<br clear=all />"));
  });
  //container.show();
  container.fadeIn('fast');
  showPoisInMap(json);

  // ie7 (and maybe ie8, but NOT ie6) needs a force repaint here, else its a game of luck whether poi results are shown
  forceRepaint();
  setTimeout(forceRepaint, 100);
}

// helper funcs for poi result list pager navigation
function hasNextPois(id, offset) {
  if (offset + poiLimit < poiCount) return true;
  return false;
}
function hasPrevPois(id, offset) {
  if (offset > 0) return true;
  return false;
}

function getPois(id, dir, find, rid, cid) { 
  if (typeof find == 'undefined' || find == null) find = '';
  if (typeof rid == 'undefined'  || rid == null ) rid = 0;
  if (typeof cid == 'undefined'  || cid == null ) cid = 0; // NEW

  clearPoiRouter();
  setBoxState("progress");
  $("poiResults").html("");
  updateRegionBbox();
  if (dir != +1 && dir != -1) poiOffset = 0;

  if (id == 0) id = poiLastId;
  if (dir == +1 && hasNextPois(id, poiOffset)) poiOffset = poiOffset + poiLimit;
  if (dir == -1 && hasPrevPois(id, poiOffset)) poiOffset = poiOffset - poiLimit;
  var paramBbox = '';
  if (hariGeo.bboxString != '0,0,0,0') paramBbox = '&bbox=' + hariGeo.bboxString;
  var paramFind = '';
  if ($.trim(find) != '') paramFind = '&find=' + $.trim(find);
  var paramSubcat = '';
  if (paramFind == '') paramSubcat = '&subcat=' + id; // as interpreted (?), a search is not restricted to a subcat
  //new: order pois around centerpoint lon/lat, nearest listened first  
  var bounds = getCurrentMapExtent();
  var center = bounds.getCenterLonLat();
  var lon = center.lon; //30.699239;
  var lat = center.lat; //36.88705;

  //rid=25; // testing istanbul
  // if province set, overwrite geo lon/lat with base of province
  if (rid != 0) {
    var json = getJsonById('provinces', rid);
    lon = json.base_lon;
    lat = json.base_lat;
  }
  
  var cidStr = "";
  if (cid>0) paramSubcat = '&subcat='+cid;
  $.getJSON(Sensus.urlMake("data/points?rid="+rid+cidStr+"&lon="+lon+"&lat="+lat+"&limit=" + poiLimit + "&offset=" + poiOffset + paramSubcat + paramBbox + paramFind),
  function(data) {
    setBoxState("poiresults");
    
    if (data.success)
    {
      hariJson.pois = data;
      poiCount = data.numOfRows;
    }
    else
    {
      hariJson.pois = [];
      poiCount = 0;
      $('#poiRows').empty();
    }
    
    var showAllPois = false;
    if (hariJson.pois.results.length == poiCount) {
      showAllPois = true;
    }
    
    // show poi navi
    $('#poiNaviPrev').empty();
    $('#poiNaviNext').empty();
    if (poiCount > 0) {

      if (hasPrevPois(id, poiOffset) && !showAllPois) {
        $('#poiNaviPrev').append('<input type="button" class="nextprev" value="&laquo; ' + Sensus.tr('prev') + ' &laquo;" onclick="getPois(0,-1,\'' + find + '\','+rid+','+cid+');" />');
      } else {
        $('#poiNaviPrev').empty();
      }
      if (hasNextPois(id, poiOffset) && !showAllPois) {
        $('#poiNaviNext').append('<input type="button" class="nextprev" value="&raquo; ' + Sensus.tr('next') + ' &raquo;" onclick="getPois(0,+1,\'' + find + '\','+rid+','+cid+');" />');
      } else {
        $('#poiNaviNext').empty();
      }
      $('#poiOptions').show();
      showPois(data);

    } else {
      $('#poiRows').empty();
      $('#poiOptions').hide();      
      $('#poiResults').text(Sensus.tr('Sorry, no pois found.'));

    }
  });
  poiLastId = id;
}


function getSinglePoi(argPoiId)
{
	if(!argPoiId)
	{
		return(false);
	}
	
	$.getJSON(Sensus.urlMake("data/singlePoint"), {"pid": argPoiId},
		function(data)
		{
			
			if(data.results)
			{
				if(data.results.length > 0)
				{
					
					var lonlat = new OpenLayers.LonLat(parseFloat(data.results[0].lon), parseFloat(data.results[0].lat));
					lonlat = lonlat.transform(map.displayProjection, map.projection);
					
					map.zoomTo(14);
					map.panTo(lonlat);
					
				}
			}
			
			showPois(data);
			
		});
}



function openPoiPage(id) {
  var marker = getMarkerByPoiId(id);
  var url = Sensus.urlMake('content/poi?id='+marker.poi.pid+'&format=html&poipage=1');
  poipage = window.open(url, "Harita_PoiDetails", "dependent=yes,width=640,height=480,hotkeys=no,location=no,resizable=yes,scrollbars=yes");
}

function getPos(element, result) {
  var result = {};
  result.x = 0;
  result.y = 0;
  while(element != null ) {
    result.x += element.offsetLeft;
    result.y += element.offsetTop;
    element = element.offsetParent;
  }
  return result;
}

function getInnerHeight() {
  var thisInnerHeight = 0;
  if (window.innerHeight)                        {thisInnerHeight = window.innerHeight;}
  else if(document.documentElement.clientHeight) {thisInnerHeight = document.documentElement.clientHeight;}
  else if(document.body.clientHeight)            {thisInnerHeight = document.body.clientHeight;}
  return thisInnerHeight;
}
function getInnerWidth() {
  var thisInnerWidth = 0;
  if (window.innerWidth)                        {thisInnerWidth = window.innerWidth;}
  else if(document.documentElement.clientWidth) {thisInnerWidth = document.documentElement.clientWidth;}
  else if(document.body.clientWidth)            {thisInnerWidth = document.body.clientWidth;}
  return thisInnerWidth;
}

function correctMapHeight()
{

  //var headerHeight = parseInt(document.getElementById('hariHeaderBannerImageDiv').style.height);
  //var headerHeight = parseInt(document.getElementById('hariHeaderBannerImageDiv').clientHeight);
  var headerHeight = parseInt(document.getElementById('header').clientHeight);
  var leftContentHeight = getInnerHeight() - headerHeight;
  document.getElementById('leftcontent').style.height = leftContentHeight +"px"; // - header height

  var map_element = document.getElementById("map");
  if(!on_print_mode)
  {
    var thisInnerWidth = getInnerWidth();
    var thisInnerHeight = getInnerHeight();
    
    var pos = getPos(map_element);
    map_element.style.height = (thisInnerHeight - pos.y) + "px";
    map_element.style.width  = (thisInnerWidth  - pos.x) + "px";            
    if(typeof(mapUpdateSize) != "undefined")
    {
      mapUpdateSize();
    }
  }
  else
  {
    map_element.style.height = "100%";
    if(typeof(mapUpdateSize) != "undefined")
    {
      mapUpdateSize();
    }
  }
}

function setBoxState(argStateName)
{
  $("#left_state").attr("class", "sensus_state_" + argStateName);
  if(argStateName == "normal")
  {
    backToInitPage();
  }
  if(argStateName == "poiedit")
  {
    $("#leftcontent").css("width","640px");
    mapUpdateSize();
    if (vector_layer.map !=null){
	  map.removeLayer(vector_layer);
    }    
    if (vector_layer.map ==null){
	  map.addLayer(vector_layer);
    }
  }else{
	if (vector_layer.map !=null){
	  map.removeLayer(vector_layer);
	}
  }
}

/////



function Proto_FeatureImageExport()
{
  
  this.exHeight = 210;
  this.exWidth = 297;
  this.exDensity = 72;
  this.exZoom = 1;
  this.exLogo = true;
  this.exScalebar = true;
  
  this.exOverlays = {};
  
  
  this.doExport = function()
  {
    var overlays = "";
    
    for(overlay in this.exOverlays)
    {
      overlays = overlays + "&overlays[]=" + overlay;
    }
    
    var addit = "";
    
    var geo = getCenterGeo();
    var url = Sensus.urlMake('content/printexport?width='+this.exWidth+'&height='+this.exHeight+'&density='+this.exDensity+'&logo='+this.exLogo+'&scalebar='+this.exScalebar+'&zoom='+this.exZoom+"&lon="+geo.lon+"&lat="+geo.lat+"&scale="+geo.scale+"&format=jpg"+overlays);
    exportpage = window.open(url, "Harita_FeatureImageExport", "dependent=yes,width=800,height=600,hotkeys=no,location=no,resizable=yes,scrollbars=yes");
    exportpage.focus();
    
  }
  
  this.addOverlay = function(argOverlay)
  {
    this.exOverlays[argOverlay] = true;
  }
  this.delOverlay = function(argOverlay)
  {
    this.exOverlays[argOverlay] = false;
    if (typeof(this.exOverlays[argOverlay]) != 'undefined'){
    	delete this.exOverlays[argOverlay];
    }    
  }
  
  this.setHeight = function(argHeight)
  {
    this.exHeight = argHeight * 1;
  }
  this.setHeightI = function(argElement)
  {
    this.exHeight = argElement.value * 1;
    //argElement.value = this.exHeight;
  }
  this.getHeight = function()
  {
    return(this.exHeight);
  }
  
  this.setWidth = function(argWidth)
  {
    this.exWidth = argWidth * 1;
  }
  this.setWidthI = function(argElement)
  {
    this.exWidth = argElement.value * 1;
    //argElement.value = this.exWidth;
  }
  this.getWidth = function()
  {
    return(this.exWidth);
  }
  
  this.setDensity = function(argDensity)
  {
    this.exDensity = argDensity * 1;
  }
  this.setDensityI = function(argElement)
  {
    this.exDensity = argElement.value * 1;
    //argElement.value = this.exDensity;
  }
  this.getDensity = function()
  {
    return(this.exDensity);
  }
  
  this.setZoom = function(argZoom)
  {
    this.exZoom = argZoom * 1;
  }
  this.setZoomI = function(argElement)
  {
    this.exZoom = argElement.value * 1;
    //argElement.value = this.exZoom;
  }
  this.getZoom = function()
  {
    return(this.exZoom);
  }
  
  this.setLogo = function(argLogo)
  {
    this.exLogo = !(!argLogo);
  }
  this.setLogoI = function(argElement)
  {
    this.exLogo = argElement.checked;
  }
  this.getLogo = function()
  {
    return(this.exLogo);
  }
  
  this.setScalebar = function(argScalebar)
  {
    this.exScalebar = !(!argScalebar);
  }
  this.setScalebarI = function(argElement)
  {
    this.exScalebar = argElement.checked;
  }
  this.getScalebar = function()
  {
    return(this.exScalebar);
  }
  
}



function Proto_FeatureImageBoxExport()
{
  
  this.divSelect = false;
  this.bboxSelected = false;
  this.step = 0;
  this.bbox = [0, 0, 0, 0];
  
  this.exDetailLevel = 1;
  this.exLogo = true;
  this.exScalebar = true;
  
  this.exOverlays = {};
  
  
  this.mosControl = false;
  
  this.init = function()
  {
    this.divSelect = document.getElementById("imageboxexport_selection");
    
    this.mosControl = new OpenLayers.Control();
    
    OpenLayers.Util.extend(this.mosControl,
    {
      
draw: function()
      {
        this.box = new OpenLayers.Handler.Box(FeatureImageBoxExport.mosControl, {"done": FeatureImageBoxExport.eventBbox});
        this.box.activate();
      }
      
    });
    
  }
  
  this.resetStep = function()
  {
    this.divSelect.className = "sel_start";
    this.step = 0;
    
    this.mosControl.box.deactivate();
    map.removeControl(this.mosControl);
    
    document.getElementById("imagebox_bbox_left").innerHTML = "-";
    document.getElementById("imagebox_bbox_bottom").innerHTML = "-";
    document.getElementById("imagebox_bbox_right").innerHTML = "-";
    document.getElementById("imagebox_bbox_top").innerHTML = "-";
  }
  
  this.nextStep = function()
  {
    
    switch(this.step)
    {
      
    case 0:
      
      this.divSelect.className = "sel_selecting";
      this.step = 1;
      
      document.getElementById("imageexport_button_area").disabled = true;
      
      this.bboxSelected = false;
      map.addControl(this.mosControl);
      
      break;
      
    case 1:
      
      this.divSelect.className = "sel_export";
      this.step = 2;
      
      this.mosControl.box.deactivate();
      map.removeControl(this.mosControl);
      
      document.getElementById("imagebox_bbox_left").innerHTML = "-";
      document.getElementById("imagebox_bbox_bottom").innerHTML = "-";
      document.getElementById("imagebox_bbox_right").innerHTML = "-";
      document.getElementById("imagebox_bbox_top").innerHTML = "-";
      
      break;
      
    case 2:
      
      this.divSelect.className = "sel_start";
      this.step = 0;
      
      break;
      
    }
    
  }
  
  this.eventBbox = function(argBbox)
  {
    
    var ll = map.getLonLatFromPixel(new OpenLayers.Pixel(argBbox.left, argBbox.bottom));
    var ur = map.getLonLatFromPixel(new OpenLayers.Pixel(argBbox.right, argBbox.top));
    
    ll = ll.transform(map.projection, map.displayProjection);            
    ur = ur.transform(map.projection, map.displayProjection);            
    
    FeatureImageBoxExport.bbox = [ll.lon, ll.lat, ur.lon, ur.lat];
    
    if(!isNaN(FeatureImageBoxExport.bbox[0]) && !isNaN(FeatureImageBoxExport.bbox[1]) && !isNaN(FeatureImageBoxExport.bbox[2]) && !isNaN(FeatureImageBoxExport.bbox[3]))
    {
      document.getElementById("imageexport_button_area").disabled = false;
      
      document.getElementById("imagebox_bbox_left").innerHTML = FeatureImageBoxExport.bbox[0];
      document.getElementById("imagebox_bbox_bottom").innerHTML = FeatureImageBoxExport.bbox[1];
      document.getElementById("imagebox_bbox_right").innerHTML = FeatureImageBoxExport.bbox[2];
      document.getElementById("imagebox_bbox_top").innerHTML = FeatureImageBoxExport.bbox[3];
    }
    else
    {
      document.getElementById("imageexport_button_area").disabled = true;
      
      document.getElementById("imagebox_bbox_left").innerHTML = "-";
      document.getElementById("imagebox_bbox_bottom").innerHTML = "-";
      document.getElementById("imagebox_bbox_right").innerHTML = "-";
      document.getElementById("imagebox_bbox_top").innerHTML = "-";
    }
    
  }
  
  
  this.doExport = function(argDoPrint)
  {
    var overlays = "";
    
    for(overlay in this.exOverlays)
    {
      overlays = overlays + "&overlays[]=" + overlay;
    }
    if (map.projection.getCode() == 'EPSG:900913'){
	    var bboxw = new OpenLayers.Bounds (this.bbox[0],this.bbox[1],this.bbox[2],this.bbox[3]).transform(map.displayProjection,map.projection);
	    var srscode  = "&srs="+map.projection.getCode();
	    var url = Sensus.urlMake('content/printboxexport?bbox=' + bboxw.toBBOX() + srscode +'&detaillevel=' + this.exDetailLevel + '&logo=' + this.exLogo + '&scalebar=' + this.exScalebar + "&format=jpg" + overlays);
    }else{
    	var srscode  = "&srs=EPSG:4326";
    	var url = Sensus.urlMake('content/printboxexport?bbox=' + this.bbox[0] + "," + this.bbox[1] + "," + this.bbox[2] + "," + this.bbox[3] + srscode + '&detaillevel=' + this.exDetailLevel + '&logo=' + this.exLogo + '&scalebar=' + this.exScalebar + "&format=jpg" + overlays);
    }
    exportpage = window.open(url, "Harita_FeatureImageBoxExport", "dependent=yes,width=800,height=600,hotkeys=no,location=no,resizable=yes,scrollbars=yes");
    exportpage.focus();
    
    if(argDoPrint)
    {
      //$(exportpage).click(function() {exportpage.print();});
      exportpage.print();
    }
  }
  
  this.addOverlay = function(argOverlay)
  {
    this.exOverlays[argOverlay] = true;
  }
  this.delOverlay = function(argOverlay)
  {
    this.exOverlays[argOverlay] = false;
    if (typeof(this.exOverlays[argOverlay]) != 'undefined'){
    	delete this.exOverlays[argOverlay];
    }
  }
  
  this.setLogo = function(argLogo)
  {
    this.exLogo = !(!argLogo);
  }
  this.setLogoI = function(argElement)
  {
    this.exLogo = argElement.checked;
  }
  this.getLogo = function()
  {
    return(this.exLogo);
  }
  
  this.setScalebar = function(argScalebar)
  {
    this.exScalebar = !(!argScalebar);
  }
  this.setScalebarI = function(argElement)
  {
    this.exScalebar = argElement.checked;
  }
  this.getScalebar = function()
  {
    return(this.exScalebar);
  }
  
  this.setDetailLevel = function(argDetailLevel)
  {
    this.exDetailLevel = argDetailLevel * 1;
  }
  this.setDetailLevelI = function(argElement)
  {
    this.exDetailLevel = argElement.value * 1;
    //argElement.value = this.exZoom;
  }
  this.getDetailLevel = function()
  {
    return(this.exDetailLevel);
  }
  
  this.init();
  
}

function Proto_HaritaWindow(argId, argWindowElement, argWindowManager)
{
	
	this.window = false;
	this.windowManager = false;
	
	this.id = false;
	
	this.title = false;
	this.content = false;
	
	this.autoSize = false;
	this.autoMargin = false;
	
	this.top = false;
	this.left = false;
	this.height = false;
	this.width = false;
	
	
	this.init = function(argId, argWindowElement, argWindowManager)
	{
		this.id = argId;
		this.window = argWindowElement;
		this.windowManager = argWindowManager;
		this.window.hide();
		this.window.attr("id", "HaritaWindow_" + argId);
		
		this.title = $("#HaritaWindow_" + argId + " .window_template_title");
		this.content = $("#HaritaWindow_" + argId + " .window_template_content");
		
		this.setAutoMargin(25);
		this.setAutoSize(false);
		
		this.setHeight(480);
		this.setWidth(640);
		
		this.center();
		
		/*
		this.setTop(25);
		this.setLeft(25);
		*/
	}
		
	this.titleHtml = function(argHtml)
	{
		return(this.title.html(argHtml));
	}
	this.contentHtml = function(argHtml)
	{
		return(this.content.html(argHtml));
	}
	
	this.show = function()
	{
		var fadingOne = this;
		this.window.fadeIn(this.fadeTime);
	}
	
	this.hide = function()
	{
		this.window.fadeOut(this.fadeTime);
	}
	
	this.destroy = function()
	{
		var fadingOne = this;
		this.window.fadeOut(this.fadeTime, function()
		{
			fadingOne.window.remove();
			fadingOne.windowManager.windowList[this.id] = false;
		});
		
	}
	
	this.setAutoSize = function(argAutoSize)
	{
		this.autoSize = argAutoSize;
		this.marginize();
	}
	
	this.setAutoMargin = function(argAutoMargin)
	{
		this.autoMargin = argAutoMargin;
		this.marginize();
	}
	
	this.setHeight = function(argHeight)
	{
		this.height = argHeight;
		if(this.autoSize) {return;}
		this.window.css("height", this.height + "px");
	}
	
	this.setWidth = function(argWidth)
	{
		this.width = argWidth;
		if(this.autoSize) {return;}
		this.window.css("width", this.width + "px");
	}
	
	this.setTop = function(argTop)
	{
		this.top = argTop;
		if(this.autoSize) {return;}
		this.window.css("top", this.top + "px");
	}
	
	this.setLeft = function(argLeft)
	{
		this.left = argLeft;
		if(this.autoSize) {return;}
		this.window.css("left", this.left + "px");
	}
	
	this.center = function()
	{
		var body = $("body");
		
		this.setTop(Math.round((body.innerHeight() - this.height) / 2 ,0));
		this.setLeft(Math.round((body.innerWidth() - this.width) / 2 ,0));
	}
	
	this.marginize = function()
	{
		if(this.autoSize)
		{
			var body = $("body");
			
			this.window.css("top", this.autoMargin + "px");
			this.window.css("left", this.autoMargin + "px");
			this.window.css("height", (body.innerHeight() - (2 * this.autoMargin)) + "px");
			this.window.css("width", (body.innerWidth() - (2 * this.autoMargin)) + "px");
			
		}
	}
	
	
	
	
	this.init(argId, argWindowElement, argWindowManager);
	
}

function Proto_HaritaWindows(argTemplateId)
{
	
	this.template = false;
	this.windowList = {};
	this.fadeTime = 1500;
	
	this.create = function(argWindowId)
	{
		this.windowList[argWindowId] = new Proto_HaritaWindow(argWindowId, this.template.clone().appendTo("body"), this);
		return(this.windowList[argWindowId]);
	}
	
	this.get = function(argWindowId)
	{
		return(this.windowList[argWindowId]);
	}
	
	this.init = function(argTemplateId)
	{
		this.template = $("#" + argTemplateId);
	}

	this.init(argTemplateId);
	
}



function Proto_HaritaCameras()
{
	
	this.lastRequest = false;
	this.lastReqult = false;
	this.camMarkers = false
	this.detailWin = false;
	this.isEnabled = false;
	
	this.init = function()
	{
		map.events.register("moveend", map, this.requestMarker);
		map.events.register("zoomend", map, this.requestMarker);
		
		this.camMarkers = new OpenLayers.Layer.Markers("CameraMarkers");
		map.addLayer(this.camMarkers);
		
		this.detailWin = HaritaWindows.create("CameraDetails");
		this.detailWin.setAutoSize(false);
		//this.detailWin.setAutoMargin(25);
		
		this.detailWin.setHeight(500);
		this.detailWin.setWidth(720);
		
		this.detailWin.center();
		
		//this.isEnabled = true;
		this.requestMarker();
	}
	
	this.requestMarker = function()
	{
		if(!HaritaCameras.isEnabled)
		{
			return;
		}
		if(map.getZoom() < 16)
		{
			HaritaCameras.camMarkers.clearMarkers();
			return;
		}
		
		var bounds = getCurrentMapExtent();
		//var center = bounds.getCenterLonLat();
		
		var request =
		{
			"bound_lat_min": bounds.bottom,
			"bound_lat_max": bounds.top,
			
			"bound_lon_min": bounds.left,
			"bound_lon_max": bounds.right
		};
		
		HaritaCameras.lastRequest = request;
	
		$.getJSON(Sensus.urlMake("data/cameras"), request, HaritaCameras.updateMarker);
	}
	
	this.updateMarker = function(argData)
	{
		if(!HaritaCameras.isEnabled)
		{
			return;
		}
		
		HaritaCameras.camMarkers.clearMarkers();
		
		if(argData)
		{
			HaritaCameras.lastResult = argData;
		}
		else
		{
			argData = HaritaCameras.lastResult;
		}
		
		for(var enKey in argData)
		{
		
			var item = argData[enKey];
			var iconUrl = item["url"] + "&width=32";
			
			var markerText = "<div class=\"camMarker\" onclick=\"HaritaCameras.showDetails(" + item.longitude + "," + item.latitude + ");return(false);\"><img src=\"" + iconUrl + "\" /></div>";
			var lonlat = new OpenLayers.LonLat(parseFloat(item.longitude), parseFloat(item.latitude));
			lonlat = lonlat.transform(map.displayProjection, map.projection);
			var icon = new TwoPoints.TextIcon(markerText, {});
			var marker = new OpenLayers.Marker(lonlat, icon);
			
			HaritaCameras.camMarkers.addMarker(marker);
			icon.offset = new OpenLayers.Pixel(-16, -12);
			icon.draw();
			
		}
		
	}
	
	this.showDetails = function(argLon, argLat)
	{
		if(!HaritaCameras.isEnabled)
		{
			return;
		}
		
		var request =
		{
			"detail_location": true,
			
			"bound_lat_min": argLat - .0000005,
			"bound_lat_max": argLat + .0000005,
			
			"bound_lon_min": argLon - .0000005,
			"bound_lon_max": argLon + .0000005
		};
		
		HaritaCameras.lastRequest = request;
		
		HaritaCameras.detailWin.hide();
		HaritaCameras.detailWin.center();
		this.detailWin.titleHtml(Sensus.tr("Camera-Views for Coordinate") + " " + argLon + " / " + argLat);
		
		$.getJSON(Sensus.urlMake("data/cameras"), request, HaritaCameras.updateDetails);
		
	}
	
	this.updateDetails = function(argData)
	{
		if(!HaritaCameras.isEnabled)
		{
			return;
		}
		
		var detailHtml = "";
		
		detailHtml = detailHtml + "<div style=\"text-align:right\"><a href=\"javascript:void(0)\" onclick=\"HaritaCameras.detailWin.hide(); return(false);\">" + Sensus.tr("Close") + "</a></div><table>";
		
		var n = 0;
		var tro = false;
		for(var enKey in argData)
		{
			
			var item = argData[enKey];
			var imageUrl = item["url"] + "&width=320";
			
			if(!item["camera"])
			{
				break;
			}
			
			if(n % 2 == 0) {detailHtml = detailHtml + "<tr>"; tro=true;}
			
			var detailHtml = detailHtml + "<td class=\"camDetailElm\"><img src=\"" + imageUrl + "\" /><div>Cam #" + item["camera"] + ", " +  item["date"] + "</div></td>";
			
			if(n % 2 == 1) {detailHtml = detailHtml + "</tr>"; tro=false;}
			
			n++;
			
		}
		if(tro) {detailHtml = detailHtml + "</tr>";}
		
		detailHtml = detailHtml + "</table>";
		
		HaritaCameras.detailWin.contentHtml(detailHtml);
		HaritaCameras.detailWin.show();
	
	}
	
	this.enable = function()
	{
		this.isEnabled = true;
		this.requestMarker();
	}
	
	this.disable = function()
	{
		this.isEnabled = false;
		HaritaCameras.camMarkers.clearMarkers();
	}
	
	this.toggle = function()
	{
		if(this.isEnabled) {this.disable();}
		else {this.enable();}
	}
	
	//return(this.init());
	
}

var searchLastId = 0;
var searchOffset = 0;
var adrsrcrid = 0; 

function onSearch (id, dir, find, rid, bid, cid, bbox) { 
	  if (typeof find == 'undefined' || find == null) find = '';
	  if (typeof rid == 'undefined'  || rid == null ) rid = '';
	  if (typeof cid == 'undefined'  || cid == null ) cid = 0;
	  if (typeof bid == 'undefined'  || bid == null ) bid = 0;
	  
	  setBoxState("progress");
	  $("poiResults").html("");
	  
	  if (dir != +1 && dir != -1) searchOffset = 0;

	  if (id == 0) id = searchLastId;
	  if (dir == +1 && hasNextSearch(id, searchOffset)) searchOffset = searchOffset + poiLimit;
	  if (dir == -1 && hasPrevSearch(id, searchOffset)) searchOffset = searchOffset - poiLimit;
	  
      var queryStr  = 'q='+find;
      
      $('#q_d').val(find);
      
      var paramCid = '';
      if (cid>0) paramCid = '&cid='+cid;

      var paramBid = '';
      if (bid>0) paramBid = '&bid='+bid;      
      
      var paramRid  = '';
      var paramBbox = '';
      if (rid!=''){
    	  paramRid = '&rid='+rid;
    	  paramBbox = "&bbox="
      } else{
    	  paramRid = '';
    	  paramBbox = '&bbox='+bbox;
      }
      
      var paramOffset = "&offset=" + searchOffset;
      
	  $.getJSON(Sensus.urlMake("data/search?"+queryStr + paramBbox + paramOffset + paramRid + paramCid + paramBid),
	  function(data) {
	    setBoxState("poiresults");
	    $('#poiRows').empty();
	    
	    if (data.success && data.numOfRows)
	    {
	      hariJson.pois = data;
	      poiCount = data.numOfRows;
	    }
	    else
	    {
	      hariJson.pois = [];
	      poiCount = 0;
	    }
	    
	    // show poi navi
	    $('#poiNaviPrev').empty();
	    $('#poiNaviNext').empty();
	    if (poiCount > 0) {
	        if (hasPrevSearch(id, searchOffset)) {
	            $('#poiNaviPrev').append('<input type="button" class="nextprev" value="&laquo; ' + Sensus.tr('prev') + ' &laquo;" onclick="onSearch(0,-1,\'' + find + '\',\'' + rid + '\',' + bid + ',' + cid + ',\'' + bbox + '\');" />');
	          } else {
	            $('#poiNaviPrev').empty();
	          }
	          if (hasNextSearch(id, searchOffset)) {
	            $('#poiNaviNext').append('<input type="button" class="nextprev" value="&raquo; ' + Sensus.tr('next') + ' &raquo;" onclick="onSearch(0,+1,\'' + find + '\',\'' + rid + '\',' + bid + ',' + cid + ',\'' + bbox + '\');" />');
	          } else {
	            $('#poiNaviNext').empty();
	          }	    	
	      $('#poiOptions').show();
	      showSearch(data);

	    } else {
	      $('#poiRows').empty();
	      $('#poiOptions').hide();      
	      $('#poiResults').text(Sensus.tr('Sorry, no pois found.'));

	    }
	  });
	  searchLastId = id;
	  return false;
}


//show poi result list for an overgiven json poi object
function showSearch(json) {
  toggleRegionPins('provinces', 0);

  var container = $('#poiResults');

  container.fadeOut('fast');
  container.empty().hide();
  container.append('<p/>'); // '+ data.numOfRows+' Results
  //$('#poiRows').html('<b>' + poiCount + '</b> ' + Sensus.tr("Pois"));
  $('#poiRows').html('<b>' + poiCount + '</b> ' + 'Sonuç');
  var i=0;  
  $.each(json.results,
  function(key, val) {
    var id = val.pid;
    var name = val.name;
    if (name.length > 32) name = name.substr(0, 32) + "...";
    
    //var editstr =  "<div style='float:right; display:inline;' onclick='editPoi("+id+");'>&nbsp;[edit]&nbsp;</div>"; 
    var editstr =  "<img src=\"" + Sensus.urlMake("images/edit.png") + "\" onclick='editPoi("+id+");' align=right>"; 
    
    if (!allowPoiEdit) editstr = "";

    var poino = searchOffset + key + 1;    
    var poinostr = "<span class='poinr' nostyle='display:inline;position:relative;top:-2px;'>&nbsp;" + (poino) + "&nbsp;</span>";
    val.no = poino;    
    var div = $("<div></div>").addClass('clickable').attr('id', 'poi-' + id).css('cursor', 'pointer').html("<div class='poi' style='float:left;'>" + poinostr + name + "</div>").click(function() {
      clickPoiResult(id)
    }).hover(
    function() {
      $(this).addClass('hover');
      hoverPoiResult(id, true);
    },
    function() {
      $(this).removeClass('hover');
      hoverPoiResult(id, false)
    });

    var router = $("<input type='checkbox' style='float:right;' class='poirouter' id='poirouter-"+id+"' onclick='chkPoiRouter("+id+")' />");
    
    container.append(div);
    container.append(editstr);
    //container.append(router);
    container.append($("<br clear=all />"));
  });
  //container.show();
  container.fadeIn('fast');
  showSearchInMap(json);

  // ie7 (and maybe ie8, but NOT ie6) needs a force repaint here, else its a game of luck whether poi results are shown
  forceRepaint();
  setTimeout(forceRepaint, 100);
}

// helper funcs for poi result list pager navigation
function hasNextSearch(id, offset) {
  if (offset + poiLimit < poiCount) return true;
  return false;
}

function hasPrevSearch(id, offset) {
  if (offset > 0) return true;
  return false;
}

function showSearchInMap(json) {

    marker_layer.clearMarkers();
    for (var i = 0; i < json.results.length; ++i) {
        
				var pointerUri = Sensus.urlMake("images/pointer.png");
				
        var val = json.results[i];

        // create marker
        var icon_url = Sensus.urlMake("/icons/" + val.cid + ".png");
        var number = searchOffset + i + 1;
				
        var text =
            "<div class=\"poimarker2\"> \
               <div align=\"center\" style=\"width:27px; height:27px;\" ><img src=\"" + icon_url + "\" /></div> \
               <div align=\"center\">" + number + "</div> \
             </div>\
             <div class=\"omx_marker_pointer\"></div>";
          
        var lonlat = new OpenLayers.LonLat(parseFloat(val.lon), parseFloat(val.lat));
        lonlat = lonlat.transform(map.displayProjection, map.projection);
        var icon = new TwoPoints.TextIcon(text, {});
        
        var marker = new OpenLayers.Marker(lonlat, icon);
        marker.poi = val;
        
        // register event listener
        //marker.events.register('mousedown', marker, function(evt) { markerMouseDown(this, evt); OpenLayers.Event.stop(evt); });
        
		// later you can specify two different behaviors: mouseover OR click (+ explicit click on close)        
		if (poiEventMode == "hover") {        
		        marker.events.register('mouseover', marker, function(evt) { markerMouseOver(this, evt); OpenLayers.Event.stop(evt); });
		        marker.events.register('mouseout', marker, function(evt) { markerMouseOut(this, evt); OpenLayers.Event.stop(evt); });
		}
		if (poiEventMode == "click") {        
		
		        marker.events.register('dblclick', marker, function(evt) { map.zoomTo(14); openMarkerTooltip(this, true); OpenLayers.Event.stop(evt); });
		
		        marker.events.register('click', marker, function(evt) { openMarkerTooltip(this, true); OpenLayers.Event.stop(evt); });
		        // in the poi overlay provide a click button for "CLOSE" with js-func  markerMouseOut(this, evt); 
		}        
        // add marker
        marker_layer.addMarker(marker);
        
        // update marker icon offset (icon size can de determined only after marker has been added)
        icon.offset = new OpenLayers.Pixel(0, -icon.imageDiv.offsetHeight);
        icon.imageDiv.style.zIndex = '1000';
        icon.draw();
        
        
    }
}

function ctxCreatePoi(e) {
	  var lon=lastGeo.lon;
	  var lat=lastGeo.lat;
	  $.getJSON(Sensus.urlMake("data/geo2adr/?lon="+lon+"&lat="+lat), function(json) {
	    if (json.success = false) { 
	      alert(Sensus.tr("no matching address found"));
	    } else {
	      var adr = json.address;
	      var str = "\n";
	      $.each(adr, function(key, val) {
	        str += Sensus.tr(key) + ": " + val + "<br/>\n";
	      });
	      //console.log(str);
	      //alert(str);
	      editPoi(0);
//			var geopoint = new OpenLayers.LonLat(lastGeo.lon, lastGeo.lat);
//			//geopoint = geopoint.transform(map.projection, map.displayProjection);
//			
//			var poptext = 'Longitude: ' + String.substr(geopoint.lon, 0, 11)
//					+ '<br />Latitude: ' + String.substr(geopoint.lat, 0, 10)
//					+ '<br />';
//			poptext = poptext + str;
//			
//			var displonlat = new OpenLayers.LonLat(geopoint.lon, geopoint.lat);
//			displonlat = geopoint.transform(map.displayProjection, map.projection);
//			
//			popup = new OpenLayers.Popup.Anchored("floatingmenu", displonlat, new OpenLayers.Size(200, 200),
//					"<div id='floatingmenuitem' style='font-size:12px;'>" + poptext + "</div>", null, true, null);
//			map.addPopup(popup, true);
	   
	      
	      /*
	{"address" : {"city" : "Özgürlük", "country" : "TÜRKIYE", "county" : "ALTINDAG", "houseNumber" : "181-1"
	, "state" : "ANKARA", "streetName" : "Isimsiz S", "zip" : "06080"}, "distance" : 1.00000000, "success"
	: true}
	*/
	    }
	  });	  
}


function geo2adr2(lon, lat) {

	$.getJSON(Sensus.urlMake("data/geo2adr/?lon=" + lon + "&lat=" + lat),
			function(json) {
				if (json.success = false) {
					alert(Sensus.tr("no matching address found"));
				} else {
					var adr = json.address;
					var str = "";
					$.each(adr, function(key, val) {
						str += Sensus.tr(key) + ": " + val + "\n";
					});
					alert(str);
				}
			});
}

function handleMapClick(evt) {
	var lonlat = map.getLonLatFromViewPortPx(new OpenLayers.Pixel(evt.xy.x,
			evt.xy.y));
	var geopoint = new OpenLayers.LonLat(lonlat.lon, lonlat.lat);
	geopoint = geopoint.transform(map.projection, map.displayProjection);

	var poptext = 'Longitude: ' + String.substr(geopoint.lon, 0, 11)
			+ '<br />Latitude: ' + String.substr(geopoint.lat, 0, 10)
			+ '<br />';
	poptext = poptext + '<a href="javascript:geo2adr2(' + geopoint.lon + ','
			+ geopoint.lat + ');">Adres Getir</a>';

	popup = new OpenLayers.Popup.Anchored("floatingmenu", map
			.getLonLatFromViewPortPx(evt.xy), new OpenLayers.Size(200, 100),
			"<div id='floatingmenuitem'>" + poptext + "</div>", null, true,
			null);
	map.addPopup(popup, true);
}

function setMrt(mrt) {
	if (!mrt || mrt == '' || mrt == 'rblall' || mrt == 'all,nore'
			|| mrt == 'ps') {
		d1('showss');
		d0('hidess');
		d0('so');
		getId('q_d').style.width = "100%";
		getId('mrtbox').disabled = true;
	} else {
		d0('showss');
		d1('hidess');
		d1('so');
		getId('q_d').style.width = "100%";
		getId('mrtbox').value = mrt;
		getId('mrtbox').disabled = false;
	}
	return false;
}

function d0(id) {
	getId(id).style.display = "none"
}

function d1(id) {
	getId(id).style.display = ""
}

function getId(id) {
	return document.getElementById(id)
}


function onSearchRoute (id, dir, find, cid) {
		if (typeof find == 'undefined' || find == null) find = '';
		if (typeof cid == 'undefined'  || cid == null ) cid = 0;
		if (route_layer.features.length == 0){
			alert ("Önce Rota belirleyiniz");
			return false;
		}			  
		setBoxState("progress");
		$("poiResults").html("");
		  
		if (dir != +1 && dir != -1) searchOffset = 0;
		if (dir == +1 && hasNextSearch(id, searchOffset)) searchOffset = searchOffset + poiLimit;
		if (dir == -1 && hasPrevSearch(id, searchOffset)) searchOffset = searchOffset - poiLimit;
		
		var paramCid = '';
		if (cid>0) paramCid = cid;
		  
		var queryStr  = find;      
		$('#q_d').val(find);

		var line=route_layer.features[0].geometry.clone().transform(epsg900913,epsg4326)
		var lineStr = line.toString();
		line.destroy;
		delete line;

		var lineBuffer = $('#sliderValue2h').val();
		var success = function(data) {
		    setBoxState("poiresults");
		    $('#poiRows').empty();
		    
		    if (data.success && data.numOfRows)
		    {
		      hariJson.pois = data;
		      poiCount = data.numOfRows;
		    }
		    else
		    {
		      hariJson.pois = [];
		      poiCount = 0;
		    }
		    
		    // show poi navi
		    $('#poiNaviPrev').empty();
		    $('#poiNaviNext').empty();
		    if (poiCount > 0) {
		        if (hasPrevSearch(id, searchOffset)) {
		            $('#poiNaviPrev').append('<input type="button" class="nextprev" value="&laquo; ' + Sensus.tr('prev') + ' &laquo;" onclick="onSearchRoute(0,-1,\'' + find + '\',\'' + cid + '\');" />');
		          } else {
		            $('#poiNaviPrev').empty();
		          }
		          if (hasNextSearch(id, searchOffset)) {
		            $('#poiNaviNext').append('<input type="button" class="nextprev" value="&raquo; ' + Sensus.tr('next') + ' &raquo;" onclick="onSearchRoute(0,+1,\'' + find + '\',\'' + cid + '\');" />');
		          } else {
		            $('#poiNaviNext').empty();
		          }	    	
		      $('#poiOptions').show();
		      showSearch(data);
		
		    } else {
		      $('#poiRows').empty();
		      $('#poiOptions').hide();      
		      $('#poiResults').text(Sensus.tr('Sorry, no pois found.'));
		
		    }
		}
		var errors = function(x,y,z) {   //Some sort of error
			setBoxState("normal");
			$('#routemsg').html(x.responseText);
		}
		var params = {
			'q'		    :find,
			'cid'	    :cid,
			'lineStr'   :lineStr,
			'lineBuffer':lineBuffer,
			'offset'    :searchOffset
		}
		
		var CallParams = {};
		CallParams.type = "POST";
		CallParams.url = "/data/searchRoute";
		CallParams.processData = true;
		CallParams.data = params;
		CallParams.dataType = "json";
		CallParams.success = success;
		CallParams.error = errors;
		$.ajax(CallParams);

		
		return false;
}



function onSearchPoint (id, dir, find, cid) {
	if (typeof find == 'undefined' || find == null) find = '';
	if (typeof cid == 'undefined'  || cid == null ) cid = 0;
	if (PointSearch.features.length == 0){
		alert ("Önce Arama Noktası belirleyiniz");
		return false;
	}
	setBoxState("progress");
	$("poiResults").html("");
	  
	if (dir != +1 && dir != -1) searchOffset = 0;
	if (dir == +1 && hasNextSearch(id, searchOffset)) searchOffset = searchOffset + poiLimit;
	if (dir == -1 && hasPrevSearch(id, searchOffset)) searchOffset = searchOffset - poiLimit;
	
	var paramCid = '';
	if (cid>0) paramCid = cid;
	  
	var queryStr  = find;      
	$('#q_d').val(find);

	var point = PointSearch.getFeatureBy('name','SearchPoint').geometry.clone().transform(epsg900913,epsg4326)
	if (!point){
		return false;
	}
	var pointStr = point.toString();
	point.destroy;
	delete point;

	var pointBuffer = $('#sliderPointValue2h').val();
	var success = function(data) {
	    setBoxState("poiresults");
	    $('#poiRows').empty();
	    
	    if (data.success && data.numOfRows)
	    {
	      hariJson.pois = data;
	      poiCount = data.numOfRows;
	    }
	    else
	    {
	      hariJson.pois = [];
	      poiCount = 0;
	    }
	    
	    // show poi navi
	    $('#poiNaviPrev').empty();
	    $('#poiNaviNext').empty();
	    if (poiCount > 0) {
	        if (hasPrevSearch(id, searchOffset)) {
	            $('#poiNaviPrev').append('<input type="button" class="nextprev" value="&laquo; ' + Sensus.tr('prev') + ' &laquo;" onclick="onSearchPoint(0,-1,\'' + find + '\',\'' + cid + '\');" />');
	          } else {
	            $('#poiNaviPrev').empty();
	          }
	          if (hasNextSearch(id, searchOffset)) {
	            $('#poiNaviNext').append('<input type="button" class="nextprev" value="&raquo; ' + Sensus.tr('next') + ' &raquo;" onclick="onSearchPoint(0,+1,\'' + find + '\',\'' + cid + '\');" />');
	          } else {
	            $('#poiNaviNext').empty();
	          }	    	
	      $('#poiOptions').show();
	      showSearch(data);
	
	    } else {
	      $('#poiRows').empty();
	      $('#poiOptions').hide();      
	      $('#poiResults').text(Sensus.tr('Sorry, no pois found.'));
	
	    }
	}
	var errors = function(x,y,z) {   //Some sort of error
		setBoxState("normal");
		$('#pointmsg').html(x.responseText);
	}
	var params = {
		'q'		    :find,
		'cid'	    :cid,
		'pointStr'  :pointStr,
		'pointBuffer':pointBuffer,
		'offset'    :searchOffset
	}
	
	var CallParams = {};
	CallParams.type = "POST";
	CallParams.url = "/data/searchPoint";
	CallParams.processData = true;
	CallParams.data = params;
	CallParams.dataType = "json";
	CallParams.success = success;
	CallParams.error = errors;
	$.ajax(CallParams);

	
	return false;
}

