  var map,mgr;
  var totalLocations = 0;
  var markers_array = new Array();
  var MapBounds = new GLatLngBounds();
  // ====== Array for decoding the failure codes ======
  var reasons=[];
  reasons[G_GEO_SUCCESS]            = "Success";
  reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
  reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
  reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
  reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
  reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
  reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
  reasons[403]                      = "Error 403: Probably an incorrect error caused by a bug in the handling of invalid JSON.";
  var listings = new Array(), type_filter = new Array(), clusters_neighborhood = new Array(), other_listings = new Array();
  var type_type = 0, venue_types_data, specialties_data;
  var gdir, directions_overlay, directions_locations, neighborhoods_data, listings_data;
  var directions_status = false;
  var default_center = new GLatLng(37.09024, -95.712891);
  var cluster_level = "neighborhood";
  var defalut_search_value = "Enter gallery name, venue type, specialty, etc.";
  var defalut_date_value = "mm/dd/yy";
  var current_neighborhood, current_neighborhood_zoom_level, neighborhood_zoomhandler = false;
  var current_sort_type = "n";
  var is_calendar_search = false;
  var map_filter_preselected = new Array(1,3,7);
  var map_speciality_preselected = new Array(3,8,9);
  var defalut_search_event = "by keyword, gallery name or artist";
  var open_window=null;
  var start_move=null;
  var on_marker_level = false;

  function onloadInit(){
    $("#search_input").val(defalut_search_value).toggleClass("grey_text");
    $("#calendar_canvas").hide();
    $("#search_input").focus(function() {
      if( this.value == defalut_search_value ) {
        $(this).toggleClass("grey_text");
        this.value = "";
      }
    }).blur(function() {
      if( !this.value.length ) {
        $(this).toggleClass("grey_text");
        this.value = defalut_search_value;
      }
    });
    $(function() {
      $("#gdate_val").datepicker({
        firstDay: 1,
        onSelect: function(dateText, inst){
          $(":radio[name=gdate]").eq(1).attr('checked','checked');
          doMap();
        }
      });
    });
    $("#gdate_val").focus(function() {
      if( this.value == defalut_date_value ) {
        $(this).toggleClass("grey_text");
        this.value = "";
      }
    }).blur(function() {
      if( !this.value.length ) {
        $(this).toggleClass("grey_text");
        this.value = defalut_date_value;
      }
    });
    $("#gdate_val").val(defalut_date_value).toggleClass("grey_text");
    $("#date_from").datepicker({
        onSelect: function(dateText, inst){
          doCalendar();
        }
      }
    ).datepicker("setDate", "+0d");
    $("#date_to").datepicker({
        onSelect: function(dateText, inst){
          doCalendar();
        }
      }
    ).datepicker("setDate", "+7d");
    $("#search_by_calendar_div").hide();
    $('.rounded').corners();
    //$('#action_tabs').tabs({ disabled: [1] });
    $('#action_tabs').tabs();
    $('#action_tabs').bind('tabsshow', function(event, ui) {
      if(ui.panel.id == "tabs-calendar") {
        $("#leftc").css("width","315px");
        $("#rightc").css("width","580px");
        $("#results_block").hide();
        $("#map_canvas").hide();
        $("#map_ad").hide();
        $("a.button:eq(2)").click();
        $("#calendar_canvas").css("height","450px");
        $("#calendar_canvas").show();
        $("#search_by_calendar_div").show();
        if(!is_calendar_search){
          doCalendar();
        }
      } else {
        $("#leftc").css("width","400px");
        $("#rightc").css("width","495px");
        $("#calendar_canvas").hide();
        $("a.button:eq(0)").click();
        $("#results_block").show();
        $("#map_canvas").show();
        $("#map_ad").show();
        doMap();
      }
    });
    $("#street_view").dialog({
      autoOpen: false,
      bgiframe: true,
      height: 400,
      width: 410,
      modal: true,
      resizable: false,
      buttons: {
        Cancel: function() {
          $(this).dialog('close');
        }
      }
    });
    $("a.button").click(
      function () {
        $("div.filter_container").hide();
        $($(this).attr("href")).show();
        resizeResultsList();
        $("a.button").removeClass("button_act");
        $(this).toggleClass("button_act").find("span:first").toggleClass("ui-icon-circle-triangle-e").toggleClass("ui-icon-circle-triangle-s").find("span:last").html("Hide Filter");
      }
    );
    $("div.filter_container").hide();
    $("a.filter").toggle(
      function () {
        $(this).parent().find("div.filter_content").fadeOut(500,resizeResultsList);
        $(this).find("span:first").toggleClass("ui-icon-circle-triangle-e").toggleClass("ui-icon-circle-triangle-s").find("span:last").html("Show Filter");
      },
      function () {
        $(this).parent().find("div.filter_content").fadeIn(500);
        resizeResultsList();
        $(this).find("span:first").toggleClass("ui-icon-circle-triangle-e").toggleClass("ui-icon-circle-triangle-s").find("span:last").html("Hide Filter");
      }
    );
    $("a.button:first").click();
    $("#search_event").val(defalut_search_event).toggleClass("defaultView");
    $("#search_event").focus(function() {
      if( this.value == defalut_search_event ) {
        this.value = "";
        $(this).toggleClass("defaultView");
      }
    }).blur(function() {
      if( !this.value.length ) {
        this.value = defalut_search_event;
        $(this).toggleClass("defaultView");
      }
    });
    resizeResultsList();
    $("#main").css("visibility","visible");
    initialize();
  }

  function resizeResultsList(){
    $("#results_list").height(560-$("#action_tabs").height());
  }

  function initTypeFilter(){
    type_filter = new Array();
    switch(type_type){
      case 1:
        var totalt = $(specialties_data).find("specialty").length;
        var lc = "", rc = "", counter = 0;
        $(specialties_data).find("specialty").each(function(){
          type_filter.push($(this).attr("id"));
          var selected = "";
          for(var i=0;i<map_speciality_preselected.length;i++){
            if(parseInt($(this).attr("id"))==map_speciality_preselected[i]){
              selected = " checked='true'";
            }
          }
          if(counter<Math.ceil(totalt/2)){
            lc += "<tr><td><input type='checkbox'"+selected+" id='etypes"+$(this).attr("id")+"' onclick='doMap(this)'></td><td>"+$(this).attr("name")+"</td></tr>";
          } else {
            rc += "<tr><td><input type='checkbox'"+selected+" id='etypes"+$(this).attr("id")+"' onclick='doMap(this)'></td><td>"+$(this).attr("name")+"</td></tr>";
          }
          counter++;
        });
        var content = "<div style='width:50%;float:left'><table>"+lc+"</table></div>"+
                      "<div style='width:50%;float:left'><table>"+rc+"</table></div>"+
                      "<div style='float:none;clear:both'></div>";
        $("#filter_speciality_types").html(content);
      break;
      default:
        var content = "";
        $("type",venue_types_data).each(function(){
          type_filter.push($(this).attr("id"));
          var selected = "";
          for(var i=0;i<map_filter_preselected.length;i++){
            if(parseInt($(this).attr("id"))==map_filter_preselected[i]){
              selected = " checked='true'";
            }
          }
          content += "<li><nobr><input type='checkbox'"+selected+" id='vtypes"+$(this).attr("id")+"' onclick='doMap(this)'> "+$(this).attr("name")+"</nobr></li>";
        });
        $("#filter_venue_types").html("<ul>"+content+"</ul>");
      break;
    }
    resizeResultsList();
  }

  function doLoading(state){
    if(state){
      $("#results_list").html("<div style='padding:10px;'><div style='float:left'><img src='img/ajax-loader.gif' width='28' height='28' align='left' style='margin-right:5px;'></div><div style='float:left;padding-top:6px;'>Loading. Please, wait...</div><div id='progressbar' style='margin-top:38px'></div></div>");
    } else {
    }
  }

  function initialize() {
    if(GBrowserIsCompatible()) {
      map = new GMap2(document.getElementById("map_canvas"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(default_center, 3);
      map.addControl(new MoreControl());
      mgr = new MarkerManager(map);
      gdir = new GDirections();
      GEvent.addListener(gdir, "error", handleErrors);
      GEvent.addListener(gdir, "load", function(){ 
        var poly = gdir.getPolyline();
        if(directions_overlay){
          map.removeOverlay(directions_overlay);
        }
        directions_overlay = poly;
        map.addOverlay(poly);
        customPanel(map,"map",gdir,document.getElementById("directions"));
      });
      GEvent.addListener(map, "zoomend", function(oldLevel,newLevel){ 
        if(neighborhood_zoomhandler && current_neighborhood && (newLevel<current_neighborhood_zoom_level)){
          //console.log("openNeighborhood on zoomend");
          //openNeighborhood(current_neighborhood,true);
        }
      });
      

      GEvent.addListener(map, "movestart", function(){ 
      start_move = true;
      });
     GEvent.addListener(map, "moveend", function(){ 
       start_move = false;	
       if(map.getZoom()>=14)
       {
       		on_marker_level = true;
        	var temp_bounds = map.getBounds();
        	var top_lat = temp_bounds.getNorthEast().lat();
        	var bottom_lat = temp_bounds.getSouthWest().lat();
        	var right_lng = temp_bounds.getNorthEast().lng();
        	var left_lng = temp_bounds.getSouthWest().lng();
       		markers_array = getAllMarkersInArea(top_lat,bottom_lat,right_lng, left_lng);
       }
       else if(on_marker_level)
       {
       		on_marker_level=false;
       		current_neighborhood = null;
       		switchToNeighborhood();
       }
     });            
      
      loadSettings();
    }
    $("#directions").hide();
    $("#main").css("visibility","visible");
  }

  function loadSettings(){
    $.ajax({
      type: "GET",
      url: "data.php",
      dataType: "xml",
      success: outputSettings
    });
  }

  function outputSettings(xd){
    venue_types_data = $("venue_types",xd);
    specialties_data = $("specialties",xd);
    $("#c_event_types").find("option").remove();
    $("#c_event_types").append("<option value=''>- all -</option>");
    $("event_types",xd).find("type").each(function(){
      $("#c_event_types").append("<option value='"+$(this).attr("id")+"'>"+$(this).attr("name")+"</option>");
    });
    $("#c_venue_types").find("option").remove();
    $("#c_venue_types").append("<option value=''>- all -</option>");
    $("venue_types",xd).find("type").each(function(){
      $("#c_venue_types").append("<option value='"+$(this).attr("id")+"'>"+$(this).attr("name")+"</option>");
    });
    $("#c_neighs").find("option").remove();
    $("#c_neighs").append("<option value=''>- all -</option>");
    $("neighborhoods",xd).find("neighborhood").each(function(){
      $("#c_neighs").append("<option value='"+$(this).attr("id")+"'>"+$(this).attr("name")+"</option>");
    });
    initTypeFilter();
    doMap();
  }

  function listingClass(src_xml){
    this.id = $(src_xml).attr("id");
    this.title = $(src_xml).attr("title");
    this.neighborhood = $(src_xml).attr("n");
    this.address = $(src_xml).attr("address");
    this.lat = parseFloat($(src_xml).attr("lat"));
    this.lng = parseFloat($(src_xml).attr("lng"));
    this.phone = $(src_xml).attr("phone");
    this.url = $(src_xml).attr("url");
    this.hours = $(src_xml).attr("hours");
    this.description = $(src_xml).attr("description");
    this.type = $(src_xml).attr("type");
  }

  function trim(string){
    return string.replace(/(^\s+)|(\s+$)/g, "");
  }

  function showDirInput(id,state,lat,lng){
    if(state){
      $("#dir_"+id).html("<h4>Start adress:<br><input type='text' id='dir_start_"+id+"' style='width:150px;'> <a href='javascript:void(0)' onclick='getStartAddress("+id+",\""+lat+"\",\""+lng+"\")'>GO</a></h4>");
    } else {
      $("#dir_"+id).html("<h4><a href='javascript:void(0)' onclick='showDirInput("+id+",true,\""+lat+"\",\""+lng+"\")'>Get Directions</a></h4>");
    }
  }

  function getStartAddress(id,lat,lng){
    setDirections($("#dir_start_"+id).val(),lat+","+lng);
  }

  function focusLocation(mid,type,zoom){
    if(type=="neighborhood"){
      var listing = getListing(mid);
      var neighborhood = getNeighborhoodData(listing.neighborhood);
      var point = new GLatLng(parseFloat(neighborhood.attr("lat")),parseFloat(neighborhood.attr("lng")));
      var current_marker = getMarkerObj(listing.neighborhood,type);
      current_marker.openInfoWindowTabsHtml(createLocationDescription(listing));
    } else {
      var current_marker = getMarkerObj(mid,type);
      openLocationTabs(current_marker);
      var point = current_marker.getPoint();
    }
    if(zoom){
      map.setCenter(point,zoom);
    } else {
      map.setCenter(point);
    }
  }

  function openLocationTabs(marker){
    marker.openInfoWindowTabsHtml([new GInfoWindowTab("Info", createLocationDescription(marker.location)),new GInfoWindowTab("calendar", "<div class='location-events' id='le_"+marker.id+"' style='width:290px;height:180px;overflow:auto;'><h4>Loading...</h4></div>")], {maxWidth: 300});
  }

  function focusLocationOnly(mid){
    var listing;
    for(var i=0;i<clusters_neighborhood.length;i++){
      for(var j=0;j<clusters_neighborhood[i].length;j++){
        if(clusters_neighborhood[i][j].id==mid){
          listing = clusters_neighborhood[i][j];
          break;
        }
      }
    }
    if(!listing){
      for(var i=0;i<other_listings.length;i++){
        if(other_listings[i].id==mid){
          listing = other_listings[i];
          break;
        }
      }
    }
    if(listing){
      clearMap();
      var point = new GLatLng(listing.lat,listing.lng);
      map.setCenter(point,15);
      var marker = new createLocationMarker(point, listing);
      if(!markers_array)markers_array=new Array();
      markers_array.push(marker);
      map.addOverlay(marker);
      openLocationTabs(marker);
      //marker.openInfoWindowTabsHtml([new GInfoWindowTab("Info", createLocationDescription(current_marker.location)),new GInfoWindowTab("calendar", createLocationCalendar(current_marker.id))]);
    }
  }

  function getMarkerObj(id,type){
    for(var i=0;i<markers_array.length;i++){
      if(markers_array[i].id==id && markers_array[i].type==type){
        return markers_array[i];
        break;
      }
    } 
    return null;
  }

  var panoClient = new GStreetviewClient();
  function createLocationDescription(location){
    var neighborhood = getNeighborhoodData(location.neighborhood)
    var myHtml = "<div class='location-item'>";
                 myHtml += "  <h2>"+location.title+"</h2>";
                 if(location.neighborhood){
                   myHtml += "<h4>"+neighborhood.attr("name")+"</h4>";
                 }
                 myHtml += "<h4>"+location.address+"</h4>";
                 if(location.phone){
                   myHtml += "<h4>"+location.phone+"</h4>";
                 }
                 if(location.url){
                   myHtml += "<h4><a href='"+location.url+"' target='_blank'>"+location.url+"</a></h4>";
                 }
                 if(location.type){
                   myHtml += "<h4>"+location.type+"</h4>";
                 }
                 if(location.hours){
                   myHtml += "<h4>Working hours: "+location.hours+"</h4>";
                 }
                 if(location.description){
                   myHtml += "<h4>"+location.description+"</h4>";
                 }
        myHtml += "  <br><h4><a href='javascript:void(0)' onclick='showStreetView(\""+location.lat+"\",\""+location.lng+"\")'>Street View</a></h4>";
//                 "  <div id='dir_"+location.id+"'><br><br></div>";
    myHtml +=    "</div>";
    return myHtml;
  }

  function createLocationCalendar(id){
    var myHtml = "<div class='location-events' id='le_"+id+"' style='width:290px;height:180px;overflow:auto;'><h4>Loading...</h4></div>";
    var url = "data.php?operation=location_events&id="+id;
    if($("input[name='gdate']:checked").val()==1 && $("#gdate_val").val()!=defalut_date_value){
      url+="&date="+$("#gdate_val").val();
    }
    $(document).queue("ajaxRequests", function() {
      $.ajax({
        type: "GET",
        url: url,
        dataType: "xml",
        success: function(result) {
          $(document).dequeue("myName");
          outputLocationEvents(result);
        }
      });
    });
    $(document).dequeue("ajaxRequests");
    return myHtml;
  }

  function outputLocationEvents(xd){
    var content = "<h4><span style='color:#909090'>No events found.</span></h4>", date = "";
    //console.log($("events",xd).find("event").length);
    var location_id = $("location",xd).attr("id");
    if($("events",xd).find("event").length>0){
      content = "<table>";
      $("events",xd).find("event").each(function(){
        var date_array = $(this).attr("date").split("-");
        var cdate = new Date();
        cdate.setDate(date_array[2]);cdate.setMonth(date_array[1]-1);cdate.setYear(date_array[0]);
        content += "<tr><td>";
        var img = "";
        if($(this).attr("image")!=""){
          img = "<img src='thumbs/_"+$(this).attr("image")+"' border='0' style='float:left;border:1px solid #1D5987;margin:5px 10px 0px 0px;'>";
        }
        if(img!=""){
          content += "<a href='thumbs/"+$(this).attr("image")+"' rel='prettyPhoto' title='"+$(this).attr("name")+"'>"+img+"</a>";
        }
        content += "<h2>"+$(this).attr("name")+"</h2>";
        var dates_str = "";
        var times = "";
        if($(this).attr("time")!=""){
          times = ", " + $(this).attr("time");
        }
        dates_str += "Opening reception "+cdate.format("F jS")+times;
        if($(this).attr("closing_date")){
          times = "";
          if($(this).attr("closing_time")!=""){
            times = ", " + $(this).attr("closing_time");
          }
          var closing_date_array = $(this).attr("closing_date").split("-");
          var closing_cdate = new Date();
          closing_cdate.setDate(closing_date_array[2]);closing_cdate.setMonth(closing_date_array[1]-1);closing_cdate.setYear(closing_date_array[0]);
          dates_str += "<br>Closes "+closing_cdate.format("F jS")+times;
        }
        content += "  <h4>"+dates_str+"</h4>";
        if($(this).attr("notes")!=""){
          content += "<h4 class='notes'>"+$(this).attr("notes")+"</h4>";
        }
        content += "</td></tr>";
      });
      content += "</table>";
    }
    $("div#le_"+location_id).html(content);
    $("a[rel^='prettyPhoto']").prettyPhoto();
  }

  function createLocationMarker(latlng, location) {
    var marker = new GMarker(latlng);
    marker.id = location.id;
    marker.latlng = latlng;
    marker.type = "listing";
    marker.location = location;
    GEvent.addListener(marker,"click", function() {
      openLocationTabs(marker);
    });
    GEvent.addListener(marker,"infowindowopen", function() {
      open_window = marker;
      showDirInput(marker.id,false,marker.latlng.lat(),marker.latlng.lng());
      createLocationCalendar(marker.id);
      $("a[rel^='prettyPhoto']").prettyPhoto();
    });
    GEvent.addListener(marker,"infowindowclose", function() {
    	if(start_move == false)open_window = null;
    });
    return marker;
  }

  function createNeighborhoodMarker(latlng, location) {
    var nltotal = 0;
    for(var i=0;i<clusters_neighborhood.length;i++){
      if(clusters_neighborhood[i][0].neighborhood==location.attr("id")){
        nltotal = clusters_neighborhood[i].length;
      }
    }
    var icon = new GIcon();
    icon.image = "marker.php?count="+nltotal;
    icon.shadow = "img/shadow-neighborhood.png";
    icon.iconSize = new GSize(25.0, 25.0);
    icon.shadowSize = new GSize(38.0, 25.0);
    icon.iconAnchor = new GPoint(12.0, 12.0);
    icon.infoWindowAnchor = new GPoint(12.0, 12.0);
    markerOptions = { icon:icon };
    var marker = new GMarker(latlng,markerOptions);
    marker.id = location.attr("id");
    marker.type = "neighborhood";
    marker.latlng = latlng;

    var myHtml = "<div class='location-item'>"+
                 "  <h2>"+location.attr("name")+"</h2>"+
                 "  <h4><a href='javascript:void(0)' onclick='openNeighborhood("+location.attr("id")+")'>View all ("+nltotal+")</a></h4>"+
                 "</div>";
    marker.infoTabs = [new GInfoWindowTab("Info", myHtml)];
    GEvent.addListener(marker,"click", function() {
      marker.openInfoWindowTabsHtml(marker.infoTabs, {maxWidth: 250});
    });
    GEvent.addListener(marker,"infowindowopen", function() {
      showDirInput(marker.id,false,marker.latlng.lat(),marker.latlng.lng());
    });
    return marker;
  }

  function createStartMarker(latlng) {
    var icon = new GIcon(G_DEFAULT_ICON);
    icon.image = "http://maps.google.com/mapfiles/dd-start.png";
    var marker = new GMarker(latlng,{ icon:icon });
    return marker;
  }

  function getStore(){
    switch($("#stores").val()){
      case "":
        return;
      break;
      case "all":
        outputLocation();
      break;
      default:
        focusLocation($("#stores").val(),16);
      break;
    }
  }

  function clearResults(){
    listings = new Array(), clusters_neighborhood = new Array(), other_listings = new Array();
    $("#total_found").html("");
    $("#results_list").html("");
  }

  function doMap(){
    if(!map) return;
    clearResults();
    clearMap();
    var urltypes = "";
    var ptype = "";
    var itype = "";
    if(type_type==1){
      ptype = "specialties";
      itype = "etypes";
    } else {
      ptype = "venue_types";
      itype = "vtypes";
    }
    for(var i=0;i<type_filter.length;i++){
      if($("input#"+itype+type_filter[i]).attr('checked')){
        if(urltypes!=""){
          urltypes+=",";
        }
        urltypes+=type_filter[i];
      }
    }
    doLoading(true);
    var dateurl = "";
    if($("input[name='gdate']:checked").val()==1 && $("#gdate_val").val()!=defalut_date_value){
      dateurl="&date="+$("#gdate_val").val();
    }
    $(document).queue("ajaxRequests", function() {
      $.ajax({
        type: "GET",
        url: "data.php?operation=map&"+ptype+"="+urltypes+dateurl,
        dataType: "xml",
        success: function(result) {
          $(document).dequeue("myName");
          outputLocations(result);
        }
      });
    });
    $(document).dequeue("ajaxRequests");
  }

  function doCalendar(){
    if(is_calendar_search){
      var url = "data.php?operation=calendar_search&q="+$("#search_event").val();
      if($("input#archived").attr("checked")){
        url+= "&archived=1";
      }
      is_calendar_search = false;
    } else {
      $("#calendar_canvas").html("<div style='padding:10px;'><div style='float:left'><img src='img/ajax-loader.gif' width='28' height='28' align='left' style='margin-right:5px;'></div><div style='float:left;padding-top:6px;'>Loading. Please, wait...</div><div id='progressbar' style='margin-top:38px'></div></div>");
      var url = "data.php?operation=calendar";
      if($("input#date_from").val() && $("input#date_from").val()!=""){
        url+= "&date_from="+$("input#date_from").val();
      }
      if($("input#date_to").val() && $("input#date_to").val()!=""){
        url+= "&date_to="+$("input#date_to").val();
      }
      if($("select#c_venue_types").val() && $("select#c_venue_types").val()!=""){
        url+= "&venue_type="+$("select#c_venue_types").val();
      }
      if($("select#c_neighs").val() && $("select#c_neighs").val()!=""){
        url+= "&neighborhood="+$("select#c_neighs").val();
      }
      if($("select#c_event_types").val() && $("select#c_event_types").val()!=""){
        url+= "&event_type="+$("select#c_event_types").val();
      }
      if($("input#c_event_ongoing").attr("checked")){
        url+= "&ongoing=1";
      }
      url+= "&sort_type="+$("select#c_sort_type").val();
    }
    $(document).queue("ajaxRequests", function() {
      $.ajax({
        type: "GET",
        url: url,
        dataType: "xml",
        success: function(result) {
          $(document).dequeue("myName");
          outputCalendar(result);
        }
      });
    });
    $(document).dequeue("ajaxRequests");
  }

  function outputCalendar(xd){
    var content = "<p style='margin:10px;padding:5px 0px 6px 0px;'><span style='color:#909090'>No listings found. Please, change search criteria and try again.</span></p>", date = "";
    if($("events",xd).find("event").length>0){
      content = "";
      $("events",xd).find("event").each(function(){
        var date_array = $(this).attr("date").split("-");
        var neighborhood = getNeighborhoodData($(this).attr("gallery_neighborhood"));
        var cdate = new Date();
        cdate.setDate(date_array[2]);cdate.setMonth(date_array[1]-1);cdate.setYear(date_array[0]);
        if($(this).attr("date")!=date){
          content += "<div style='padding:5px 5px 5px 10px;background-color:#5A5959;color:#ffffff;'>"+cdate.format("l F, jS")+"</div>";
          date = $(this).attr("date");
        }
        var img = "";
        if($(this).attr("image")!=""){
          if($(this).attr("image").substring(0,1)=='l')
          {
          	img = "<img src='map/thumbs/_"+$(this).attr("image")+"' border='0'>";
          }
          else
          {
          	img = "<img src='thumbs/_"+$(this).attr("image")+"' border='0'>";
          }
        }
        content += "<div class='calendar_event'>";
        if(img!=""){
          if($(this).attr("image").substring(0,1)=='l')
          {
            content += "<div style='float:left;width:75px;height:75px;border:1px solid #1D5987;margin:5px 10px 0px 0px;'><a href='map/thumbs/"+$(this).attr("image")+"' rel='prettyPhoto' title='"+$(this).attr("name")+"'>"+img+"</a></div>";          
          }
          else
          {
            content += "<div style='float:left;width:75px;height:75px;border:1px solid #1D5987;margin:5px 10px 0px 0px;'><a href='thumbs/"+$(this).attr("image")+"' rel='prettyPhoto' title='"+$(this).attr("name")+"'>"+img+"</a></div>";
          }
        }
        content += "<div style='float:left;'>"+
                   "  <h2>"+$(this).attr("name")+"</h2>"+
                   "  <h4>"+$(this).attr("gallery_name")+"</h4>"+
                   "  <h4>"+$(this).attr("gallery_address")+"</h4>";
        if(neighborhood){
          content += "  <h4 style='color:#7D0C00'>"+neighborhood.attr("name")+"</h4>";
        }
        var dates_str = "";
        var times = "";
        if($(this).attr("time")!=""){
          times = ", " + $(this).attr("time");
        }
        dates_str += "Opening reception "+cdate.format("F jS")+times;
        if($(this).attr("closing_date")){
          times = "";
          if($(this).attr("closing_time")!=""){
            times = ", " + $(this).attr("closing_time");
          }
          var closing_date_array = $(this).attr("closing_date").split("-");
          var closing_cdate = new Date();
          closing_cdate.setDate(closing_date_array[2]);closing_cdate.setMonth(closing_date_array[1]-1);closing_cdate.setYear(closing_date_array[0]);
          dates_str += "<br>Closes "+closing_cdate.format("F jS")+times;
        }
        content += "  <h3 style='margin-top:10px'>"+dates_str+"</h3>";
        content += "</div><div style='clear:both'></div>";
        if($(this).attr("notes")!=""){
          content += "<h4 class='notes'>"+$(this).attr("notes")+"</h4>";
        }
        content += "</div>"
      });
    }
    $("div#calendar_canvas").html(content);
    $("a[rel^='prettyPhoto']").prettyPhoto();
  }

  function doSearch(){
    clearResults();
    doLoading(true);
    $.ajax({
      type: "GET",
      url: "data.php?operation=search&search="+$("#search_input").val(),
      dataType: "xml",
      success: outputLocations
    });
  }

  function showStreetView(lat, lng){
    var point = new GLatLng(lat,lng);
    $("#street_view").dialog("open");
    var panoramaOptions = { latlng:point };
    var myPano = new GStreetviewPanorama(document.getElementById("street_view_div"), panoramaOptions);
  }

  function getListing(id){
    for(var i=0;i<clusters_neighborhood.length;i++){
      var cc = clusters_neighborhood[i];
      for(var j=0;j<cc.length;j++){
        if(cc[j].id==id){
          return cc[j];
          break;
        }
      }
    }
    return null;
  }

  function addToCLusters(listing){
    var ise = -1;
    for(var i=0;i<clusters_neighborhood.length;i++){
      var cc = clusters_neighborhood[i];
      for(var j=0;j<cc.length;j++){
        if(cc[j].neighborhood==listing.neighborhood){
          ise = i;
          break;
        }
      }
    }
    if(ise!=-1){
      clusters_neighborhood[ise].push(listing);
    } else {
      clusters_neighborhood.push(new Array(listing));
    }
  }

  function getNeighborhoodData(id){
    var result = null;
    $("neighborhood",neighborhoods_data).each(function(){
      if($(this).attr("id")==id){
        result = $(this);
      }
    });
    return result;
  }

  function clearMap(){
    map.clearOverlays();
    markers_array = new Array();
    mgr.clearMarkers();
    MapBounds = new GLatLngBounds();
  }

  function outputLocations(xd){
    //clearMap();
    clusters_neighborhood = new Array();
    totalLocations = $("location",xd).length;
    var content = "";
    var counter = 0;
    neighborhoods_data = $("neighborhoods",xd);
    listings_data = $("location",xd);
    var other_listings_content = "";
    $("#total_found").html(totalLocations+" results");
    if(totalLocations>0){
      var marker_count = 0;
      $("location",xd).each(function(){
        var listing = new listingClass($(this));
        if(cluster_level=="neighborhood" && listing.neighborhood!=""){
          addToCLusters(listing);
        } else {
          other_listings.push(listing);
        }
        counter++;
      });
      //content += showAsNeighborhoods();
      if($("#sort_type").val()=="n"){
        content += showAsNeighborhoods();
      } else {
        content += showAsListings();
      }
      showAllMarkers();
    } else {
      content += "<p style='margin:10px;padding:5px 0px 6px 0px;'><span style='color:#909090'>No listings found. Please, change search criteria and try again.</span></p>";
    }
    $("#results_list").html(content);
    doLoading(false);
  }

  function showAsNeighborhoods(){
    var content = "<ul class='neighborhood_list'>";
    $("neighborhood",neighborhoods_data).each(function(){
      var nltotal = -1;
      for(var i=0;i<clusters_neighborhood.length;i++){
        if(clusters_neighborhood[i][0].neighborhood==$(this).attr("id")){
          nltotal = clusters_neighborhood[i].length;
        }
      }
      if(nltotal>0){
        content += "<li id='n_"+$(this).attr("id")+"'><p><a href='javascript:void(0)' onclick='openNeighborhood("+$(this).attr("id")+")'>"+$(this).attr("name")+" ("+nltotal+")</a></p></li>";
      }
    });
    content += "</ul>";
    for(var i=0;i<other_listings.length;i++){
      var listing = other_listings[i];
      content += "<div class='location-item'>"+
                 "<a href='javascript:void(0)' onclick='focusLocation("+listing.id+",\"listing\")'>"+listing.title+"</a><br>"+
                 "<h4>"+listing.address+"</h4>";
                 if(listing.phone){
                   content += "<h4>"+listing.phone+"</h4>";
                 }
      content += "</div>";
    }
    return content;
  }

  function showAsListings(){
    var content = "";
    $(listings_data).each(function(){
      var listing = new listingClass($(this));
      content += "<div class='location-item'>"+
                 "<a href='javascript:void(0)' onclick='focusLocationOnly("+listing.id+")'>"+listing.title+"</a><br>"+
                 "<h4>"+listing.address+"</h4>";
                 if(listing.phone){
                   content += "<h4>"+listing.phone+"</h4>";
                 }
      content += "</div>";
    });
    return content;
  }

  function changeSortType(src_obj){
    if(src_obj.value=="n"){
      $("#results_list").html(showAsNeighborhoods());
    } else {
      $("#results_list").html(showAsListings());
    }
  }

  function showAllMarkers(noautozoom){
    clearMap();
    for(var i=0;i<clusters_neighborhood.length;i++){
      var cnid = clusters_neighborhood[i][0].neighborhood;
      var cc_data = getNeighborhoodData(cnid);
      if(cc_data && parseFloat(cc_data.attr("lat"))!=0){
        var point = new GLatLng(parseFloat(cc_data.attr("lat")),parseFloat(cc_data.attr("lng")));
        var marker = new createNeighborhoodMarker(point, cc_data);
        markers_array.push(marker);
        //mgr.addMarker(marker,0,17);
        MapBounds.extend(point);
      }
    }
    for(var i=0;i<other_listings.length;i++){
      var listing = other_listings[i];
      var point = new GLatLng(listing.lat,listing.lng);
      var marker = new createLocationMarker(point, listing);
      MapBounds.extend(point);
      markers_array.push(marker);
    }
    if(markers_array.length == 1)mgr.addMarker(markers_array[0],0,17);
    else mgr.addMarkers(markers_array,0,17);
    mgr.refresh();
    if(!noautozoom){
      zoomInArea(MapBounds,noautozoom);
    }
  }

  function zoomInArea(MapBounds){
    var zoom = map.getBoundsZoomLevel(MapBounds);
    map.setZoom(zoom);
    current_neighborhood_zoom_level = zoom;
    var clat = (MapBounds.getNorthEast().lat() + MapBounds.getSouthWest().lat()) / 2;
    var clng = (MapBounds.getNorthEast().lng() + MapBounds.getSouthWest().lng()) / 2;
    map.setCenter(new GLatLng(clat,clng));
    neighborhood_zoomhandler = true;
  }

  function openNeighborhood(nid,noautozoom){
    //console.log("openNeighborhood: "+nid+", "+noautozoom);
    neighborhood_zoomhandler = false;
    if(current_neighborhood){
      //console.log("current_neighborhood: "+current_neighborhood);
      $("ul.neighborhood_list li#n_"+current_neighborhood).find("p").removeClass("openNeighborhood");
      $("ul.neighborhood_list li#n_"+current_neighborhood).find("ul").remove();
      if(current_neighborhood==nid){
        current_neighborhood=null;
        showAllMarkers(noautozoom);
        var neighborhood = getNeighborhoodData(nid);
        map.setCenter(new GLatLng(parseFloat(neighborhood.attr("lat")),parseFloat(neighborhood.attr("lng"))));
        if($("#sort_type").val()!="a"){
          $("div.location-item").show();
        }
        return;
      }
    }
    var content = "";
    for(var i=0;i<clusters_neighborhood.length;i++){
      if(clusters_neighborhood[i][0].neighborhood==nid){
        current_neighborhood = nid;
        if($("#sort_type").val()!="a"){
          $("div.location-item").hide();
        }
        clearMap();
        for(var j=0;j<clusters_neighborhood[i].length;j++){
          var listing = clusters_neighborhood[i][j];
          var point = new GLatLng(listing.lat,listing.lng);
          var marker = new createLocationMarker(point, listing);
          MapBounds.extend(point);
          markers_array.push(marker);
          content += "<li>"+
                     "<a href='javascript:void(0)' onclick='focusLocation("+listing.id+",\"listing\")'>"+listing.title+"</a><br>"+
                     "<h4>"+listing.address+"</h4>";
                     if(listing.phone){
                       content += "<h4>"+listing.phone+"</h4>";
                     }
          content += "</li>";
        }
        $("ul.neighborhood_list li#n_"+nid).find("p").addClass("openNeighborhood");
        $("ul.neighborhood_list li#n_"+nid).append("<ul>"+content+"</ul>");
        if(markers_array.length == 1)mgr.addMarker(markers_array[0],0,17);
	else mgr.addMarkers(markers_array,0,17);
        mgr.refresh();
        zoomInArea(MapBounds);
        break;
      }
    }
    $("#results_list").scrollTo($("ul.neighborhood_list li#n_"+nid), 'medium');
  }

  function setDirections(from,to){
    if(directions_overlay){
      map.removeOverlay(directions_overlay);
      gdir.clear();
      $("#directions").html("");
    }
    directions_locations = "from: " + from + " to: " + to;
    //gdir.load(direction,{"locale":"en_US",getPolyline:true,getSteps:true});
    gdir.load(directions_locations,{getPolyline:true,getSteps:true});
  }

  function handleErrors(){
    var error = "";
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
      error = "No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code;
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
      error = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code;
    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
      error = "The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code;
    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
      error = "The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code;
    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
      error = "A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code;
    else error = "An unknown error occurred.";
    $("#directions").show();
    $("#directions").html("Driving directions error!<br>"+error);
  }

  function customPanel(map,mapname,dirn,div) {
    var html = "";
    function waypoint(point, type, address) {
      var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
    }
    function routeDistance(dist) {
      html += "<div style='padding-bottom:0.3em;'><span class='tipArial'><b>"+dist+"</b></span></div>";
    }      
    function detail(point, num, description, dist) {
      html += "<div class='directionItem' onclick='showDirectionDetails(new GLatLng("+point.toUrlValue(6)+"))'>"+description+" ("+dist+")</div>";
    }
    function copyright(text) {
      //html += '<div style="font-size: 0.86em;">' + text + "</div>";
    }
    for (var i=0; i<dirn.getNumRoutes(); i++) {
      if (i==0) {
        var type="play";
      } else {
        var type="pause";
      }
      var route = dirn.getRoute(i);
      var geocode = route.getStartGeocode();
      var point = route.getStep(0).getLatLng();
      waypoint(point, type, geocode.address);
      routeDistance(route.getDistance().html+" (about "+route.getDuration().html+")");
      for (var j=0; j<route.getNumSteps(); j++) {
        var step = route.getStep(j);
        if(j==0){
          var marker = new createStartMarker(step.getLatLng());
          map.addOverlay(marker);
        }
        detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html);
      }
    }
    var geocode = route.getEndGeocode();
    var point = route.getEndLatLng();
    waypoint(point, "stop", geocode.address);
    copyright(dirn.getCopyrightsHtml());
    div.innerHTML = html;
    $("#directions").show();
  }

  function MoreControl(){};
  MoreControl.prototype = new GControl();
  MoreControl.prototype.initialize = function(map) {
    var container = document.createElement("div");
    var savepos = document.createElement("div");
    savepos.id= "directions";
    savepos.title= "Show/Hide regions layers on the map";
    savepos.className= "directoins_div";
    container.appendChild(savepos);
    map.getContainer().appendChild(container);
    return container;
  }
  MoreControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 32));
  }

  function focusTo(obj_name){
    $("#"+obj_name).focus()
  }
  
