
function get_request_object()
{
  try
  {
    if(window.ActiveXObject){
      httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
      httpRequest = new XMLHttpRequest();
    }
    return httpRequest;
  }
  catch(err)
  {
    var txt="get_request_object Error description: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
  }
}

function get_streets_for_city(city,street)
{
  try
  {
    httpRequest = get_request_object();
    var url = "resources/ajax.php?action=get_streets&city=" + city + "&street=" + street;
    httpRequest.open("GET", url, true);
    httpRequest.onreadystatechange = function () {fill_streets_dropdown_list(); } ;
    httpRequest.send(null);  
  }
  catch(err)
  {
    var txt="Error description get_streets_for_city: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
  }
}

function fill_streets_dropdown_list()
{
  try
  {
    if(httpRequest.readyState == 4)
    {
      if (httpRequest.status == 200)
      {
        
        var streets = JSON.parse(httpRequest.responseText);
        var select = document.getElementById('street_select');
        select.length = 0;
        
        for(var i=0;i < streets.length;i++)
        {
          var new_option = document.createElement('option');
          new_option.text = streets[i]['street'];
          new_option.value = streets[i]['street'];
  
          try {
            select.add(new_option, null); // standards compliant; doesn't work in IE
          }
          catch(ex) {
            select.add(new_option); // IE only
          }
        }
        
      }
    }
  }
  catch(err)
  {
    var txt="Error description refresh_bookmarks: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
  }
}

function reload_bookmarks(current_bookmark_id,section)
{
  try
  {
    //we push a item into the field every time this method is called
    BOOKMARKS_RELOAD_CALLS_POOL.push("reload_bookmarks");
    sleep(1);
    
    if(BOOKMARKS_RELOAD_CALLS_POOL.length > 0)
    {
      BOOKMARKS_RELOAD_CALLS_POOL = [];
      httpRequest = get_request_object();
      
      if(current_bookmark_id != '')      
        current_bookmark_id = '&property_id=' + current_bookmark_id;
      if(section != '')        
        section = '&section=' + section;      
      
      var url = "resources/ajax.php?action=reload_bookmarks" + current_bookmark_id + section;
      httpRequest.open("GET", url, true);      
      httpRequest.onreadystatechange = function () { refresh_bookmarks(); };
      httpRequest.send(null);  
    }    
  }
  catch(err)
  {
    var txt="Error description reload_bookmarks: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
  }
}

function refresh_bookmarks()
{
  try
  {
    if(httpRequest.readyState == 4)
    {
      if (httpRequest.status == 200)
      {
        var wrapper = document.getElementById('bookmark_wrapper');
        
        while (wrapper.hasChildNodes())
          wrapper.removeChild(wrapper.firstChild);

        var newdiv = document.createElement('div');
        newdiv.innerHTML = httpRequest.responseText;
        wrapper.appendChild(newdiv);                
      }
    }
  }
  catch(err)
  {
    var txt="Error description refresh_bookmarks: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
  }

}



function save_window_resize(width,height)
{
  try
  {
    httpRequest = get_request_object();
    var url = "resources/ajax.php?action=save_window_resize&width=" + width + "&height=" +height;
    httpRequest.open("GET", url, true);
    httpRequest.onreadystatechange = function () {} ;
    httpRequest.send(null);  
  }
  catch(err)
  {
    var txt="Error description save_resize: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
  }
}

function sleep(naptime){
  try
  {
    naptime = naptime * 1000;
    var sleeping = true;
    var now = new Date();
    var alarm;
    var startingMSeconds = now.getTime();
    while(sleeping){
       alarm = new Date();
       alarmMSeconds = alarm.getTime();
       if(alarmMSeconds - startingMSeconds > naptime)
        { sleeping = false; }
    }
  }
  catch(err)
  {
    var txt="Error description sleep: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
  }        
}


function lookup_address(address, put_marker)
{
  try
  {
  if (put_marker==null)
    put_marker=true;
    
    httpRequest = get_request_object();
    var url = "resources/ajax.php?action=lookup_address&address=" + address;
    httpRequest.open("GET", url, true);
    httpRequest.onreadystatechange = function () {refresh_map(put_marker); } ;
    httpRequest.send(null);  
  }
  catch(err)
  {
    var txt="Error description lookup_address: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
  }
}
function refresh_map(put_marker)
{
  try
  {
  if (put_marker==undefined)
    put_marker=true;
    
  if(httpRequest.readyState == 4)
  {
    
    coors = httpRequest.responseText.split(",",2);
    map.setCenter(new GLatLng(coors[1], coors[0]), 15, G_NORMAL_MAP);
  
    /*put marker if requested*/
    if (put_marker)
    {
      var point = new GLatLng(coors[1],coors[0]);
          
      var anIcon = new GIcon(G_DEFAULT_ICON);
      anIcon.image = ICON_URL;
      anIcon.iconSize = new GSize(31, 36);
      
      var marker = new GMarker(point, {draggable: true,icon: anIcon});
    
      marker.enableDragging();
      
      map.clearOverlays();
      map.addOverlay(marker);
    }
      
    /*update location fields if available*/
    var area1 = window.document.getElementById("location[1]");
    var area2 = window.document.getElementById("location[2]");
    
    
    if (area1!=undefined)
    {
      
      area1.value = coors[0];
      area2.value = coors[1];
      
      GEvent.addListener(marker, "dragend", function() {
        area1.value = marker.getLatLng().lng();
        area2.value = marker.getLatLng().lat();
      });
    }
    
      
    
  }
  }
  catch(err)
  {
    var txt="Refresh map,Error description: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
  }
}

