
/**
 * The map object, null until script loads in.
 * @type {GMap2}
 */
var map = null;  

/**
 * The bounds of the markers once loaded in.
 * @type {GLatLngBounds}
 */
var bounds = null;

/**
 * The marker with currently opened info window.
 * @type {GMarker}
 */
var currentMarker = null;

/**
 * The dom element that the map is loaded into
 * @type {Element}
 */
var mapDiv = null;

/**
 * The dom element that everything is a child of.
 * @type {Element}
 */
var containerDiv = null;

/**
 * Position of mouse click (clientX) on map div when in static mode.
 * @type {Number}
 */
var clickedX = 0;

/**
 * Position of mouse click (clientY) on map div when in static mode.
 * @type {Number}
 */
var clickedY = 0;

/**
 * Indicates whether we've created a script tag with Maps API yet
 * @type {Boolean}
 */
var isLoaded = false;


      // this variable will collect the html which will eventually be placed in the side_bar
      var side_bar_html = "";
    
      // arrays to hold copies of the markers and html used by the side_bar
      // because the function closure trick doesnt work there
      var gmarkers = [];
      var i = 0;




/**
 * Called after script is asynchronously loaded in.
 * Creates the GMap2, GMarker objects and performs actions according to 
 * what the user did to trigger the map load (search, zoom, click etc).
 */
function loadMap() {
  if (GBrowserIsCompatible()) {
    mapDiv.style.background = '#fff';
    mapDiv.style.cursor = '';
    map = new GMap2(mapDiv, {logoPassive: true});
    bounds = new GLatLngBounds();
    for (var i = 0; i < businesses.length; i++) {
      bounds.extend(new GLatLng(businesses[i].lat, businesses[i].lng));
    }
    var latSpan = bounds.toSpan().lat();
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

    // The static map server gives markers more space when calculating
    // bounds and zoom level, so sometimes the API will give a higher
    // zoom level than was used by the static map server.
    // The .98 value is just a guess right now, may need tweaking.
    var newBounds = map.getBounds();
    var newLatSpan = newBounds.toSpan().lat();
    if (latSpan/newLatSpan > .90) { map.zoomOut(); }
if(map.getZoom()>20){map.zoomOut();map.zoomOut();map.zoomOut();map.zoomOut();map.zoomOut();map.zoomOut();}
    for (var i = 0; i < businesses.length; i++) {
      var marker = createMarker(i);
      var latlng = marker.getLatLng();
      var pixel = map.fromLatLngToDivPixel(latlng);
      if (Math.abs(pixel.x - clickedX) < 12 && Math.abs(pixel.y - clickedY) < 20) {
        //GEvent.trigger(marker, 'click');
      }
      map.addOverlay(marker);
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
    }
  }





}

/**
 * Zooms to the viewport that fits all the markers.
 */
function zoomToAll() {
  map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}

/**
 * Creates a marker for the given business.
 * @param {Number} ind
 * @return {GMarker}
 */




function createMarker(ind) {

  var business = businesses[ind];

        var baseIcon = new GIcon();
        //baseIcon.shadow = "http://www.xpatrentals.com/images/googleicon.png";
        baseIcon.iconSize = new GSize(20, 32);
        //baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);
        //baseIcon.infoShadowAnchor = new GPoint(18, 25);

//var newIcon = MapIconMaker.createMarkerIcon({width: 64, height: 64, primaryColor: "#00ff00"});
//alert (business.state);
//        var letter = String.fromCharCode(eval(business.state.charCodeAt(0)));

	var letter = business.zip;
          var letteredIcon = new GIcon(baseIcon);
          letteredIcon.image = "http://www.xpatrentals.com/images/google/" + letter + ".png";


          // Set up our GMarkerOptions object
          markerOptions = { icon:letteredIcon };



  var marker = new GMarker(new GLatLng(business.lat, business.lng), markerOptions);  
  GEvent.addListener(marker, 'mouseover', function() {
    marker.html = [business.country,'', business.name, '', 
                 
                  '',
                 business.phone, '', '', ''].join('');
                // '<a target="_blank" ',
                // 'href="http://maps.google.com/maps?saddr=&daddr=',
                // formatAddressForMaps2(business), '">to here</a> - ', 
                 //'<a target="_blank" ',
                 //'href="http://maps.google.com/maps?saddr=',
                 //formatAddressForMaps2(business), '&daddr=', '"> from here <br> ',
                // '<a href="javascript:zoomToAll()">view all</a>'
		
    currentMarker = marker;
    marker.openInfoWindowHtml(marker.html);
  });


        // save the info we need to use later for the side_bar
        gmarkers[i] = marker;
        // add a line to the side_bar html
        side_bar_html += '<a href="javascript:myclick(' + i + ')">link</a><br>';
        i++;
 
//alert(side_bar_html);

  return marker;
}

/**
 * Formats business info into a URL-friendly version for maps url.
 * @param {Object} business
 * @return {String}
 */
function formatAddressForMaps(business) {
  var address = business.street + ' ' + business.city + ' ' + business.state + ' ' + business.zip;
  return escape(address.replace(' ', '+'));
}

function formatAddressForMaps2(business) {
  var address = business.street;
  return escape(address.replace(' ', '+'));
}

/**
 * Convenience function for creating an element and assigning an id to it.
 * @param {String} elementType
 * @param {String} id
 * @return {Element} 
 */
function _cel(elementType, id) {
  var element = document.createElement(elementType);
  element.id = id;
  return element;
}

/**
 * Loads in the Maps API script. This is called after some sort of user interaction.
 * The script loads asynchronously and calls loadMap once it's in.
 */
function loadScript() {

  if (!isLoaded) {
    isLoaded = true;
    var div = document.createElement('div');
    div.className = 'message';
    div.innerHTML = '<font size=3 color=#008fd4><b>Loading advanced mapping...</b></font>';
    div.style.left = (500/2 - 53) + 'px';
    div.style.top = 500/2 + 'px'; 
    mapDiv.appendChild(div);
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://maps.google.com/maps?file=api&v=2.x' + 
                 '&async=2&callback=loadMap&key=' + mapkey;
    document.body.appendChild(script);
  }
}

/**
 * Sets up the gadget by setting CSS and click events.
 */
function loadMapGadget() {
  containerDiv = document.getElementById('container');
  mapDiv = document.getElementById('map');

// mapDiv.onclick = function (e) {
//   clickedX = (window.event && window.event.offsetX) || e.clientX;
//   clickedY = (window.event && window.event.offsetY) || e.clientY;
//  loadScript(); 
// };

  mapDiv.style.cursor = 'pointer';

  var urlString = ['http://maps.google.com/staticmap?markers='];
  var markerString = [];


// for (var i = 0; i < businesses.length; i++) {
//alert(businesses[i].state);
//   markerString.push(businesses[i].lat + ',' + businesses[i].lng + ',' + businesses[i].state.toLowerCase());
//}
// urlString.push(markerString.join('|'));
// urlString.push('&size=500x400');
// urlString.push('&key=' + mapkey);
// mapDiv.style.background = 'url(\'' + urlString.join('') + '\')';
//alert(urlString);
loadScript()

}

// This function picks up the click and opens the corresponding info window
function myclick(i) {
GEvent.trigger(gmarkers[i], "mouseover");
}


//window.onload = loadMapGadget();
 // document.getElementById("side_bar").innerHTML = side_bar_html;
