MM_Cfg_Regale = {
  instance: null,
  sensors: [],
  sensors5Way: [],
  boards: [],
  onSensor: 0,
  onSensor5Way: 0,
  onBoard: 0,
  grid: [],
  tplPxl: [],
  
  doLog: true,
  
  pixelNotationObject: 1,
  pixelNotationArray: 2,
  pixelNotation: 2,
  pixelNotationNfo: ['', 'byObject', 'byArray'],
  
  gridTranslation: {
     n: {x: 0, y: 1, o: 's'}
    ,e: {x: 1, y: 0, o: 'w'}
    ,s: {x: 0, y: -1, o: 'n'}
    ,w: {x: -1, y: 0, o: 'e'}
  },
  
  poolFn: {
    cntJunctions: function(x, y, find)
    {
      var cnt = 0;
      var oStack = ['n','e','s','w'];

      var inStack = 0;
      while (o = oStack[inStack])
      {
        inStack++;
        if (find == MM_Cfg_Regale.gridJunctions[y][x][o])
        {
          if (('n' == o && y == MM_Cfg_Regale.instance.numRows) || ('e' == o && x == MM_Cfg_Regale.instance.numColumns))
          {
            // no count
          }
          else
          {
            cnt++;
          }
        }
      }

      return cnt;
    },
    
    chgJunction: function(x, y, o, c)
    {
      if (MM_Cfg_Regale.gridJunctions[y])
      {
        if (MM_Cfg_Regale.gridJunctions[y][x])
        {
          if (3 != MM_Cfg_Regale.gridJunctions[y][x][o])
          {
            MM_Cfg_Regale.gridJunctions[y][x][o] = c;

            var mX = MM_Cfg_Regale.gridTranslation[o].x;
            var mY = MM_Cfg_Regale.gridTranslation[o].y;
            var mO = MM_Cfg_Regale.gridTranslation[o].o;
            
            if (MM_Cfg_Regale.gridJunctions[y + mY][x + mX])
            {
              if (3 != MM_Cfg_Regale.gridJunctions[y + mY][x + mX][mO])
              {
                MM_Cfg_Regale.gridJunctions[y + mY][x + mX][mO] = c;
              }
            }
          }
        }
      }
    },
    
    
    mouseClick: function(e)
    {
      var pos = {
        x: 0,
        y: 0
      };
      
      var c = this.elScreen.getCoordinates();
      pos.x = e.event.clientX - c.left;
      pos.y = e.event.clientY - c.top;
      pos.y = c.height - pos.y;
      
      this.elCrossHair.style.backgorundImage = 'url(/media/Image/Icons/cross-hair-grey.gif)';
      var out = 'pos: ' + Json.toString(pos);
      if (this.thePixels[pos.x] && this.thePixels[pos.x][pos.y]) 
      {
        var grid = this.thePixels[pos.x][pos.y];
        this.elCrossHair.style.backgorundImage = 'url(/media/Image/Icons/cross-hair-magenta.gif)';
        out += '; Grid: ' + Json.toString(grid);
        
        switch (grid.o)
        {
          case 0 :
            MM_Cfg_Regale.gridJunctions.chg(grid.x, grid.y, 'n', 2);
            MM_Cfg_Regale.gridJunctions.chg(grid.x, grid.y, 'e', 2);
            MM_Cfg_Regale.gridJunctions.chg(grid.x, grid.y, 's', 2);
            MM_Cfg_Regale.gridJunctions.chg(grid.x, grid.y, 'w', 2);
            break;
          case 1 :
            switch (MM_Cfg_Regale.gridJunctions[grid.y][grid.x].e)
            {
              case 1 :
                MM_Cfg_Regale.gridJunctions.chg(grid.x, grid.y, 'e', 2);
                break;
              case 2 :
                MM_Cfg_Regale.gridJunctions.chg(grid.x, grid.y, 'e', 1);
                break;
            }
            break;
          case 2 :
            switch (MM_Cfg_Regale.gridJunctions[grid.y][grid.x].n)
            {
              case 1 :
                MM_Cfg_Regale.gridJunctions.chg(grid.x, grid.y, 'n', 2);
                break;
              case 2 :
                MM_Cfg_Regale.gridJunctions.chg(grid.x, grid.y, 'n', 1);
                break;
            }
            break;
        }
        
        this.reBuild();
      }
    },
    
    mouseMove: function(e)
      {
        var pos = {
          x: 0,
          y: 0
        };
        
        var c = this.elScreen.getCoordinates();
        pos.x = e.event.clientX - c.left;
        pos.y = e.event.clientY - c.top;
        pos.y = c.height - pos.y;
        
//        this.elCrossHair.setStyles({
//          left: pos.x - 5,
//          bottom: pos.y - 5 - window.getSize().scroll.y
//        });
        
        
        this.elCrossHair.style.backgorundImage = 'url(/media/Image/Icons/cross-hair-grey.gif)';
        var out = 'pos: ' + Json.toString(pos);
        if (this.thePixels[pos.x] && this.thePixels[pos.x][pos.y]) 
        {
          var grid = this.thePixels[pos.x][pos.y];
          this.elCrossHair.style.backgorundImage = 'url(/media/Image/Icons/cross-hair-magenta.gif)';
          out += '; Grid: ' + Json.toString(grid);
          
        var xGrind = MM_Cfg_Regale.instance.getGridLengthX();
        var yGrind = MM_Cfg_Regale.instance.getGridLengthY();
          
          switch (grid.o)
          {
            case 0 :
//              this.elHLs.c.setStyles({
//                 left    : Math.floor((xGrind + this.staerke) * grid.x * this.scale)
//                ,bottom  : Math.floor((yGrind + this.staerke) * grid.y * this.scale)
//                ,width   : Math.floor(this.staerke * this.scale)
//                ,height  : Math.floor(this.staerke * this.scale)
//                ,opacity : 0.5
//              });
              
              if (0 < MM_Cfg_Regale.gridJunctions.cnt(grid.x, grid.y, 1))
              {
                this.gridHiglight(grid, 'n', 1);
                this.gridHiglight(grid, 'e', 1);
                this.gridHiglight(grid, 's', 1);
                this.gridHiglight(grid, 'w', 1); 
              }
              else
              {
                this.gridHiglight(grid, 'n', 2);
                this.gridHiglight(grid, 'e', 2);
                this.gridHiglight(grid, 's', 2);
                this.gridHiglight(grid, 'w', 2); 
              }
              
              break;
              
            case 1 :
              var amNow = MM_Cfg_Regale.gridJunctions[grid.y][grid.x].e;
              var hlLength = 0;
              var xOffset = -1;
              
              offset = 1;
              
              while (
                    grid.x + offset < MM_Cfg_Regale.instance.numColumns
                &&  MM_Cfg_Regale.gridJunctions[grid.y][grid.x + offset]
                &&  MM_Cfg_Regale.gridJunctions[grid.y][grid.x + offset].w == amNow
                &&  2 > MM_Cfg_Regale.gridJunctions.cnt(grid.x + offset, grid.y, 1)
                )
                {
                  offset++;
                  hlLength++;
                }
              
              while (
                    MM_Cfg_Regale.gridJunctions[grid.y][grid.x + xOffset]
                &&  MM_Cfg_Regale.gridJunctions[grid.y][grid.x + xOffset].e == amNow
                &&  2 > MM_Cfg_Regale.gridJunctions.cnt(grid.x + xOffset, grid.y, 1)
                )
                {
                  xOffset--;
                  hlLength++;
                }
              
              
//              console.log(amNow);
//              console.log(cntBorders);
//              console.log(MM_Cfg_Regale.gridJunctions[grid.y][grid.x]);
//              console.log(MM_Cfg_Regale.gridJunctions[grid.y][grid.x + 1]);
//              console.log(hlLength);
              
              var gridA = {
                 x: grid.x + 1 + xOffset
                ,y: grid.y
                ,o: grid.o
              };
              
              if (hlLength > 0)
              {
                this.gridHiglight(gridA, 'e', null, hlLength) + 1;
              }
              else
              {
                this.elHLs.e.setStyle('opacity', 0);
              }
              
              this.elHLs.c.setStyle('opacity', 0);
              this.elHLs.n.setStyle('opacity', 0);
              this.elHLs.w.setStyle('opacity', 0);
              this.elHLs.s.setStyle('opacity', 0);
              break;
              
            case 2 :
              this.gridHiglight(grid, 'n');
              this.elHLs.c.setStyle('opacity', 0);
              this.elHLs.e.setStyle('opacity', 0);
              this.elHLs.w.setStyle('opacity', 0);
              this.elHLs.s.setStyle('opacity', 0);
              break;
          }
        }
        else
        {
          this.elHLs.n.setStyle('opacity', 0);
          this.elHLs.e.setStyle('opacity', 0);
          this.elHLs.c.setStyle('opacity', 0);
              this.elHLs.w.setStyle('opacity', 0);
              this.elHLs.s.setStyle('opacity', 0);
        }
        this.elCrossHair.set('text', out);
      },
    
    fillPixelsArray: function(start, size, Grid, color)
    {
      start.x = Math.floor(start.x);
      start.y = Math.floor(start.y);
      size.x = Math.floor(size.x);
      size.y = Math.floor(size.y);
      
      proof = {
        x: start.x + size.x,
        y: start.y + size.y
      };
      
      for (start.x; start.x < proof.x; start.x++) 
      {
        for (start.y = proof.y - size.y; start.y < proof.y; start.y++) 
        {
          this.thePixels[start.x][start.y] = Grid;
          if(!this.gfxPixels[start.x][start.y]) this.gfxPixels[start.x][start.y] = [];
          this.gfxPixels[start.x][start.y].push(color);
//          start.x + '-' + start.y + '-' + color;
        }
      }
    },
    fillPixelsObject: function(start, size, Grid, color)
    {
      start.x = Math.floor(start.x);
      start.y = Math.floor(start.y);
      size.x  = Math.floor(size.x);
      size.y  = Math.floor(size.y);
      
      proof = {
        x: start.x + size.x,
        y: start.y + size.y
      };
      
      for (start.x; start.x < proof.x; start.x++) 
      {
        for (start.y = proof.y - size.y; start.y < proof.y; start.y++) 
        {
          this.thePixels[start.x + '-' + start.y] = Grid;
//          start.x + '-' + start.y + '-' + color;
//          this.gfxPixels.push();
        }
      }
    }
  },
  
  getSensorsAt: function()
  {
  
  },
  evtKeyDown: function(e)
  {
//    if (this.lastValue == this.value)
//      return;
//
//    if (this.timeOut) 
//      window.clearTimeout(this.timeOut);
  },
  evtKeyUp: function(e)
  {
    if (this.timeOut) 
      window.clearTimeout(this.timeOut);
      
    if (this.lastValue == this.value)
      return;
      
    this.timeOut = window.setTimeout(function()
    {
      this.value = this.value.replace(/\D/g, '');
      MM_Cfg_Regale.instance.reBuild();
    }.bind(this), 1500);
  },
  evtChange: function(e)
  {
    this.value = this.value.replace(/\D/g, '');
    
    switch (e.target.id)
    {
      case 'regal-width':
        if (this.value >= 40 && this.value <= 720) 
        {
          MM_Cfg_Regale.instance.reBuild();
        }
        break;
      case 'regal-height':
        if (this.value >= 40 && this.value <= 300) 
        {
          MM_Cfg_Regale.instance.reBuild();
        }
        break;
      case 'regal-columns':
        if (this.value >= MM_Cfg_Regale.minColumns && this.value <= MM_Cfg_Regale.maxColumns) 
        {
          MM_Cfg_Regale.instance.reBuild();
        }
        break;
      case 'regal-rows':
        if (this.value >= MM_Cfg_Regale.minRows && this.value <= MM_Cfg_Regale.maxRows) 
        {
          MM_Cfg_Regale.instance.reBuild();
        }
        break;
    }
  },
  resetSensorDispatcher: function()
  {
    while (MM_Cfg_Regale.sensors.length > this.onSensor) 
    {
      Sensor = MM_Cfg_Regale.sensors.pop();
      Sensor.el2.remove();
      Sensor.el.remove();
      Sensor = null;
    }
    this.onSensor = 0;
  },
  getSensor: function(grid)
  {
    if (!MM_Cfg_Regale.sensors[this.onSensor]) 
    {
      MM_Cfg_Regale.sensors[this.onSensor] = new MM_Cfg_Regal_Sensor();
    }
    
    return MM_Cfg_Regale.sensors[this.onSensor++];
  },
  resetSensor5WayDispatcher: function()
  {
    while (MM_Cfg_Regale.sensors5Way.length > this.onSensor5Way) 
    {
      Sensor = MM_Cfg_Regale.sensors5Way.pop();
      Sensor.el2.remove();
      Sensor.el.remove();
      Sensor = null;
    }
    this.onSensor5Way = 0;
  },
  getSensor5Way: function()
  {
    if (!MM_Cfg_Regale.sensors5Way[this.onSensor5Way]) 
    {
      MM_Cfg_Regale.sensors5Way[this.onSensor5Way] = new MM_Cfg_Regal_Sensor5Way();
    }
    
    return MM_Cfg_Regale.sensors5Way[this.onSensor5Way++];
  },
  resetBoardDispatcher: function()
  {
    Sensor = MM_Cfg_Regale.boards[this.onBoard++];
    while (Sensor)
    {
      Sensor.hide();
      Sensor = MM_Cfg_Regale.boards[this.onBoard++];
    }
//    while (MM_Cfg_Regale.boards.length > this.onBoard)
//    {
//      Sensor = MM_Cfg_Regale.boards.pop();
//      Sensor.el.remove();
//      Sensor = null;
//    }
    this.onBoard = 0;
  },
  getBoard: function()
  {
    if (!MM_Cfg_Regale.boards[this.onBoard]) 
    {
      MM_Cfg_Regale.boards[this.onBoard] = new MM_Cfg_Regal_Board();
    }
    
//    console.log('this.onBoard: ' + this.onBoard);
//    console.log('MM_Cfg_Regale.boards: ' + MM_Cfg_Regale.boards.length);
    return MM_Cfg_Regale.boards[this.onBoard++];
  },
  maxColumns: 0,
  minColumns: 0,
  maxRows: 0,
  minRows: 0,
  setUpResizer: function()
  {
    var Resizer = new Element('div', {
      style: 'position: absolute; bottom: 0; left: 0; padding: 20px 20px 0 0; border: 2px dashed grey; border-width: 1px 1px 0 0;'
    });
    var ResizeContainer = new Element('div', {
      style: 'width: 500px; height: 300px; position: absolute; bottom: 46px; left: 44px; padding: 20px 20px 0 0; border: 1px solid green;'
    });
    
    var ResizeHandle = new Element('div', {
      style: 'position: absolute; left: 100px; bottom: 100px; width: 16px; height: 16px; background: url(/media/Image/Icons/resize-handle.gif);'
    });
    el.adopt(Resizer);
    el.adopt(ResizeContainer);
    ResizeContainer.adopt(ResizeHandle);
    ResizeHandle.makeDraggable({
      container: ResizeContainer,
      onDrag: function(handler)
      {
        var w = parseInt(ResizeContainer.style.left) - 4 + parseInt(handler.style.left);
        var h = parseInt(ResizeContainer.style.bottom) - 2 + parseInt(handler.getParent().getCoordinates().height) - parseInt(handler.style.top) - parseInt(Resizer.getStyle('padding-top'));
        Resizer.setStyles({
          width: w,
          height: h
        });
        
        MM_Cfg_Regale.instance.elWidth.value = w;
        MM_Cfg_Regale.instance.elHeight.value = h;
      },
      onComplete: function()
      {
        MM_Cfg_Regale.validateInputs();
        MM_Cfg_Regale.instance.reBuild();
      }
    });
  },
  setInputs: function()
  {
    MM_Cfg_Regale.maxColumns = Math.floor(MM_Cfg_Regale.instance.elWidth.value / 30);
    MM_Cfg_Regale.minColumns = Math.ceil(MM_Cfg_Regale.instance.elWidth.value / 150);
    MM_Cfg_Regale.maxRows    = Math.floor(MM_Cfg_Regale.instance.elHeight.value / 30);
    MM_Cfg_Regale.minRows    = Math.ceil(MM_Cfg_Regale.instance.elHeight.value / 150);
    
    $('columns-max').set('text', MM_Cfg_Regale.maxColumns);
    $('columns-min').set('text', MM_Cfg_Regale.minColumns);
    $('rows-max').set('text', MM_Cfg_Regale.maxRows);
    $('rows-min').set('text', MM_Cfg_Regale.minRows);
  },
  validateInputs: function()
  {
    var input = MM_Cfg_Regale.instance.elWidth;
    input.value = Math.max(40, input.value);
    input.value = Math.min(720, input.value); 
    input.lastValue = input.value;
    
    var input = MM_Cfg_Regale.instance.elHeight;
    input.value = Math.max(40, input.value);
    input.value = Math.min(300, input.value); 
    input.lastValue = input.value;
    
    MM_Cfg_Regale.setInputs();
    
    var input = MM_Cfg_Regale.instance.elRows;
    input.value = Math.max(MM_Cfg_Regale.minRows, input.value);
    input.value = Math.min(MM_Cfg_Regale.maxRows, input.value); 
    input.lastValue = input.value;
    
    var input = MM_Cfg_Regale.instance.elColumns;
    input.value = Math.max(MM_Cfg_Regale.minColumns, input.value);
    input.value = Math.min(MM_Cfg_Regale.maxColumns, input.value); 
    input.lastValue = input.value;
  }
};

