/****************************************************************************

bitjuice v0.1

*** LEGAL ***

Copyright (c) 2007, Michael Mahemoff and Numondo Ltd.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*** BASIC USAGE ***
var bitmap = new Bitmap(10,20); // width, height
containerElement.appendChild(bitmap);
bitmap.drawPoint(5,5,"pink"); // x,y,html colour

*** ADVANCED USAGE ***
var bitmap = new Bitmap(10,20, {container:containerElement, blankColor:"gray"});
bitmap.drawLine(1,2,5,5,"pink");
bitmap.drawRect(1,2,5,5,"pink");
bitmap.drawFilledRect(1,2,5,5,"pink");
bitmap.destroy(); // Same as containerElement.removeChild(bitmap);

See http://www.ajaxify.com/run/bit/form/scratchpad/ and read the code below
for extra tips

*** INTERNAL DESIGN NOTES ***

*** TODO ***
- Optimise by unrolling function calls
- Handle logging (e.g. delete various logging commands and/or provide custom
  logging)
- Fill function?
- Sprites (based on image DOM object - e.g. showSprite(x,y,image)
- Event capture e.g. bitmap.onmouseclick = function(x,y)
- (Hard) Convert to GIF image (non-IE - using data: url)

*** RELATED ***
http://blog.lib.umn.edu/dean0130/blog/2006/02/javascript_drawing_program.html
data: http://software.hixie.ch/utilities/cgi/data/data
JS data uri: http://t3.dotgnu.info/code/jsbitmap/
JS data uri: http://simonwillison.net/2003/Aug/11/selfContained/
PNGLets: http://www.elf.org/pnglets/#Display

****************************************************************************/

function Bitmap(width, height, options) {

  options = options || {};
  options["debug"] = options["debug"] || false;

  this.blankColor = options["blankColor"] || "white";
  this.borderCollapse = true;
  this.container = options["container"];
  if (options["borderCollapse"]==false) this.borderCollapse = false;
  this.tds = [];
  this.width = width;
  this.height = height;
  this.size = 0; // Could get by querying tds, but needed for here anyway
  this.element = document.createElement("table");
  this.element.className = "bitmap";
  this.element.style.borderCollapse = this.borderCollapse ? "collapse" : "separate";

  for (var row=0; row<height; row++) {
    var tr = this.element.insertRow(-1);
    for (var col=0; col<width; col++) {
      this.size++;
      var td = tr.insertCell(-1);
      td.style.backgroundColor = this.blankColor;
      this.tds.push(td);
      tr.appendChild(td);
      if (options["debug"]) {
        td.innerHTML = col+","+row+":"+(this.size);
      }
    }
  }
  if (this.container) this.container.appendChild(this.element);

  if (!Bitmap.classDefined) {
    Bitmap.classDefined = true;

    Bitmap.prototype.destroy = function() {
      this.element.parentNode.removeChild(this.element);
    }

    Bitmap.prototype.clear = function() {
      for (var i=0; i<this.tds.length; i++) {
        this.tds[i].style.backgroundColor = this.blankColor;
      }
    }

    Bitmap.prototype.replace = function(bitmapArray) {
      for (var i=0; i<this.tds.length; i++) {
        this.tds[i].style.backgroundColor = bitmapArray[i];
      }
    }

    Bitmap.prototype.readColor = function(x,y) {
      return this.tds[x + this.width*y].style.backgroundColor;
    }

    Bitmap.prototype.drawPoint = function(x,y,color) {
      logError(x + " " + y);
      if (x<0 || x>this.width-1 || y<0 || y>this.height-1) {
        logError("Co-ords out of range");
        return;
      }
      this.tds[x + this.width*y].style.backgroundColor = color;
    }

    Bitmap.prototype.erasePoint = function(x,y) {
      this.drawPoint(x,y,this.blankColor);
    }

    Bitmap.prototype.drawLine = function(x1,y1,x2,y2,color) {
      var width = Math.abs(x2-x1);
      var height = Math.abs(y2-y1);
      if (x1==x2 && y1==y2) { this.drawPoint(x1,y1); return; }
      if (width<height) { // Climb by height (incremenet y)
        logError("width < height");
        if (y2<y1) {
          logError("swapping A");
          var t = x1; x1 = x2; x2 = t; 
              t = y1; y1 = y2; y2 = t; 
        }
        logError(x1+" " + y1 + " " + x2 + " " + y2);
        for (var y = y1; y<=y2; y++) {
          var x = Math.round(x1 + (x2-x1)*(y-y1)/height)
          keepInRange(x,x1,x2);
          this.drawPoint(x,y,color);
        }
      } else {
        logError("width > height");
        if (x2<x1) {
          var t = x1; x1 = x2; x2 = t;
              t = y1; y1 = y2; y2 = t;
          logError("swapping B");
        }
        for (var x = x1; x<=x2; x++) {
          var y = Math.round(y1 + (y2-y1)*(x-x1)/width);
          keepInRange(y,y1,y2);
          logError("draw " + x + " " + y + " " + color);
          this.drawPoint(x,y,color);
        }
      }

    }

    Bitmap.prototype.drawRect = function(x1,y1,x2,y2,color) {
      logError("d1");
      this.drawLine(x1,y1,x2,y1,color);
      logError("d2");
      this.drawLine(x2,y1,x2,y2,color);
      logError("d3");
      this.drawLine(x2,y2,x1,y2,color);
      logError("d4");
      this.drawLine(x1,y2,x1,y1,color);
    }

    Bitmap.prototype.drawFilledRect = function(x1,y1,x2,y2,color) {
      if (x1>x2) { var t = x1; x1 = x2; x2 = t; }
      if (y1>y2) { var t = y1; y1 = y2; y2 = t; }
      for (var y=y1; y<=y2; y++) {
        for (var x=x1; x<=x2; x++) {
          this.drawPoint(x,y,color);
        }
      }
    }

    Bitmap.prototype.drawPoly = function() {
      // TODO check args > 5 and odd
      arg = arrayIze(arguments);
      var color = arg.pop();
      arg.push(arg[0]);
      arg.push(arg[1]);
      logError("---> array " + debugArray(arg));
      for (var i=2; i<arg.length; i=i+2) {
        logError("poly " + arg[i-2]+","+arg[i-1]+" "+arg[i]+","+arg[i+1]+" "+color);
        this.drawLine(arg[i-2],arg[i-1],arg[i],arg[i+1],color);
      }
    }

  }

  return this;

}

function swap(i,j) {
  iOrig = i;
  i = j;
  j = iOrig;
}

function keepInRange(val,min,max) {
  if (val<min) val = min;
  if (val>max) val = max;
}

function logError(error) {
  // document.body.innerHTML = "<div style='background:red'>"+error+"</div>" + document.body.innerHTML;
  if (this.console) console.log(error);
}

function debugArray(a) {
  var s="";
  for (var i=0; i<a.length; i++) {
    s+=a[i] +" ";
  }
  return s;
}

function arrayIze(obj) {
  var a = new Array();
  for (var i=0; i<obj.length; i++) {
    a.push(obj[i]);
  }
  return a;
}

