// 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: 8}, 
city:     {lon:0,lat:0,bbox:[0,0,0,0], zoom: 10}, 
district: {lon:0,lat:0, bbox:[0,0,0,0], zoom: 13}, 
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:[]
};

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

var allowPoiEdit = false;      
var lastCatId = 0;		
var poiLastId = 0;
var poiOffset = 0;
var poiLimit  = 15;
var poiCount  = 0;
var leftWidth = 310;
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);
 
  /*  
  Mosaic.removeMarker("ctxRoute1");  
  Mosaic.removeMarker("ctxRouteN");   
*/  
}

function removeRoutingFeatures(list) {

  $.each(list, function(i, item) {
    if (typeof item != "undefined") {
    //if (typeof item.name != "undefined") {
      try { Mosaic.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("marker1.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 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.icon) imgStr = '<img src="'+ Sensus.urlMake('images/'+item.icon+'.png') +'" />';
      ulObj.append('<li id="'+item.id+'">'+imgStr+' '+Sensus.tr(item.label)+' </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');
	Mosaic.setMapCenter(ValueKeeper.lon_base, ValueKeeper.lat_base, ValueKeeper.zoom_base);
}

function slideAuto(boxFeatureName) { // jquery object
  $.each(boxFeatureNames, function(i,val) {
    $('#box_'+val+'_content').slideUp(200);
  });
  $('#box_'+boxFeatureName+'_content').slideToggle(200);
}

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 {          
            Mosaic.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();

  //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":false } );
  
  addContextMenuItem(  {"id": "ctxRouteTo", "label": "route to",  "handler": function(e) { ctxRouteTo(e); }, "icon":"flag-red", "enabled":false } );
  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": "ctxGeo2Adr", "label": "get address",  "handler": function(e) { geo2adr(e); }, "icon":"user-identity" } );

  // 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":"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" } );

  // 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].zoom) {
    setMapCenter(parseFloat(hariGeo[region].lon), parseFloat(hariGeo[region].lat), hariGeo[region].zoom);  
  } else {
    setMapCenter(parseFloat(hariGeo[region].lon), parseFloat(hariGeo[region].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);
    $('#leftcontent').show();
  } else {
    resizeLeft(0); 
    $('#leftcontent').hide();
  }
  //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();
  markers.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 } ];
  
  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 addLocationMarkers(json) { //  20, 34, -10, -34);
  $.each(json, function(i,item) {
    var icon = Sensus.urlMake("images/"+item.icon);
    Mosaic.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");
      Mosaic.addImageMarker("rid_"+rid, icon, lon, lat, 64, 80); //, 35, 43);
      //
      marker = MosaicInternal.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);
        Mosaic.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 removeRegionPins(region) {
  region = "provinces";

  $.each(hariJson[region], function(i,item) {
    Mosaic.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 setStartFlagToGeo(icon, lon, lat, mode) {
  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 = "marker1";

  Mosaic.removeMarker   ("marker1");    
  addLocationMarkers([{"name":"marker1","icon":icon, "lon":lon,"lat":lat}]);
  

  //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;
  
  Mosaic.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 = "marker2";

  Mosaic.removeMarker   ("marker2"); 
  addLocationMarkers([{"name":"marker2","icon":icon, "lon":lon,"lat":lat}]);
  
  //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);
  } else {
    alert(Sensus.tr("routing impossible as endpoints are not defined"));
  }
}

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

removeRoutingFeatures(routvias);    
routvias = [];
  
  try {
    clearLine();
    Mosaic.removeMarker("marker1");
    Mosaic.removeMarker("marker2");
    
    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(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 = Mosaic.setMapExtent(og[0], og[1], og[2], og[3]);                      
  //if (zoomTo) map.zoomToExtent(extent);
}

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

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 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) {
    var adr = loc.location.address;      
    str += '<br/><input type="radio" onchange="var geos=adr2geoGetAndMarkSelectedGeos();" name="adr2geosel'+nr+'" value="'+i+'"';
    if (i==0) str += ' checked="checked" ';
    str += '>';  
    var zoom = hariGeo.province.zoom;
    if (typeof adr['city'] != 'undefined') zoom = hariGeo.city.zoom;
    if (typeof adr['streetName'] != 'undefined') zoom = hariGeo.district.zoom;
    str += ' <a href="javascript:setMapCenter('+loc.location.position.longitude+', '+loc.location.position.latitude+', '+zoom+');  ">'+Sensus.tr("center") +'</a> ';        
    $.each(subsets, function(j, detail) {          
      if (typeof adr[detail] != 'undefined') {
        str +=  Sensus.tr(detail)+": "+adr[detail]+"; "; // Sensus.tr(detail)+": "+
      }
    });
    i++;
  });
  return '<div class="small">'+str+'</div>';
}

function removeLocationMarkers() {
  try {
    Mosaic.removeMarker("adr2geomarker1");  
    Mosaic.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 pos = hariJson.adr2geo[(i-1)][0][val].location.position ;
      geos.push(pos);
      addLocationMarkers([{"name":"adr2geomarker"+i,"icon":"marker"+i+".png", "lon":pos.longitude,"lat":pos.latitude}]);    
    }
  } 
  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, street, zip, province2, city2, street2, zip2, state, state2) {  

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

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

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

  if ($.trim(province) == "" && $.trim(city) == "" && $.trim(street) == "" && $.trim(zip) == "" 
      || (isRouting && $.trim(province2) == "" && $.trim(city2) == "" && $.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+"&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+"&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 = "";
      $.each(adr, function(key, val) {
        str += Sensus.tr(key) + ": " + val + "\n";
      });
      alert(str);
      /*
{"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 initRegions() {

  $.getJSON(Sensus.urlMake("data/regions/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() {

      Mosaic.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")]);
			$.each(data, function(i, item) {
				ar.push([item.cid, 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),
    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),
    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.results', 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-edit?create=1&cid="+poiLastId));  
    startPoiPosEdit(0);
  }
}

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> ' + Sensus.tr("Pois"));
  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 leftContentHeight = getInnerHeight() -75;
  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();
  }
}

/////



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;
  }
  
  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;
    }
    
    var url = Sensus.urlMake('content/printboxexport?bbox=' + this.bbox[0] + "," + this.bbox[1] + "," + this.bbox[2] + "," + this.bbox[3] + '&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;
  }
  
  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 OpenLayers.Marker.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());
	
}
