/*
 * Code inspired by Google Maps API Tutorial, Mike Williams 
 * @link http://econym.googlepages.com/
 */

var formIdCollection = ['residential', 'multi_family', 'farm_ranch', 'land', 'commercial'];
var typesWithYear = ['residential', 'commercial', 'multi_family'];

/*
 * Initialize variables used later on
 */
var map;
var i = 0;
var markerCollection = [];
var infoWindowHtmlCollection = [];
var coordinates = [];
var bounds;
var tooltip;
//var logDiv;
var propertiesCountElement;
var icon;
var autoPositionZoom = true;

var updateMapButton;
var updateMapLabel;

function bodyOnLoad() {
//-------------------------------------------------------------------
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GOverviewMapControl());
    map.addControl(new GMapTypeControl());
    map.enableDoubleClickZoom();
    
    var baseIcon = new GIcon();
    baseIcon.iconSize = new GSize(32, 32);
    baseIcon.shadowSize = new GSize(59, 32);
    baseIcon.iconAnchor = new GPoint(16, 0);
    baseIcon.infoWindowAnchor = new GPoint(13, 13);
    
    icon = new GIcon(baseIcon);
    icon.image = "http://www.sierravistarealestateaz.com/search/pix/map_house1.png";
    icon.shadow = "http://www.sierravistarealestateaz.com/search/pix/map_house1s.png";

    /*
     * We'll zoom the map later so that it includes all properties
     * Start on Sierra Vista
     */
    
    map.setCenter(new GLatLng(cities['Sierra Vista'][0], cities['Sierra Vista'][1]), cities['Sierra Vista'][2]);

    /*
     * Create tooltip DIV
     */
    tooltip = document.createElement("div");
    document.getElementById("map").appendChild(tooltip);
    tooltip.style.visibility = "hidden";

//    logDiv = document.getElementById('logDiv');
    propertiesCountElement = document.getElementById('propertiesCount');
    
    updateSearchForm();
    submitForm(true);
  }
}

function parseSearchResults(url) {
//-------------------------------------------------------------------
  var request = GXmlHttp.create();
  request.open("GET", url, true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var xmlDoc = request.responseXML;
      
      /* This is what we're working with
      <markers>
        <marker lat="43.65654" lng="-79.90138" label="Marker One">
         <infowindow><![CDATA[
           Some stuff to display in the<br>First Info Window
         ]]></infowindow>
        </marker>
      </markers>

      */

      // obtain the array of markers and loop through it
      var markers = xmlDoc.documentElement.getElementsByTagName("marker");
      // hide the info window, otherwise it still stays open where the removed marker used to be

      map.getInfoWindow().hide();
      map.clearOverlays();
      
      markerCollection = [];
      infoWindowHtmlCollection = [];
      coordinates = [];
      bounds = new GLatLngBounds();

      for (i = 0; i < markers.length; i++) {
        var lat = parseFloat(markers[i].getAttribute("lat"));
        var lng = parseFloat(markers[i].getAttribute("lng"));

        /*
         * If Google Maps gets two or more properties with the same coordinates it will display none of them
         * This makes sure that at least the first of them is displayed.
         */
        if (typeof coordinates[lat+','+lng] == 'undefined') {
          coordinates[lat+','+lng] = true;
          
          var point = new GLatLng(lat,lng);
          bounds.extend(point);  // this is for automatic zoom
          
  //        var infoWindowHtml = markers[i].getAttribute("infowindow");
          var infoWindowHtml = GXml.value(markers[i].getElementsByTagName("infowindow")[0]);
          var label = markers[i].getAttribute("label");
          var address = markers[i].getAttribute("address");
          var marker = createMarker(point,label,infoWindowHtml);
  
//          logDiv.innerHTML += "<br>" +i+": "+label+" ("+lat+","+lng+") "+address;
          
          map.addOverlay(marker);
        }
      }
      propertiesCountElement.innerHTML = 'Found ' + markers.length + ' properties.';

      /*
       * See if we're searching for properties in only one city
       */
      var criterionCity = selectValue('cityGmap');
      if ( (criterionCity != '') && (typeof(cities[criterionCity]) != 'undefined') ) {
        map.setCenter(new GLatLng(cities[criterionCity][0], cities[criterionCity][1]), cities[criterionCity][2]);
        
        autoPositionZoom = false;
      } else {
        autoPositionZoom = true;
      }
      
      /*
       * Zoom the map to show all properties
       */
      if (autoPositionZoom) {
        map.setZoom(map.getBoundsZoomLevel(bounds));
//        map.setZoom(map.getBoundsZoomLevel(bounds)-1);
        map.setCenter(bounds.getCenter());
      }
      
      /*
       * Enable the button again
       */
      updateMapButton.disabled = false;
      updateMapButton.value = updateMapLabel;
      
    }
  };
  request.send(null);
}