var MM_Cfg_Regal = new Class();
MM_Cfg_Regal.prototype = {
  elArea: null,
  elScreen: null,
  elCrossHair: null,
  elWidth: null,
  elHeight: null,
  elColumns: null,
  elRows: null,
  elStatus: null,
  thePixels: [],
  theGrid: [],
  fullWidth: 0,
  scale: 1.25,
  
  elHLs: {
     n: null
    ,w: null
    ,s: null
    ,e: null
    ,c: null
  },
  
  gridJunctions: [],
  
  gridHasBoards: function(grid)
  {
    
  },
  
  gridHiglight: function(grid, orientation, code, length)
  {
    var xGrind = MM_Cfg_Regale.instance.getGridLengthX();
    var yGrind = MM_Cfg_Regale.instance.getGridLengthY();
    var doPaint = false;

    var colors = {
       1: {color: 'red', opacity: 0.5}
      ,2: {color: 'green', opacity: 0.5}
      ,3: {color: 'blue', opacity: 0.2}
    };  
    var probeCode = MM_Cfg_Regale.gridJunctions[grid.y][grid.x][orientation];
    
    if (!arguments[2])
    {
      code = probeCode;
    }
    
    if (!arguments[3])
    {
      length = 1;
    }
    
    switch (orientation)
    {
      case 'n' :
        if (grid.y < this.numRows)
        {
          doPaint = true;
        }
        
        if (code != probeCode)
        {
          doPaint = false;
        }
        
        if (doPaint)
        {
          this.elHLs.n.setStyles({
             left    : Math.floor((xGrind + this.staerke) * grid.x * this.scale)
            ,bottom  : Math.floor((this.staerke + (yGrind + this.staerke) * (grid.y)) * this.scale)
            ,width   : Math.floor(this.staerke * this.scale)
            ,height  : Math.floor((yGrind) * this.scale)
            ,opacity : colors[code].opacity
            ,'background-color' : colors[code].color
          });
        }
        else
        {
          this.elHLs.n.setStyle('opacity', 0);
        }
        break;
      case 'e' :
        if (grid.x < this.numColumns)
        {
          doPaint = true;
        }
        
        if (code != probeCode)
        {
          doPaint = false;
        }
        
        if (doPaint)
        {
          this.elHLs.e.setStyles({
             left    : Math.floor((this.staerke + (xGrind + this.staerke) * (grid.x)) * this.scale)
            ,bottom  : Math.floor((yGrind + this.staerke) * grid.y * this.scale)
            ,width   : Math.floor(((xGrind + this.staerke) * length - this.staerke) * this.scale)
            ,height  : Math.floor(this.staerke * this.scale)
            ,opacity : colors[code].opacity
            ,'background-color' : colors[code].color
          });
        }
        else
        {
          this.elHLs.e.setStyle('opacity', 0);
        }
        break;
      case 's' :
        if (grid.y > 0)
        {
          doPaint = true;
        }
        
        if (code != probeCode)
        {
          doPaint = false;
        }
        
        
        
        if (doPaint)
        {
          this.elHLs.s.setStyles({
             left    : Math.floor((xGrind + this.staerke) * grid.x * this.scale)
            ,bottom  : Math.floor((this.staerke + (yGrind + this.staerke) * (grid.y - 1)) * this.scale)
            ,width   : Math.floor(this.staerke * this.scale)
            ,height  : Math.floor((yGrind + this.staerke) * this.scale)
            ,opacity : colors[code].opacity
            ,'background-color' : colors[code].color
          });
        }
        else
        {
          this.elHLs.s.setStyle('opacity', 0);
        }
        break;
      case 'w' :
        if (grid.x > 0)
        {
          doPaint = true;
        }
        
        if (code != probeCode)
        {
          doPaint = false;
        }
        
        if (doPaint)
        {
            this.elHLs.w.setStyles({
               left    : Math.floor((this.staerke + (xGrind + this.staerke) * (grid.x - 1)) * this.scale)
              ,bottom  : Math.floor((yGrind + this.staerke) * grid.y * this.scale)
              ,width   : Math.floor((xGrind + this.staerke) * this.scale)
              ,height  : Math.floor(this.staerke * this.scale)
              ,opacity : colors[code].opacity
              ,'background-color' : colors[code].color
            });
        }
        else
        {
          this.elHLs.w.setStyle('opacity', 0);
        }
        break;
    }
  },
  
  initialize: function(el)
  {
    MM_Cfg_Regale.instance = this;
    this.thePixels = MM_Cfg_Regale.tplPxl;
    
    this.elStatus = $('regal-status');
    
    this.elArea = el;
    this.elScreen = new Element('div', {
      style: 'position: absolute;'
    });
    this.elCrossHair = new Element('div', {
      style: 'height: 9px; line-height: 9px; width: 250px; white-space: no-wrap; background: url(/media/Image/Icons/cross-hair-grey.gif) no-repeat left top white; padding: 0; padding-left: 30px; font-size: 9px;'
    });
    this.elCrossHair.set('text', 'asdf');
    
    this.elArea.getParent().adopt(this.elCrossHair);
    this.elArea.getParent().adopt(this.elScreen);
    
    this.elHLs.n = new Element('div', {style: 'position: absolute; bottom: 0; left: 0; background-color: blue;'});
    this.elHLs.n.setStyle('opacity', 0);
    this.elHLs.e = this.elHLs.n.clone();
    this.elHLs.s = this.elHLs.n.clone();
    this.elHLs.w = this.elHLs.n.clone();
    this.elHLs.c = this.elHLs.n.clone();
    
    this.elArea.adopt(this.elHLs.n, this.elHLs.e, this.elHLs.s, this.elHLs.w, this.elHLs.c);
    
    [this.elHLs.n, this.elHLs.e, this.elHLs.s, this.elHLs.w, this.elHLs.c].each(function(el)
    {
      el.setStyles({
        'z-index': 2100
      })
    });
    
    this.elScreen.setStyles(this.elArea.getParent().getStyles('width', 'height', 'padding'));
    this.elScreen.setStyles({
      bottom: 0,
      left: 0,
      'z-index': 3000,
      width: 480,
      height: 300,
      'position': 'absolute'
    });
    this.elCrossHair.setStyles({
      bottom: 0,
      left: 0,
//      display: 'none',
      position: 'absolute',
      'z-index': 2999,
      'line-height': '9px'
    });
    
    this.elWidth = $('regal-width');
    this.elHeight = $('regal-height');
    this.elColumns = $('regal-columns');
    this.elRows = $('regal-rows');
    
    this.elScreen.addEvents({
       mousemove: MM_Cfg_Regale.poolFn.mouseMove.bindWithEvent(this)
      ,click: MM_Cfg_Regale.poolFn.mouseClick.bindWithEvent(this)
      ,mouseenter: function()
      {
//        this.elCrossHair.setStyle('display', 'block');
      }.bind(this)
      ,mouseleave: function()
      {
//        this.elCrossHair.setStyle('display', 'none');
      }.bind(this)
    });
    
    
    [this.elWidth, this.elHeight, this.elColumns, this.elRows].each(function(el)
    {
      el.addEvents({
        keyup: MM_Cfg_Regale.evtKeyUp.bindWithEvent(el),
        keydown: MM_Cfg_Regale.evtKeyDown.bindWithEvent(el),
        change: MM_Cfg_Regale.evtChange.bindWithEvent(el)
      });
    });
    
    
    this.reBuild();
  },
  reBuild: function()
  {
    MM_Cfg_Regale.validateInputs();
    
    this.fullWidth = this.elArea.getCoordinates().width - 20;
    this.scale = this.fullWidth / 360;
    
    if (parseInt(this.elWidth.value) > 360) 
    {
      this.scale *= 0.5;
    }
    else 
      if (parseInt(this.elWidth.value) < 180) 
      {
        this.scale *= 1.5;
      }
    
//    this.elArea.getParent().setStyle('height', Math.floor(this.scale * 300));
    this.elArea.getParent().setStyle('height', 300);
    
    this.numColumns = parseInt(this.elColumns.value);
    this.numRows = parseInt(this.elRows.value);
    
    this.build();
  },
  columns: [],
  rows: [],
  grid: [],
  numColumns: 0,
  numRows: 0,
  staerke: 4,
  gfxPixels: [],
  
  
  fillPixels: null,
  
  buildCreateBoards: function()
  {
//    this.rows = [];
//    this.columns = [];
//    
//    for (var i = 0; i <= this.numRows; i++) 
//    {
//        this.rows.push(MM_Cfg_Regale.getBoard());
//    }
//    for (var i = 0; i <= this.numColumns; i++) 
//    {
//        this.columns.push(MM_Cfg_Regale.getBoard());
//    }
  },
  
  buildPlaceBoards: function()
  {
    for (var r = 0; r <= this.numRows; r++) 
    {
      var columns = [{start: 0, started: false, length: 0}];
      var column = 0;
      for (var c = 0; c < this.numColumns; c ++)
      {
        switch (MM_Cfg_Regale.gridJunctions[r][c].e)
        {
          case 1 :
            if (!columns[column].started)
            {
              columns[column].started = true;
              columns[column].start = c;
            }
            columns[column].length ++;
            break;
          case 2 :
            if (columns[column].length > 0)
            {
              columns.push({start: 0, started: false, length: 0});
              column++;
            }
            break;
        }
      }
      
      var i = 0;
      var column = null;
      while (column = columns[i++])
      {
        var Board = MM_Cfg_Regale.getBoard();
        Board.setOptions({
          orientation: 'horizontal',
          grid: {
            x: column.start,
            y: r,
            n: column.length
          }
        });
      }
    }
    for (var r = 0; r <= this.numColumns; r++) 
    {
      var columns = [{start: 0, started: false, length: 0}];
      var column = 0;
      for (var c = 0; c < this.numRows; c ++)
      {
        switch (MM_Cfg_Regale.gridJunctions[c][r].n)
        {
          case 1 :
            if (!columns[column].started)
            {
              columns[column].started = true;
              columns[column].start = c;
            }
            columns[column].length ++;
            break;
          case 2 :
            if (columns[column].length > 0)
            {
              columns.push({start: 0, started: false, length: 0});
              column++;
            }
            break;
        }
      }
      
      var i = 0;
      var column = null;
      while (column = columns[i++])
      {
        var Board = MM_Cfg_Regale.getBoard();
        Board.setOptions({
          orientation: 'vertical',
          grid: {
            x: r,
            y: column.start,
            n: column.length
          }
        });
      }
    }

  },
  buildCreatePixels: function()
  {
    switch (MM_Cfg_Regale.pixelNotation)
    {
      case MM_Cfg_Regale.pixelNotationObject :
        this.fillPixels = MM_Cfg_Regale.poolFn.fillPixelsObject;
        
        this.thePixels = {};
        break;
        
      case MM_Cfg_Regale.pixelNotationArray :
        this.fillPixels = MM_Cfg_Regale.poolFn.fillPixelsArray;
        
        this.thePixels = [];
        this.thePixels.length = 500;
        this.gfxPixels = [];
        this.gfxPixels.length = 500;
        for (var i = 0; i <= 500; i++)
        {
          this.thePixels[i] = [];
          this.thePixels[i].length = 500;
          this.gfxPixels[i] = [];
          this.gfxPixels[i].length = 500;
        }
        break;
    }
    
    
    var xGrind = MM_Cfg_Regale.instance.getGridLengthX();
    var yGrind = MM_Cfg_Regale.instance.getGridLengthY();
    var offset = {
      x: 10,
      y: 10
    };
    var clickPad = {
      x: 5,
      y: 5
    };
    
    for (var r = 0; r <= this.numRows; r++) 
    {
      for (var c = 0; c <= this.numColumns; c++) 
      {
        var grid = {
          x: c,
          y: r
        };
        
        var allX = ((this.staerke + xGrind) * c);
        var allY = ((this.staerke + yGrind) * r);
        
        if (c < this.numColumns) 
        {
          this.fillPixels({
            x: offset.x + (((allX - clickPad.x) + ((clickPad.x * 2) + this.staerke)) * MM_Cfg_Regale.instance.scale),
            y: offset.y + ((allY - clickPad.y) * MM_Cfg_Regale.instance.scale)
          }, {
            x: ((clickPad.x + xGrind) - ((clickPad.x * 2) + this.staerke)) * MM_Cfg_Regale.instance.scale,
            y: ((clickPad.y * 2) + this.staerke) * MM_Cfg_Regale.instance.scale
          }, {x: grid.x, y: grid.y, o: 1}, 2);
        }
        
        if (r < this.numRows) 
        {
          grid.o = 2;
          this.fillPixels({
            x: offset.x + ((allX - clickPad.x) * MM_Cfg_Regale.instance.scale),
            y: offset.y + ((allY - clickPad.y + ((clickPad.y * 2) + this.staerke)) * MM_Cfg_Regale.instance.scale)
          }, {
            x: ((clickPad.x * 2) + this.staerke) * MM_Cfg_Regale.instance.scale,
            y: (clickPad.y + yGrind - ((clickPad.y * 2) + this.staerke)) * MM_Cfg_Regale.instance.scale
          }, {x: grid.x, y: grid.y, o: 2}, 3);
        }
        
        grid.o = 0;
        this.fillPixels({
          x: offset.x + ((allX - clickPad.x) * MM_Cfg_Regale.instance.scale),
          y: offset.y + ((allY - clickPad.y) * MM_Cfg_Regale.instance.scale)
        }, {
          x: ((clickPad.x * 2) + this.staerke) * MM_Cfg_Regale.instance.scale,
          y: ((clickPad.y * 2) + this.staerke) * MM_Cfg_Regale.instance.scale
        }, {x: grid.x, y: grid.y, o: 0}, 1);
      }
    }
  },
  buildCreateGfx: function()
  {
    if (!MM_Cfg_Regale.doLog) 
      return;
    
//    console.log({
//      asdf: this.thePixels
//    });
    
    new Ajax('/plugin/de.masstisch.ajax/Configurator/RegalImg.php', {
      data: 'img=' + Json.toString(this.gfxPixels),
      onComplete: function(resp)
      {
        this.elScreen.setStyles({
          'background': 'url(' + resp + ') no-repeat bottom left;'
        });
      }
.bind(this)
    }).request();
  },
  build: function()
  {
    var now = new Date();
    this.elStatus.addClass('ajax-loading');
    var backTo = this.elArea.getParent();
    backTo.removeChild(this.elArea);
    
    this.buildCreateBoards();
    this.buildPlaceBoards();
    this.buildCreatePixels();
//    this.buildCreateGfx();
    
    MM_Cfg_Regale.resetBoardDispatcher();
    MM_Cfg_Regale.resetSensorDispatcher();
    MM_Cfg_Regale.resetSensor5WayDispatcher();
    
    
    this.elArea.inject(this.elScreen, 'before');
    this.elStatus.removeClass('ajax-loading');
    this.elStatus.set('text', (new Date() - now) + ':' + MM_Cfg_Regale.pixelNotationNfo[MM_Cfg_Regale.pixelNotation]);
  },
  build_Old: function()
  {
    //	   	var xGrind = MM_Cfg_Regale.instance.getGridLengthX();
    //	   	var yGrind = MM_Cfg_Regale.instance.getGridLengthY();
    //		
    //        for (var r = 0; r <= this.numRows; r ++)
    //        {
    //	        for (var c = 0; c <= this.numColumns; c ++)
    //	        {
    //				var grid = {x: c, y: r};
    //				
    //				if (c < this.numColumns)
    //				{
    //			   	    var Sensor = MM_Cfg_Regale.getSensor();
    //					Sensor.grid = grid;
    //				    Sensor.setStyles({
    //					   	 bottom	: (((this.staerke + yGrind) * r)) * MM_Cfg_Regale.instance.scale
    //						,left	: (this.staerke + ((this.staerke + xGrind) * c)) * MM_Cfg_Regale.instance.scale
    //						,width	: xGrind * MM_Cfg_Regale.instance.scale
    //						,height	: this.staerke * MM_Cfg_Regale.instance.scale
    //				   	});
    //				}
    //				
    //				if (r < this.numRows)
    //				{
    //			   	    var Sensor = MM_Cfg_Regale.getSensor();
    //					Sensor.grid = grid;
    //				    Sensor.setStyles({
    //					   	 bottom	: (this.staerke + ((this.staerke + yGrind) * r)) * MM_Cfg_Regale.instance.scale
    //						,left	: (((this.staerke + xGrind) * c)) * MM_Cfg_Regale.instance.scale
    //						,width	: this.staerke * MM_Cfg_Regale.instance.scale
    //						,height	: yGrind * MM_Cfg_Regale.instance.scale
    //				   	});	
    //				}
    //				
    //				var Sensor = MM_Cfg_Regale.getSensor5Way();
    //				Sensor.grid = grid;
    //			    Sensor.setStyles({
    //				   	 bottom	: (((this.staerke + yGrind) * r)) * MM_Cfg_Regale.instance.scale
    //					,left	: (((this.staerke + xGrind) * c)) * MM_Cfg_Regale.instance.scale
    //					,width	: this.staerke * MM_Cfg_Regale.instance.scale
    //					,height	: this.staerke * MM_Cfg_Regale.instance.scale
    //					,background : 'yellow'
    //			   	});	
    //	        }
    //        }
  
  
  
    //			   var coords = this.el.getCoordinates();
    //			   var xGrind = MM_Cfg_Regale.instance.getGridLengthX();
    //			   var xPad = parseInt(this.el.style.left) + this.staerke;
    //			   var xPad2 = xGrind + this.staerke;
    //			   
    //			   for (var i = 0; i < this.grid.n; i ++)
    //			   {
    //			   	   var Sensor = MM_Cfg_Regale.getSensor();
    //				   Sensor.setStyles({
    //				   	 bottom: this.el.style.bottom
    //					,left: (xPad + xPad2 * i) * MM_Cfg_Regale.instance.scale
    //					,width: xGrind * MM_Cfg_Regale.instance.scale
    //					,height: this.staerke * MM_Cfg_Regale.instance.scale
    //				   });
    //			   }
    //			   
    //			   var coords = this.el.getCoordinates();
    //			   var xGrind = MM_Cfg_Regale.instance.getGridLengthY();
    //			   var xPad = parseInt(this.el.style.bottom) + this.staerke;
    //			   var xPad2 = xGrind + this.staerke;
    //			   
    //			   for (var i = 0; i < this.grid.n; i ++)
    //			   {
    //			   	   var Sensor = MM_Cfg_Regale.getSensor();
    //				   Sensor.setStyles({
    //				   	 bottom: (xPad + xPad2 * i) * MM_Cfg_Regale.instance.scale
    //					,left: this.el.style.left
    //					,width: this.staerke * MM_Cfg_Regale.instance.scale
    //					,height: xGrind * MM_Cfg_Regale.instance.scale
    //				   });
    //			   }
  },
  getGridY: function(grid)
  {
    var rows = this.numRows + 1;
    var space = this.elHeight.value - (this.staerke * rows);
    
    return (space / this.numRows * grid + (grid * this.staerke));
  },
  getGridX: function(grid)
  {
    var rows = this.numColumns + 1;
    var space = this.elWidth.value - (this.staerke * rows);
    
    return (space / this.numColumns * grid + (grid * this.staerke));
  },
  getGridLengthX: function()
  {
    var cnt = this.numColumns + 1;
    var space = this.elWidth.value - (this.staerke * cnt);
    
    return (space / this.numColumns);
  },
  getGridLengthY: function()
  {
    var cnt = this.numRows + 1;
    var space = this.elHeight.value - (this.staerke * cnt);
    
    return (space / this.numRows);
  },
  grid2LengthX: function(gridSpan)
  {
    return this.getGridLengthX() * gridSpan + this.staerke * (gridSpan + 1);
  },
  grid2LengthY: function(gridSpan)
  {
    return this.getGridLengthY() * gridSpan + this.staerke * (gridSpan + 1);
  }
};

