Application = (function() {
  var map, maptimizeMap;
  
  function addCommas(nStr) {
  	nStr += '';
  	x = nStr.split('.');
  	x1 = x[0];
  	x2 = x.length > 1 ? '.' + x[1] : '';
  	var rgx = /(\d+)(\d{3})/;
  	while (rgx.test(x1)) {
  		x1 = x1.replace(rgx, '$1' + ',' + '$2');
  	}
  	return x1 + x2;
  }
  // Load google map API
  function init(center, zoom, id) {
    google.load("maps", "2");
    google.setOnLoadCallback(function() {
      initCallback.defer();
    });
  }

  function requestContent(marker, ids) {
    var waitingContent = $('waiting_content'),
        content        = new Element('div', {id: 'window'}).addClassName('maptimize_info_window').insert(waitingContent.cloneNode(true).show());
    marker.openInfoWindowHtml(content);
    content.observe('click', paginate)
    
    new Ajax.JSONRequest(contentUrl, {
      callbackParamName: "callback",
      parameters: {"id[]": ids},
      onSuccess: function(response) {
        content.update(response.responseJSON);
      },
      onFailure: function(response) {
        content.upate("An error occurs on server");
      }
    });
  }
  
  function paginate(event) {
    var element = event.element();
    if (element.href && element.up().hasClassName('digg_pagination')) {
      event.stop();
	  var url = element.href;
	  if (url.indexOf('http:') != 0)
		url = rootUrl + url;
      new Ajax.JSONRequest(url, {
        callbackParamName: "callback",
        onSuccess: function(response) {
          $('window').update(response.responseJSON);
        },
        onFailure: function(response) {
          $('window').upate("An error occurs on server");
        }
      });
    }
  }
  
  function initCallback(center, zoom) {
    if (GBrowserIsCompatible()) {
      // Create a new google map
      map = new GMap2($('map'));

      // Centered over US
  		map.setCenter(new GLatLng(38.5, -98.5), 
      map.getBoundsZoomLevel(new GLatLngBounds(new GLatLng(24.926294766395593, -127.529296875), 
                                               new GLatLng(50.79204706440684, -66.533203125))));

      // Add controls
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());

      // // Attach maptimize plugin and set callbacks
      maptimizeMap = new Maptimize.Map(map, {
        theme: getTheme(),
        onMarkersLoaded: function() {
          var count = 0;
          maptimizeMap.getMarkers().each(function(marker) {count += marker.getValueSum()});
          $('center').update(addCommas(count) + ' patents on map');
        },
        onMarkerClicked:function(marker) {
          requestContent(marker.getGMarker(), marker.getId()); 
        },
        onZoomMaxClusterClicked:function(cluster, ids) {
          requestContent(cluster.getGMarker(), ids);
        }
      });

      // For debugging
      window.map          = map;
      window.maptimizeMap = maptimizeMap;
    }
  }

  
  return {init: init}
})();


document.observe('dom:loaded', Application.init)

