function formatMoney(amt) {
		var n = new Number(amt);
    return "$ " + n.toLocaleString().split(".")[0] + "."
        + n.toFixed(2).split(".")[1];
}

function empty( mixed_var ) {
    // !No description available for empty. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/empty
    // +   original by: Philippe Baumann
    // +      input by: Onno Marsman
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: LH
    // +   improved by: Onno Marsman
    // +   improved by: Francesco
    // +   improved by: Marc Jansen
    // *     example 1: empty(null);
    // *     returns 1: true
    // *     example 2: empty(undefined);
    // *     returns 2: true
    // *     example 3: empty([]);
    // *     returns 3: true
    // *     example 4: empty({});
    // *     returns 4: true
    // *     example 5: empty({'aFunc' : function () { alert('humpty'); } });
    // *     returns 5: false
    
    var key;
    
    if (mixed_var === "" ||
        mixed_var === 0 ||
        mixed_var === "0" ||
        mixed_var === null ||
				mixed_var === 'Null' ||
				mixed_var === 'NULL' ||
        mixed_var === false ||
        mixed_var === undefined
    ){
        return true;
    }

    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }
    return false;
}

function truncate(str,len){
	var len = (len)?len:80;
	var trunc;
	if (str) {
	
	  trunc = str.replace(/(<([^>]+)>)/ig,"");
	  if (trunc.length > len) {
	
	    /* Truncate the content of str, then go back to the end of the
	       previous word to ensure that we don't truncate in the middle of
	       a word */
	    trunc = trunc.substring(0, len);
	    trunc = trunc.replace(/\w+$/, '');
	
	    /* Add an ellipses to the end */
	    trunc += '...<\/a>';
	  }
	}

  return trunc;
}