var MM_Cfg_Regal_Sensor = new Class();
MM_Cfg_Regal_Sensor.prototype = {
  el: null,
  initialize: function()
  {
    this.el = new Element('div');
    this.el2 = new Element('div');
    this.el.adopt(this.el2);
    this.el2.empty();
    
    this.el.setStyles({
      position: 'absolute',
      bottom: 0,
      left: 0,
      padding: 5,
      overflow: 'hidden',
      'z-index': 1500
    });
    
    this.el2.setStyles({
      background: 'blue',
      opacity: 0,
      overflow: 'hidden'
    });
    
    MM_Cfg_Regale.instance.elArea.adopt(this.el);
    
    this.el.addEvents({
      mouseenter: function()
      {
        this.el2.setStyles({
          opacity: 1,
          width: this.el.getStyle('width'),
          height: this.el.getStyle('height')
        });
      }
.bind(this)      ,
      mouseleave: function()
      {
        this.el2.setStyles({
          opacity: 0
        });
      }
.bind(this)
    });
  },
  setStyles: function(styles)
  {
    styles.left = parseInt(styles.left) - 5;
    styles.bottom = parseInt(styles.bottom) - 5;
    this.el.setStyles(styles);
  }
};

var MM_Cfg_Regal_Sensor5Way = new Class();
MM_Cfg_Regal_Sensor5Way.prototype = {
  el: null,
  initialize: function()
  {
    this.el = new Element('div');
    this.el2 = new Element('div');
    this.el.adopt(this.el2);
    this.el2.empty();
    
    this.el.setStyles({
      position: 'absolute',
      bottom: 0,
      left: 0,
      padding: 5,
      overflow: 'hidden',
      'z-index': 2000
    });
    
    this.el2.setStyles({
      background: 'blue',
      opacity: 0,
      overflow: 'hidden'
    });
    
    MM_Cfg_Regale.instance.elArea.adopt(this.el);
    
    this.el.addEvents({
      mouseenter: function()
      {
        this.el2.setStyles({
          opacity: 1,
          width: this.el.getStyle('width'),
          height: this.el.getStyle('height')
        });
        
        MM_Cfg_Regale.getSensorsAt(this.grid);
      }
.bind(this)      ,
      mouseleave: function()
      {
        this.el2.setStyles({
          opacity: 0
        });
      }
.bind(this)
    });
  },
  setStyles: function(styles)
  {
    styles.left = parseInt(styles.left) - 5;
    styles.bottom = parseInt(styles.bottom) - 5;
    this.el.setStyles(styles);
  }
};

