Prototype.BrowserFeatures.VML = !!document.namespaces;
Prototype.BrowserFeatures.Canvas = !!(document.createElement('canvas') && document.createElement('canvas').getContext);
var Highlight = Class.create({
  initialize: function(element) {
    this.element = $(element);
    this.highlightObj = this;
    this.highlight_color = 'rgba(255,255,0,0.2)';
    if(!Prototype.BrowserFeatures.VML && !Prototype.BrowserFeatures.Canvas) 
      return console.log('Browser Unsupported: VML & Canvas Missing!');
    if(element.hasAttribute('highlight_color'))
      this.highlight_color = element.readAttribute('highlight_color');
    this.initializeCanvas();
    this.initializeAreas();
  },
  initializeCanvas: function() {
    this.container = new Element('div', {style: 'width: ' + this.element.getWidth() + 'px; height: ' + this.element.getHeight() + 'px; background: url('+ this.element.src +') no-repeat; position: relative; margin: 0; padding: 0;'});
    this.container.insert(this.element.insert({before: this.container}));
    this.element.setStyle({position: 'absolute', top: 0, left: 0, opacity: 0});
    if(Prototype.BrowserFeatures.Canvas) {
      this.canvas = new Element('canvas', {style: 'width: ' + this.element.getWidth() + 'px; height: ' + this.element.getHeight() + 'px; position: absolute; top: 0; left: 0;'});
      this.clear();
    } else {
      document.namespaces.add("v", "urn:schemas-microsoft-com:vml"); 
      var style = document.createStyleSheet();
      $w('shape rect oval circ fill stroke imagedata group textbox').each(function(shape) {
        style.addRule('v\\:' + shape, "behavior: url(#default#VML); antialias:true");
      });
      this.canvas = new Element('var', {style: 'zoom: 1; overflow: hidden; display: block; width:' + this.element.getWidth() + 'px; height: ' + this.element.getHeight() + 'px; position: absolute; top: 0; left: 0; border: 0px'});
    }
    this.element.insert({before: this.canvas});
    this.canvas.width = this.element.getWidth();
    this.canvas.height = this.element.getHeight();
  },
  initializeAreas: function() {
    $('map_'+ this.element.getAttribute('usemap').substr(1)).select('area').each(function(area) {
      if(!area.hasAttribute('coords') && !area.coords) return;
      // this.highlight(area);
      area.observe('mouseover', this.highlight.bind(this, area));
      area.observe('mouseout', this.clear.bind(this));
    }.bind(this));
  },
  highlight: function(area) {
    var coords = area.getAttribute('coords').split(',').collect(function(coord) { return parseFloat(coord); });
    if(Prototype.BrowserFeatures.Canvas) {
      var i, context = this.canvas.getContext('2d');

      context.beginPath();
      switch(area.getAttribute('shape').toLowerCase()) {
        case 'rect':
          context.rect(coords[0], coords[1], coords[2] - coords[0], coords[3] - coords[1]);
          break;
        case 'poly':
          context.moveTo(coords[0], coords[1]);
          for(i=2; i < coords.length; i+=2) {
            context.lineTo(coords[i], coords[i+1]);
          }
          break;
        case 'circle':
          context.arc(coords[0], coords[1], coords[2], 0, Math.PI * 2, false)
          break;
      }
      context.closePath();

      context.fillStyle = this.highlight_color;
      context.fill();
    } else {
      var shape;
      switch(area.getAttribute('shape').toLowerCase()) {
        case 'rect':
          shape = new Element('v:rect', {filled: 't', stroked: 'f', style: 'zoom: 1; margin: 0; padding: 0; display: block; border: 0; position: absolute; left: ' + coords[0] + 'px; top: ' + coords[1] + 'px; width: ' + (coords[2] - coords[0]) + 'px; height: ' + (coords[3] - coords[1]) + 'px;'});
          break;
        case 'poly':
          shape = new Element('v:shape', {filled: 't', stroked: 'f', coordorigin: '0,0', coordsize: this.canvas.width + ',' + this.canvas.height, path: 'm ' + coords[0] + ',' +coords[1] +' l '+ coords.join(',') + ' x e', style: 'zoom: 1; margin: 0; padding: 0; display: block; position: absolute; top: 0px; left: 0px; width:' + this.canvas.width + 'px; height: ' + this.canvas.height + 'px;'});
          break;
        case 'circle':
          shape = new Element('v:oval', {filled: 't', stroked: 'f', style: 'zoom: 1; margin: 0; padding: 0; display: block; position: absolute; left: ' + (coords[0] - coords[2]) + 'px; top: ' + (coords[1] - coords[2]) + 'px; width: ' + (coords[2]*2) + 'px; height: ' + (coords[2]*2) + 'px;'});
          break;
      }
      var colors = this.highlight_color.match(/(\d{1,3},\d{1,3},\d{1,3}),([0-9.]+)/)
      this.canvas.insert(shape.insert(new Element('v:fill', {color: this.rbaValuesToCSS(colors[1]), opacity: colors[2]})));
    }
  },
  rbaValuesToCSS: function(value) {
    return "#" + value.split(',').map(function(c) {
      var string = Math.round(parseInt(c)).toString(16);
      if (string.length == 1) string = '0' + string;
      return string;
    }).join('').toUpperCase();
  },
  clear: function() {
    if(Prototype.BrowserFeatures.Canvas) {
      this.canvas.getContext('2d').clearRect(0, 0, this.element.getWidth(), this.element.getHeight());
    } else {
      this.canvas.innerHTML = '';
    }
  }
});

var setupHighlight = function() {
  $$('img.highlight[usemap]').each(function(element) {
    if(!element.highlightObj)
      new Highlight(element);
  });
};
Event.observe(window, 'load', setupHighlight);