function submitForm(loadSavedValues) {
// ------------------------------------------------------------------
  /*
   * Disable the submit button
   */
  updateMapButton = document.getElementById('updateMap');
  updateMapLabel = updateMapButton.value;
  updateMapButton.value = 'Loading properties...';
  updateMapButton.disabled = true;
  
  /*
   * Load saved default values
   */
  var cookieCriteria;
  var formElement = document.getElementById('searchFormGmap');
  if (loadSavedValues) {
    cookieCriteria = getCookie('gmapValues');
    var criteriaValues = cookieCriteria.split('\|');

    if (criteriaValues.length > 0) {
      with (formElement) {
        for (var j=0; ((j < elements.length) && (typeof(criteriaValues[j]) != 'undefined') ); j++) {
          if (elements[j].tagName == 'SELECT') {
            elements[j].selectedIndex = criteriaValues[j];
          } else if (elements[j].type != 'hidden') {
            elements[j].value = criteriaValues[j];
          }
        }
      }
    }
    updateSearchForm();
  }
  
  /*
   * Build url for gmap-xml.php (returns properties matching the search criteria)
   */
  var url = location.protocol+'//'+location.host+'/search/gmap-xml.php?';
  var itemValue;
  var cookieValue;
  
  cookieCriteria = '';
  with (formElement) {
    for (var j=0; j < elements.length; j++) {
      if (elements[j].tagName == 'SELECT') {
        itemValue = elements[j].options[ elements[j].selectedIndex ].value;
        cookieValue = elements[j].selectedIndex;
      } else {
        itemValue = elements[j].value;
        cookieValue = elements[j].value;
      }
      url += elements[j].name + '=' + urlencode(itemValue) + '&';
      // build url parameters for gmap-xml.php call
      
      if (elements[j].type != 'hidden') {
        cookieCriteria += cookieValue+'|';
      }
      // save form values into a cookie
    }
  }
  setCookie('gmapValues', cookieCriteria);
//  prompt('url', url);
  /*
   * Fetch the properties
   */
  parseSearchResults(url);
}

/**
 * Returns the value that is selected in a html form item SELECT
 * @param id
 * @return string
 */
function selectValue(id) {
//-------------------------------------------------------------------
  var element = document.getElementById(id);
  if (!element) {
    return '';
  }
  return element.options[ element.selectedIndex ].value;
}
 
function in_array(needle, haystack) {
//-------------------------------------------------------------------
  for (var ii = 0; ii < haystack.length; ii++) {
    if (haystack[ii] == needle)
      return true;
  }
  return false;
}
 