function save_marker_state(id, htmlContent, action)
{
  try
  {
    var JSONObject = new Object;
    
    if(action == 'open')
    {
      JSONObject.state = 'opened';
      JSONObject.id = id;
      JSONObject.content = htmlContent;
      
    }
    else if(action == 'close')
    {
      JSONObject.state = 'closed';
      JSONObject.id = id;
    }
    
    JSONstring = JSON.stringify(JSONObject);
    
    var url = 'resources/ajax.php?action=save_marker_state&json='+JSONstring;
     
    httpRequest.open('GET', url, true);
    httpRequest.onreadystatechange = function () { change(); } ;
    httpRequest.send(null);
  }
  catch(err)
  {
    var txt="save marker state Error description: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
  }
}

function remove_outside_markers(ne_lat,ne_lng,sw_lat,sw_lng)
{
  try
  {
    var display_area_width = Math.abs(sw_lng-ne_lng);
    var display_area_height = Math.abs(sw_lat-ne_lat);
        
    var desired_loading_area_sw_lat = sw_lat - display_area_height * MARKER_LOAD_AREA_EXTENSION;
    var desired_loading_area_sw_lng = sw_lng - display_area_width * MARKER_LOAD_AREA_EXTENSION;
    var desired_loading_area_ne_lat = ne_lat + display_area_height * MARKER_LOAD_AREA_EXTENSION;
    var desired_loading_area_ne_lng = ne_lng + display_area_width * MARKER_LOAD_AREA_EXTENSION;
    
    not_deleted_markers = Array();
    while(!(CURRENT_MARKERS.length < 1))
    {
      cur_marker = CURRENT_MARKERS.pop();
      
      cur_lat = cur_marker.getLatLng().lat();
      cur_lng = cur_marker.getLatLng().lng();  
       
      if((cur_lng < desired_loading_area_sw_lng || cur_lng > desired_loading_area_ne_lng) || 
         (cur_lat < desired_loading_area_sw_lat || cur_lat > desired_loading_area_ne_lat))
         {
           map.removeOverlay(cur_marker);
         }
      else
      {
        not_deleted_markers.push(cur_marker); 
      }
    }
    CURRENT_MARKERS = not_deleted_markers;
  }
  catch(err)
  {
    var txt="remove markers,Error description: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
    
  }
  
}

function debug(mssg)
{
  try
  {
    if(DEBUG_MODE == true)
    {
      new_w = window.open("","Debuging window");
        
      new_w.document.write(mssg+"<br />");
    }
  }
  catch(err)
  {
    var txt="debug - Error description: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
    
  }
}