var MM_Cfg_Regal_Board = new Class();
MM_Cfg_Regal_Board.prototype = {
  el: null,
  orientation: '',
  length: 0,
  staerke: 0,
  grid: {
    x: 0,
    y: 0,
    n: 1
  },
  hide: function()
  {
    this.el.setStyle('display', 'none');
  },
  setOptions: function(opt)
  {
    for (key in opt) 
    {
      this[key] = opt[key];
    }
    this.paint();
  },
  setOrientation: function(val)
  {
    this.orientation = val;
    this.paint();
  },
  setLength: function(val)
  {
    this.length = val;
    this.paint();
  },
  setGrid: function(val)
  {
    this.grid = val;
    this.paint();
  },
  paint: function()
  {
    switch (this.orientation)
    {
      case 'horizontal':
        var y = MM_Cfg_Regale.instance.getGridY(this.grid.y);
        this.length = MM_Cfg_Regale.instance.grid2LengthX(this.grid.n);
        
        this.el.setStyles({
          width: Math.floor(this.length * MM_Cfg_Regale.instance.scale),
          height: Math.floor(this.staerke * MM_Cfg_Regale.instance.scale),
          bottom: Math.floor(y * MM_Cfg_Regale.instance.scale) + 'px',
          left: (MM_Cfg_Regale.instance.getGridX(this.grid.x)) * MM_Cfg_Regale.instance.scale + 'px',
          display: 'block'
        });
        
        break;
      case 'vertical':
        this.el.setStyles({
          height: MM_Cfg_Regale.instance.grid2LengthY(this.grid.n) * MM_Cfg_Regale.instance.scale,
          width: Math.floor(this.staerke * MM_Cfg_Regale.instance.scale),
          left: (MM_Cfg_Regale.instance.getGridX(this.grid.x)) * MM_Cfg_Regale.instance.scale + 'px',
          bottom: Math.floor(MM_Cfg_Regale.instance.getGridY(this.grid.y) * MM_Cfg_Regale.instance.scale) + 'px',
          display: 'block'
        });
        break;
    }
  },
  initialize: function()
  {
    this.el = new Element('div');
    this.staerke = MM_Cfg_Regale.instance.staerke;
    
    this.el.setStyles({
      position: 'absolute',
      bottom: 0,
      left: 0,
      background: '#dddddd',
      overflow: 'hidden'
    });
    
    MM_Cfg_Regale.instance.elArea.adopt(this.el);
  }
};