function updateSearchForm() {
//-------------------------------------------------------------------
  /*
   * Display form items difined for selected property type
   */
  var selectedType = selectValue('propertyTypeGmap');
  var displayFormPart = selectedType;
  if ( (selectedType == 'residential') || (selectedType == 'rental_residential') ) {
    displayFormPart = 'residential';
  }
  if (selectedType == 'residential') {
    document.getElementById('residentialType').style.display = 'block';
    document.getElementById('rentalType').style.display = 'none';
  }
  if (selectedType == 'rental_residential') {
    document.getElementById('residentialType').style.display = 'none';
    document.getElementById('rentalType').style.display = 'block';
  }
  
  for (var j = 0; j < formIdCollection.length; j++) {
    var formPart = document.getElementById(formIdCollection[j]);
    if (formIdCollection[j] == displayFormPart) {
      formPart.style.display = 'block';
    } else {
      formPart.style.display = 'none';
    }
  }

  /*
   * Hide form items for Year Built <min> - <max>
   */
  var yearBuiltElement = document.getElementById('yearBuilt');
  if (in_array(selectedType, typesWithYear)) {
    yearBuiltElement.style.display = 'block';
  } else {
    yearBuiltElement.style.display = 'none';
  }
}

/**
 * Creates one property marker and saves it to our collection
 */
function createMarker(point, markerLabel, infoWindowHtml) {
// ------------------------------------------------------------------
  var marker = new GMarker(point, icon);
  marker.tooltip = '<div class="tooltip">'+markerLabel+'<\/div>'; //+i+': '
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml(infoWindowHtml);
  });
  GEvent.addListener(marker, "mouseover", function() {
    showTooltip(marker);
  });        
  GEvent.addListener(marker, "mouseout", function() {
    tooltip.style.visibility = "hidden";
  }); 
  
  markerCollection[i] = marker;
  infoWindowHtmlCollection[i] = infoWindowHtml;
  return marker;
}

/**
 * Update tooltip content and make it visible
 */
function showTooltip(marker) {
//-------------------------------------------------------------------
  tooltip.innerHTML = marker.tooltip;
  var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
  var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
  var anchor = marker.getIcon().iconAnchor;
  var width = marker.getIcon().iconSize.width;
  var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y)); 
  pos.apply(tooltip);
  tooltip.style.visibility = "visible";
}

function myclick(i) {
  markerCollection[i].openInfoWindowHtml(infoWindowHtmlCollection[i]);
}
function mymouseover(i) {
  showTooltip(markerCollection[i]);
}
function mymouseout() {
  tooltip.style.visibility = "hidden";
}

function urlencode( str ) {
//-------------------------------------------------------------------
  // http://kevin.vanzonneveld.net
  // +   original by: Philip Peterson
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +      input by: AJ
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   improved by: Brett Zamir
  // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
  // *     example 1: urlencode('Kevin van Zonneveld!');
  // *     returns 1: 'Kevin+van+Zonneveld%21'
  // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
  // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
  // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
  // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                           
  var histogram = {}, tmp_arr = [];
  var ret = str.toString();
  
  var replacer = function(search, replace, str) {
      var tmp_arr = [];
      tmp_arr = str.split(search);
      return tmp_arr.join(replace);
  };
  
  // The histogram is identical to the one in urldecode.
  histogram["'"]   = '%27';
  histogram['(']   = '%28';
  histogram[')']   = '%29';
  histogram['*']   = '%2A';
  histogram['~']   = '%7E';
  histogram['!']   = '%21';
  histogram['%20'] = '+';
  
  // Begin with encodeURIComponent, which most resembles PHP's encoding functions
  ret = encodeURIComponent(ret);
  
  for (search in histogram) {
      replace = histogram[search];
      ret = replacer(search, replace, ret); // Custom replace. No regexing
  }
  
  // Uppercase for full PHP compatibility
  return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
      return "%"+m2.toUpperCase();
  });
  
  return ret;
}

function setCookie(name, value, expire, path) {
// ------------------------------------------------------------------
  document.cookie = name + "=" + value +
    ((expire == null) ? "" : ("; expires=" + expire.toGMTString())) +
    ((path   == null) ? "" : ("; path=" + path));
}

function getCookie(name) {
// ------------------------------------------------------------------
  var search = name + "=";
  if (document.cookie.length > 0) {
  // if there are any cookies
    offset = document.cookie.indexOf(search);
    if (offset != -1) {
    // if cookie exists
      offset += search.length;
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1) {
        end = document.cookie.length;
      }
      return unescape(document.cookie.substring(offset, end));
    }
  }
  return '';
}
