// © 2004-2008, Applied Geographics, Inc.  All rights reserved.

function ScaleBar(id, targetMap, width, units, precision) {
  this.id = id;
  
  this.element = document.getElementById(id);
  this.text = document.getElementById(id + "_Text");
  
  this.targetMap = targetMap;
  this.width = width;
  this.units = units;
  this.precision = precision;
  
  this.attachEventInternal = function(element, eventName, handler) {
    if (element.attachEvent) {
      element.attachEvent("on" + eventName, handler);
    }
    else {
      element.addEventListener(eventName, handler, false);
    }
  };

  this.attachToMap = function() {
    var controller = this;
    var map = document.getElementById(this.targetMap);
    map.attachEvent("mapextentchange", function () { controller.mapExtentChanged(); });
    this.element.map = map;
  };

  this.getLengthText = function() {    
    var barLength = this.element.map.getPixelSize() * this.width;

    if (this.units == Units.Pixels || this.element.map.controller.units == Units.Pixels) {
      return Math.round(barLength) + " pixels";
    }

    if (this.units == Units.Feet) {
      if (this.element.map.controller.units == Units.Meters) {
        barLength /= 0.3048;
      }

      if (barLength < 5280) {
        return this.precisionRound(barLength) + " feet";
      }
      else {
        barLength /= 5280;
        return this.precisionRound(barLength) + " miles";
      }
    }
    else
    {
      if (this.element.map.controller.units == Units.Feet) {
        barLength *= 0.3048;
      }

      if (barLength < 1000) {
        return this.precisionRound(barLength) + " meters";
      }
      else {
        barLength *= 0.001;
        return this.precisionRound(barLength) + " kilometers";
      }
    }
  };
  
  this.mapExtentChanged = function() {
    if (this.text.childNodes.length == 1) {
      this.text.removeChild(this.text.firstChild);
    }
    
    this.text.appendChild(document.createTextNode(this.getLengthText()));
  };
  
  this.precisionRound = function(d) {
    if (this.precision == 0) {
      return d;
    }
    
    var p = parseInt(Math.ceil(Math.log(d) / Math.LN10));
    p = this.precision > 0 ? this.precision - p : -this.precision > p ? -this.precision - p : 0;
    
    return Math.round(d * Math.pow(10, p)) * Math.pow(10, -p);
  };
  
  var controller = this;
  this.element.controller = this;

  this.attachEventInternal(window, "load", function () { controller.attachToMap(); });
  
  return this.element;
}