window.addEvent('domready', function()
{
//  MM_Cfg_Regale.gridJunctions.chg = MM_Cfg_Regale.poolFn.chgJunction;
//  MM_Cfg_Regale.gridJunctions.cnt = MM_Cfg_Regale.poolFn.cntJunctions;
  
  
  if (el = $('regal-area')) 
  {
//    new MM_Cfg_Regal(el);
    //		MM_Cfg_Regale.setUpResizer();
  }
  
  if (el = $('btn-rebuild'))
  {
    el.setStyles({
      cursor: 'default'
    });
    
    el.addEvents({
      mouseenter: function()
      {
        this.setStyle('background-color', '#00ff00');
      },
      mouseleave: function()
      {
        this.setStyle('background-color', 'transparent');
      },
      click: function()
      {
        MM_Cfg_Regale.pixelNotation = 2; //MM_Cfg_Regale.pixelNotation == 1 ? 2 : 1;
        MM_Cfg_Regale.instance.reBuild();
      }
    });
  }
  
  if (el = $('btn-underlay'))
  {
    el.setStyles({
      cursor: 'default'
    });
    
    el.addEvents({
      mouseenter: function()
      {
        this.setStyle('background-color', '#00ff00');
      },
      mouseleave: function()
      {
        this.setStyle('background-color', 'transparent');
      },
      click: function()
      {
        MM_Cfg_Regale.instance.buildCreateGfx();
      }
    });
  }
});