function save_map_state()
{
  
  try
  {
    debug("Taking item from REQUEST_POOL");
    var curent_bounds = REQUEST_POOL.shift();
    debug("REQUEST_POOL: "+REQUEST_POOL.length+" items left");
    
    if(curent_bounds == null)
    {
      REQUEST_IN_PROGRESS = false;
      debug("No calls in stack, REQUEST_IN_PROGRESS = false");
      debug("-------------------------------------");
      return;
    }
    REQUEST_IN_PROGRESS = true;
    debug("Starting request, REQUEST_IN_PROGRESS = true;");
    
    
      
    view_change = "drag";
    
    var httpRequest = get_request_object();
    //we dont do zoom event anymore so we just clear the overlays when the zoom is changed
    debug("save_map_state: get_request_object");
    
    //we dont do drag when on low zoom level
    //if we are in a low zoom level, we can see largeer part of the map
    if(map.getZoom() < DEFAULT_ZOOM_LEVEL && PREW_ZOOM_LVL < DEFAULT_ZOOM_LEVEL && view_change == "drag")
      //if we are zooming in do nothing
      //if(PREW_ZOOM_LVL < map.getZoom())
      {
        debug("-------------------------------------");
        save_map_state();
        return;
      }
    
    if(PREW_ZOOM_LVL != map.getZoom())
    {
      debug("closeInfoWindow");
      map.closeInfoWindow();
      
      if (map.getExtInfoWindow() != null) {
        map.closeExtInfoWindow();
      }
      
      debug("clearing all overlays");  
      map.clearOverlays();
    }
    
    debug("save_map_state: creating JSON");

    
    var JSONObject = new Object;
    JSONObject.zoom = map.getZoom();
    debug("save_map_state: map.getZoom()");
    
    JSONObject.prew_zoom = PREW_ZOOM_LVL;
    
    PREW_ZOOM_LVL = JSONObject.zoom;
    
    JSONObject.view_change = view_change;
    
    JSONObject.center = new Object;
    JSONObject.center.lat = map.getCenter().lat() ;
    JSONObject.center.lng = map.getCenter().lng() ;
    
    debug("save_map_state: got lat and long");
    
    var ne_lat = curent_bounds.getNorthEast().lat();
    var ne_lng = curent_bounds.getNorthEast().lng();
    var sw_lat = curent_bounds.getSouthWest().lat();
    var sw_lng = curent_bounds.getSouthWest().lng();
    
    JSONObject.north_east_corner = new Object;
    JSONObject.north_east_corner.lat = ne_lat;
    JSONObject.north_east_corner.lng = ne_lng;
    
    JSONObject.south_west_corner = new Object;
    JSONObject.south_west_corner.lat = sw_lat;
    JSONObject.south_west_corner.lng = sw_lng;
    
    debug("save_map_state: JSON.stringify");
    
    JSONstring = JSON.stringify(JSONObject);
  
    debug("starting request to server");
    var url = 'resources/ajax.php?action=save_map_state&json='+JSONstring;
    httpRequest.open('GET', url, true);
    httpRequest.onreadystatechange = function () { on_marker_array_recieve(ne_lat,ne_lng,sw_lat,sw_lng); } ;
        
    httpRequest.send(null);  
    
    if(document.getElementById("ajax_loader"))
      document.getElementById("ajax_loader").style.display='block';
  }
  catch(err)
  {
  
  debug("save_map_state exception:"+print_r(err));
    var txt="save map state,Error description: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    //alert(txt);
  }
      


}
function stripslashes(str) {
  try
  {
    if(str == null)
    {
      debug("toto je nula"+str);
      return "";
    }
    var pattern1 = /\\'/g;
    var pattern2 = /\\"/g;
    var pattern3 = /\\0/g;
    var pattern4 = /\\\\/g;
  
    str=str.replace(pattern1,'\'');
    str=str.replace(pattern2,'"');
    str=str.replace(pattern3,'\0');
    str=str.replace(pattern4,'\\');
    
    return str;
  }
  catch(err)
  {
    var txt="stripslashes - Error description: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
  }
}


function on_marker_array_recieve(ne_lat,ne_lng,sw_lat,sw_lng)
{
  try
  {
    if(httpRequest.readyState == 4)
    {
      if (httpRequest.status == 200)
      {                                       
        if(document.getElementById("ajax_loader"))
          document.getElementById("ajax_loader").style.display='none';
        
        debug("recieved server answer, removing outside markers");
        remove_outside_markers(ne_lat,ne_lng,sw_lat,sw_lng);
        
        var JSONObject = new Object;
        
        var markers = JSON.parse(httpRequest.responseText);
        counter = 0;
        
        debug("starting adding markers: "+markers.length);
        for(var i=0;i<markers.length;i++)
        {
          debug('striping slashes property '+markers[i]['title']);
          markers[i]['html'] = stripslashes(markers[i]['html']);
          debug("getting marker position");
          var point = new GLatLng(markers[i]['lat'],markers[i]['lon']);
          var marker = createMarker(point,markers[i]['title'],markers[i]['html'], 0,"");
          
          debug("marker object created, adding event");
          GEvent.addListener(marker, "click", function(){ save_marker_state(0,'',"open"); });
          GEvent.addListener(marker, "infowindowclose", function(){ save_marker_state(0,"","close"); });
          counter++;
          map.addOverlay(marker);
          
          debug("marker added to map ");
          CURRENT_MARKERS.push(marker);
          debug("marker added to current marker set ");
          
          
        }
        
        if(markers.length>0)
          debug("Request ended,"+markers.length+" markers added");
        else
          debug("Request ended,no markers added");
        debug("-------------------------------------");
        save_map_state();
        
      }
    }
  }
  catch(err)
  {
    var txt="on_marker_array_recieve Error description: " + err.description + "\n\n";
    txt+="Click OK to continue.\n\n";
    alert(txt);
  }

}

function change() {

}


function print_r(theObj,indent){
  var output='';
  if (indent == undefined) { indent = '    '; } else { indent += '    '; }
  if(theObj.constructor == Array || theObj.constructor == Object) {
  for(var p in theObj){
             if(theObj[p].constructor == Array|| theObj[p].constructor == Object){
               var type = (theObj[p].constructor == Array) ? "Array" : "Object";
               output += indent+'['+p+']('+type+")=>\n";
               output += print_r(theObj[p],indent);
             } else { output += indent+'['+p+']:'+theObj[p]+"\n"; }
          }
       }
       return output;
     }