function getAllMarkersInArea(top_lat, bottom_lat, right_lng, left_lng)
{
    var temp_markers_array = new Array();
    var open_lat=null;
    var open_lng=null;
    var open_id=null;
    if(open_window!=null)
    {
    	open_id=open_window.id;
    	open_lat=open_window.getLatLng().lat();
    	open_lng=open_window.getLatLng().lng();
    	open_window=null;
    }
    clearMap();
    
    var checkCoords = false;
    if(top_lat >= -90 && top_lat <= 90)checkCoords=true
    
    for(var i=0;i<clusters_neighborhood.length;i++){
        if($("#sort_type").val()!="a"){
          $("div.location-item").hide();
        }
        
        for(var j=0;j<clusters_neighborhood[i].length;j++){
          var listing = clusters_neighborhood[i][j];
          if(checkCoords && listing.lat<=top_lat && bottom_lat<=listing.lat && listing.lng <= right_lng && listing.lng >= left_lng)
          {
		  var point = new GLatLng(listing.lat,listing.lng);
		  var marker = new createLocationMarker(point, listing);
		  temp_markers_array.push(marker);
		  //if(open_lat==listing.lat && open_lng==listing.lng)var clickMarker = marker;
		  if(open_id==listing.id)var clickMarker = marker;
	   }

        }
    }   
    if(temp_markers_array.length >= 1)
    {
	markers_array = temp_markers_array;
	mgr.clearMarkers();
	if(temp_markers_array.length == 1)mgr.addMarker(markers_array[0],0,17);
	else mgr.addMarkers(markers_array,0,17);
	mgr.refresh();
	if(clickMarker!=null)GEvent.trigger(clickMarker, "click");
    }
}  
function switchToNeighborhood()
{
	showAllMarkers(true);
	//clearMap();
	//mgr.clearMarkers();
	//mgr.addMarkers(markers_array,0,17);
	//mgr.refresh();
}