var PropertyMap = Class.create({
  initialize: function(map_data,property_data,edit,map_container_id,map_controls_id,input_prefix,controller,scrollWheelZoom,autoZoomAndCenter) {
    this.property_data = property_data;
    this.map_data = map_data;
    this.property_markers = [];
    this.markers = [];
    this.mapContainer = $(map_container_id);
    this.mapControls = $(map_controls_id);
    this.map_width = (this.map_data.width) ? this.map_data.width : 500;
    this.map_height = (this.map_data.height) ? this.map_data.height : 400;
// added case for maps that already have their dimensions set
    if (edit || this.mapContainer.style.display == 'none') {
		this.map = new google.maps.Map2(this.mapContainer, {
			size: new google.maps.Size(this.map_width, this.map_height)
		});
	} else {
		this.map = new google.maps.Map2(this.mapContainer);
	}
//    this.map = new google.maps.Map2(this.mapContainer);
		if (autoZoomAndCenter && this.property_data.length > 1) {
			
			this.map.setCenter(new GLatLng(0,0),0);
			
			var bounds = new GLatLngBounds();
			var includedProperties = 0;
			for (var i=0;i<this.property_data.length;i++){
				var latitude = Number(this.property_data[i][input_prefix].latitude);
				var longitude = Number(this.property_data[i][input_prefix].longitude);

				if(latitude != 0 && longitude != 0 && !isNaN(latitude) && !isNaN(longitude)){
//					alert(this.property_data[i][input_prefix].latitude + ' - ' + this.property_data[i][input_prefix].longitude);
					includedProperties++;
					var latlng = new GLatLng(this.property_data[i][input_prefix].latitude, this.property_data[i][input_prefix].longitude); 
					var marker = new GMarker(latlng);
					bounds.extend(latlng);
				}
			}
			if (includedProperties > 0) {
	  		this.map.setCenter(bounds.getCenter(), this.map.getBoundsZoomLevel(bounds), G_NORMAL_MAP);
	  	}else{
				this.map.setCenter(new google.maps.LatLng(this.map_data.start_latitude, this.map_data.start_longitude), parseInt(this.map_data.start_zoom), G_NORMAL_MAP);
			}
		}
		else {
			this.map.setCenter(new google.maps.LatLng(this.map_data.start_latitude, this.map_data.start_longitude), parseInt(this.map_data.start_zoom), G_NORMAL_MAP);
		}
		this.point = new google.maps.LatLng(this.map_data.start_latitude,this.map_data.start_longitude);
		this.latitude = this.map_data.start_latitude;
		this.longitude = this.map_data.start_longitude;
		this.zoom = this.map_data.start_zoom;
		this.map.enableContinuousZoom();
		if (scrollWheelZoom == null || scrollWheelZoom == true) {
			this.map.enableScrollWheelZoom();
		}
		else {
			
		}
	this.map.addControl(new google.maps.SmallMapControl());
	  this.map.addControl(new google.maps.MapTypeControl());
    this.read_coords = false;
    
    this.inputPrefix = (input_prefix) ? input_prefix : '';
		this.controller = (controller) ? controller : '';
    if (edit){
      this.property_data[0][input_prefix].labels = ['Info','Address'];
      var info = '<div style="width:350px;">';
      info += '<div style="float:left;width:160px;height:160px;">';
      info += this.property_data[0][input_prefix]['thumbnail'];
      info += '</div>';
      info += '<div style="float:left;width:180px;">';
      info += '<div style="font-weight:bold;padding:2px;"><a href="/' + this.inputPrefix + '/view/' + this.property_data[0][input_prefix]['id'] + '">' + this.property_data[0][input_prefix]['title'] + '</a></div>';
      
      info += '<div style="padding:2px;">' + truncate(this.property_data[0][this.inputPrefix]['description'],80) + '</div>';
      info += '</div>';
      info += '</div>';
      
      var address = '<div>';
      address += '<div style="width:350px;">';
      address += '<div style="padding:2px;">' + this.property_data[0][this.inputPrefix]['address_line_1'] + '</div>';
      if(this.property_data[0][this.inputPrefix]['address_line_2']){
        address += '<div style="padding:2px;">' + this.property_data[0][this.inputPrefix]['address_line_2'] + '</div>';
      }
      if(this.property_data[0][this.inputPrefix]['city']){
        address += '<div style="padding:2px;">' + this.property_data[0][this.inputPrefix]['city'] + '</div>';
      }
      
      address += '</div>';
      
      this.property_data[0][this.inputPrefix].htmls = [info,address];
  		if (this.property_data[0][this.inputPrefix].latitude && this.property_data[0][this.inputPrefix].longitude){
        this.latitude = this.property_data[0][this.inputPrefix].latitude;
        this.longitude = this.property_data[0][this.inputPrefix].longitude;
        this.point = new google.maps.LatLng(this.property_data[0][this.inputPrefix].latitude,this.property_data[0][this.inputPrefix].longitude);
        this.placeMarker(0,this.point,this.property_data[0][this.inputPrefix].labels,this.property_data[0][this.inputPrefix].htmls);
      }
      if (this.property_data[0][this.inputPrefix].zoom){
        this.zoom = this.property_data[0][this.inputPrefix].zoom;
        this.map.setZoom (this.zoom);
      }
      this.createMarkerEditControls();
    }else{
      for (var i=0;i<this.property_data.length;i++){
        this.property_data[i][this.inputPrefix].labels = ['Info','Address'];
// adding htmls - joakim
		      var info = '<div style="width:250px;">';
		      info += '<div style="float:left;width:90px;height:90px;">';
		      info += this.property_data[i][this.inputPrefix]['thumbnail'];
		      info += '</div>';
		      info += '<div style="float:left;width: 150px;">';
		      info += '<div style="font-weight:bold;padding:2px;"><a href="/'+this.controller+'/view/' + this.property_data[i][this.inputPrefix]['id'] + '">' + this.property_data[i][this.inputPrefix]['title'] + '</a></div>';
					
		      info += '<div style="padding:2px;">' + truncate(this.property_data[i][this.inputPrefix]['description'],80) + '</div>';
		      info += '</div>';
		      info += '</div>';
		      
		      var address = '<div>';
		      address += '<div style="width:250px;">';
		      address += '<div style="padding:2px;">' + this.property_data[i][this.inputPrefix]['address_line_1'] + '</div>';
		      if(this.property_data[i][this.inputPrefix]['address_line_2']){
		        address += '<div style="padding:2px;">' + this.property_data[i][this.inputPrefix]['address_line_2'] + '</div>';
		      }
		      if(this.property_data[i][this.inputPrefix]['city']){
		        address += '<div style="padding:2px;">' + this.property_data[i][this.inputPrefix]['city'] + '</div>';
		      }
		      address += '</div>';		
       // this.property_data[i][this.inputPrefix].htmls = ['Info goes here...','Address goes here...'];
			this.property_data[i][this.inputPrefix].htmls = [info,address];
				var latitude = Number(this.property_data[i][this.inputPrefix].latitude);
				var longitude = Number(this.property_data[i][this.inputPrefix].longitude);
//				alert(typeof(latitude) + ' = ' + latitude);
//				alert(typeof(latitude));
//				if(latitude != 0 && longitude != 0 && latitude != NaN && longitude != NaN){
//					alert(latitude + ' = ' + typeof(latitude));
				//if(typeof(latitude)=='number' && typeof(longitude)=='number'){
//        if (!empty(this.property_data[i][this.inputPrefix].latitude) && !empty(this.property_data[i][this.inputPrefix].longitude)){
				if(latitude != 0 && longitude != 0 && !isNaN(latitude) && !isNaN(longitude)){
//  alert('included');
    		  point = new google.maps.LatLng(this.property_data[i][this.inputPrefix].latitude,this.property_data[i][this.inputPrefix].longitude);
          this.placeMarker(i,point,this.property_data[i][this.inputPrefix].labels,this.property_data[i][this.inputPrefix].htmls);
        }
      }
    }
  },
  createMarkerEditControls: function(){
    this.markerEditContainer = new Element('div',{'class': '','id': 'marker_edit_container'});
    this.coordsButtonContainer = new Element('div',{'class': '','id': 'btn_read_coords_container','style': 'float:left;'});
    this.markerEditContainer.appendChild(this.coordsButtonContainer);
    this.coordsButton = new Element('input',{'type': 'button','class': '','id': 'btn_read_coords','value': 'Read Coords'});
    this.coordsButtonContainer.appendChild(this.coordsButton);
    this.coordsEditInstructions = new Element('div',{'class': '','id': 'coords_edit_instructions','style': 'margin-bottom:10px;float:left;clear:both;font-style:italic;'});
    this.coordsEditInstructions.innerHTML = 'Click on <i>Read Coords</i> to change coordinates and zoom level.';
    this.markerEditContainer.appendChild(this.coordsEditInstructions);
    
    this.latitudeDisplay = new Element('div',{'class': '','id': 'latitude_display','style': 'float:left;clear:both;'});
    this.markerEditContainer.appendChild(this.latitudeDisplay);
    
    this.longitudeDisplay = new Element('div',{'class': '','id': 'longitude_display','style': 'float:left;clear:both;'});
    this.markerEditContainer.appendChild(this.longitudeDisplay);
    
    this.zoomDisplay = new Element('div',{'class': '','id': 'zoom_display','style': 'float:left;clear:both;'});
    this.markerEditContainer.appendChild(this.zoomDisplay);
    
    this.resetCoordsButtonContainer = new Element('div',{'class': '','id': 'btn_reset_coords_container','style': 'float:left;clear:both;'});
    this.markerEditContainer.appendChild(this.resetCoordsButtonContainer);
    this.resetCoordsButton = new Element('input',{'type': 'button','class': '','id': 'btn_reset_coords','value': 'Reset Map'});
    this.resetCoordsButtonContainer.appendChild(this.resetCoordsButton);
    
//    new Insertion.After(this.mapContainer, this.markerEditContainer);
//    this.mapContainer.insert({after: this.markerEditContainer});
    this.mapControls.appendChild(this.markerEditContainer);

    Event.observe(this.coordsButton, 'click', this.readCoords.bindAsEventListener(this));
    Event.observe(this.resetCoordsButton, 'click', this.resetMap.bindAsEventListener(this));
    
    if (!$(this.inputPrefix + 'Latitude')){
      this.latitudeInput = new Element('input',{'class': '','id': this.inputPrefix + 'Latitude','name': this.inputPrefix + 'Latitude', 'type': 'hidden'});
      this.markerEditContainer.appendChild(this.latitudeInput);
    }else{
      this.latitudeInput = $(this.inputPrefix + 'Latitude');
    }
    this.latitudeInput.value = this.latitude;
    if (!$(this.inputPrefix + 'Longitude')){
      this.longitudeInput = new Element('input',{'class': '','id': this.inputPrefix + 'Longitude','name': this.inputPrefix + 'Longitude', 'type': 'hidden'});
      this.markerEditContainer.appendChild(this.longitudeInput);
    }else{
      this.longitudeInput = $(this.inputPrefix + 'Longitude');
    }
    this.longitudeInput.value = this.longitude;
    if (!$(this.inputPrefix + 'Zoom')){
      this.zoomInput = new Element('input',{'class': '','id': this.inputPrefix + 'Zoom','name': this.inputPrefix + 'Zoom', 'type': 'hidden'});
      this.markerEditContainer.appendChild(this.zoomInput);
    }else{
      this.zoomInput = $(this.inputPrefix + 'Zoom');
    }
    this.zoomInput.value = this.zoom;
    
    this.latitudeDisplay.innerHTML = 'Latitude: ' + this.latitudeInput.value;
    this.longitudeDisplay.innerHTML = 'Longitude: ' + this.longitudeInput.value;
    this.zoomDisplay.innerHTML = 'Zoom: ' + this.zoomInput.value;
    
  },
  placeMarker: function(index,point,labels,htmls){
    this.property_markers[index] = this.createTabbedMarker(index,point,htmls,labels);
    this.map.addOverlay(this.property_markers[index]);
  },
  createTabbedMarker: function(index,point,htmls,labels) {
    this.markers[index] = new google.maps.Marker(point);
    google.maps.Event.bind(this.markers[index], "click", this, function() {
      
      // adjust the width so that the info window is large enough for this many tabs
      if (this.property_data[index][this.inputPrefix].htmls.length > 2) {
        this.property_data[index][this.inputPrefix].htmls[0] = '<div style="width:'+this.property_data[index][this.inputPrefix].htmls.length*88+'px">' + this.property_data[index][this.inputPrefix].htmls[0] + '</div>';
      }
    
      this.tabs = [];
      for (var i=0; i<this.property_data[index][this.inputPrefix].htmls.length; i++) {
        this.tabs.push(new google.maps.InfoWindowTab(this.property_data[index][this.inputPrefix].labels[i],this.property_data[index][this.inputPrefix].htmls[i]));
      }
      this.markers[index].openInfoWindowTabsHtml(this.tabs);
    });
    return this.markers[index];
  },
  readCoords: function(){
    this.read_coords = (this.read_coords) ? false : true;
    if (this.read_coords){
      this.coordsButton.value = 'Set Coords';
      this.coordsEditInstructions.innerHTML = 'Click on map to set coordinates and zoom level.';
      this.latitudeInput.readOnly = false;
      this.longitudeInput.readOnly = false;
      this.zoomInput.readOnly = false;
      
      this.mapContainer.down(1).style.cursor = 'crosshair';
      
      
      this.zoom = this.map.getZoom();
      this.zoomInput.value = this.zoom;      
      this.zoomDisplay.innerHTML = 'Zoom: ' + this.zoomInput.value;
      this.property_data[0][this.inputPrefix].zoom = this.zoomInput.value;
        
      
      this.coordsListener = google.maps.Event.bind(this.map,"click", this, function(overlay,point) {
        this.latitudeInput.value = point.lat();
        this.longitudeInput.value = point.lng();
        this.zoomInput.value = this.map.getZoom();
        this.latitude = point.lat();
        this.longitude = point.lng();
        this.zoom = this.map.getZoom();
        
        this.latitudeDisplay.innerHTML = 'Latitude: ' + this.latitudeInput.value;
        this.longitudeDisplay.innerHTML = 'Longitude: ' + this.longitudeInput.value;
        this.zoomDisplay.innerHTML = 'Zoom: ' + this.zoomInput.value;
        
        this.property_data[0][this.inputPrefix].latitude = this.latitudeInput.value; 
        this.property_data[0][this.inputPrefix].longitude = this.longitudeInput.value;
        this.property_data[0][this.inputPrefix].zoom = this.zoomInput.value;
        this.mapContainer.down(1).style.cursor = 'crosshair';
        
        this.point = new google.maps.LatLng(this.latitudeInput.value,this.longitudeInput.value);
        if (this.property_markers[0]){
          this.property_markers[0].setLatLng(this.point);
        }else{
          this.placeMarker(0,this.point,this.property_data[0][this.inputPrefix].labels,this.property_data[0][this.inputPrefix].htmls);
        }
		  });
		  
      this.zoomListener = google.maps.Event.bind(this.map, "zoomend", this, function(oldzoom,zoom) {
        this.zoomInput.value = zoom;
        this.zoom = zoom;
        this.zoomDisplay.innerHTML = 'Zoom: ' + zoom;
        this.property_data[0][this.inputPrefix].zoom = zoom;
      });

    }else{
      this.coordsButton.value = 'Read Coords';
      this.coordsEditInstructions.innerHTML = 'Click on <i>Read Coords</i> to change coordinates and zoom level.';
      this.latitudeInput.readOnly = true;     
      this.longitudeInput.readOnly = true;
      this.zoomInput.readOnly = true;

      this.mapContainer.down(1).style.cursor = 'url(http://www.google.com/intl/en_ALL/mapfiles/openhand.cur), default';
      google.maps.Event.removeListener(this.coordsListener);
      google.maps.Event.removeListener(this.zoomListener);
      
    }  
  },
  resizeMap: function() {
    this.map.checkResize();
    this.map.setCenter(this.point, this.zoom);
  },
  resetMap: function(){
    this.map.setCenter(new google.maps.LatLng(this.map_data.start_latitude, this.map_data.start_longitude), parseInt(this.map_data.start_zoom), G_SATELLITE_MAP);
    this.read_coords = true;
    
    this.latitudeInput.readOnly = false;
    this.longitudeInput.readOnly = false;
    this.zoomInput.readOnly = false;
      
    this.zoom = parseInt(this.map_data.start_zoom);
    this.zoomInput.value = this.zoom;      
    this.zoomDisplay.innerHTML = 'Zoom: ' + this.zoomInput.value;
    this.property_data[0][this.inputPrefix].zoom = this.zoomInput.value;
     
    this.latitudeInput.value = this.map_data.start_latitude;
    this.longitudeInput.value = this.map_data.start_longitude;
    this.latitude = this.map_data.start_latitude;
    this.longitude = this.map_data.start_longitude;
    
    this.latitudeDisplay.innerHTML = 'Latitude: ' + this.latitudeInput.value;
    this.longitudeDisplay.innerHTML = 'Longitude: ' + this.longitudeInput.value;
    
    this.property_data[0][this.inputPrefix].latitude = this.latitudeInput.value; 
    this.property_data[0][this.inputPrefix].longitude = this.longitudeInput.value;
    
    this.point = new google.maps.LatLng(this.latitudeInput.value,this.longitudeInput.value);
    
    if (this.property_markers[0]){
      this.property_markers[0].setLatLng(this.point);
    }else{
      this.placeMarker(0,this.point,this.property_data[0][this.inputPrefix].labels,this.property_data[0][this.inputPrefix].htmls);
    }
    
    this.read_coords = false;
    this.coordsButton.value = 'Read Coords';
    this.coordsEditInstructions.innerHTML = 'Click on <i>Read Coords</i> to change coordinates and zoom level.';
    this.latitudeInput.readOnly = true;     
    this.longitudeInput.readOnly = true;
    this.zoomInput.readOnly = true;

    this.mapContainer.down(1).style.cursor = 'url(http://www.google.com/intl/en_ALL/mapfiles/openhand.cur), default';
    if (this.coordsListener){
      google.maps.Event.removeListener(this.coordsListener);
    }
    if(this.zoomListener){
      google.maps.Event.removeListener(this.zoomListener);
    }
  }

});

