// JavaScript Document
function bannerClickedNative(codbanner) {
  if (codbanner == 0) alert('Banner da Confermare !');
  else window.open('cpBannerClick.php?codbanner='+codbanner);
  return false
}

function Grid(name, codgrid) {

  function setOriginXY(x, y) {__self.xPos = x; __self.yPos = y}
  function setRows(rows) {__self.rows = rows}
  function setCols(cols) {__self.cols = cols}
  function setRowHeight(h) {__self.rowH = h}
  function setColWidth(w) {__self.colW = w}
  function setPrice(p) {__self.price = p}
  function setBckImage(img) {__self.bckImage = img}
  function setMaxWidth(w) {__self.maxWidth = w}
  function setMaxHeight(h) {__self.maxHeight = h}
  function setGridLayout(rowsNo, colsNo, rowH, colW) {
    setRows(rowsNo)
    setCols(colsNo)
    setRowHeight(rowH)
    setColWidth(colW)
    __self.width = __self.cols * __self.colW;
    __self.height = __self.rows * __self.rowH;
  }

  function getXorigin() {
    if(!document.getElementById || !document.getElementsByTagName || !document.createElement) {alert('ai');return;}

    var obj = document.getElementById(__self.name);

    if(!obj|| !obj.offsetParent) {alert('ai2');return;}

    /* riferimento al body del documento */
    var body = document.getElementsByTagName('body')[0];

    var left = 0, top = 0;

    /* ottiene la posizione assoluta del div */

    /* distanza dal bordo sinistro della pagina */
    for (var tmpObj = obj; tmpObj.offsetParent; tmpObj = tmpObj.offsetParent)
      left += tmpObj.offsetLeft;

       /* distanza dal bordo superiore */
    for (var tmpObj = obj; tmpObj.offsetParent; tmpObj = tmpObj.offsetParent)
      top += tmpObj.offsetTop;

      return left;
  }

  function getYorigin() {
    if(!document.getElementById || !document.getElementsByTagName || !document.createElement) {alert('ai');return;}

    var obj = document.getElementById(__self.name);

    if(!obj|| !obj.offsetParent) {alert('ai2');return;}

    /* riferimento al body del documento */
    var body = document.getElementsByTagName('body')[0];

    var left = 0, top = 0;

    /* ottiene la posizione assoluta del div */

    /* distanza dal bordo sinistro della pagina */
    for (var tmpObj = obj; tmpObj.offsetParent; tmpObj = tmpObj.offsetParent)
      left += tmpObj.offsetLeft;

       /* distanza dal bordo superiore */
    for (var tmpObj = obj; tmpObj.offsetParent; tmpObj = tmpObj.offsetParent)
      top += tmpObj.offsetTop;

      return top;
  }

  /**
  * function drawGrid
  * pixel grid rendering
  */
  function drawGrid() {
    __self.width = __self.cols * __self.colW;
    __self.height = __self.rows * __self.rowH;

    var s = ''

    // grid
    s += '<div id="'+__self.name+'" '
    // style
    s += 'style="position:absolute;left:'+getXorigin()+';top:'+getYorigin()+';width='+__self.width+';height='+__self.height+' '

    // this background don't work on NS
    //if (__self.bckImage !='') {
    //  s += ';background:url(\''+__self.bckImage+'\')'
    //}


    s += ';border:0px solid #000000'


    s += '" '
    // end style

    s += 'title="seleziona l\'area in cui inserire il tuo banner" '
    s += '></div>'
    // end grid
    document.write(s)

    // add selector div
    s = ''
    s += '<div id="square" '
    // style
    s += 'style="visibility:hidden;margin:0;padding:0;font-size:0pt;filter:alpha(opacity=50);-moz-opacity:0.5" '
    // end style


    s += 'title="Clicca l\'area selezionata per acquistarla !" '

    s += '>'

    // div content
    // end div content

    s += '</div>'
    // end selector
    document.write(s)

    // busy areas
    for(i=0; i<__busyArea; i++) {
      s = ''
      if (__area[i][8] == 0) { // this is a busy area, not a locked one
        s += '<a href="'+__area[i][5]+'" onClick="return bannerClickedNative(\''+__area[i][7]+'\')" '

        s += '> '
        s += '<img src="'+__area[i][6]+'" border="0" '

        s += 'style="position:absolute;left:'+__area[i][0]+';top:'+__area[i][1]+';width:'+__area[i][2]+';height:'+__area[i][3]+' '


        s += '" '
        // end style

        s += 'title="'+__area[i][4]+'" '

        //s += 'width="'+__area[i][2]+'" height="'+__area[i][3]+'" '
        s += '>'
        s += '</a>'
      } else {  // locked areas
        s += '<div '

        s += 'style="position:absolute;left:'+__area[i][0]+';top:'+__area[i][1]+';width:'+__area[i][2]+';height:'+__area[i][3]+'; '
        s += 'margin:0;padding:0;font-size:0pt; '

        //s += ';background:url(\''+__area[i][6]+'\')'

        s += ';background-color:#FFFFFF '
        s += ';filter:alpha(opacity=90);-moz-opacity:0.9; '
        if (__self.IE) s += 'border-width:1px;'; else s += 'border-width:0px;';
        //s += 'border-width:1px';
        s += 'border-style:solid;border-color:#FF0000 '


        s += '" '
        // end style

        s += 'title="'+__area[i][4]+'" '

        s += '>'
        s += '</div>'
        //alert(s)
      }
      document.write(s)
    }
    // end busy areas

  }

  function mouseDown(e) {
    if (!insideSelected(e)) {
      if (insideGrid(e)) {
        __selected = 0

        getSquareCoords()
        if (squareIsFree()) { // set initial position and draw square
          __self.squareCstart = __self.squareC
          __self.squareRstart = __self.squareR
          __self.mouseIsDown = 1
          drawSquare('start')
        } else {
          __self.mouseIsDown = 0
        }
      } else {
        __self.mouseIsDown = 0
      }
    } else {
      buyArea()
    }
  }

  function mouseMove(e) {
    if (__self.mouseIsDown) {
      if (insideGrid(e)) {
        getSquareCoords()
        if (squareIsFree()) {
          if (dimensionOK()) {
            drawSquare()
          }
        }
      } else {
        //alert('outside')
      }
    } else {
      if (insideSelected(e)) {
        //alert('click to buy')
      }
    }
  }

  function mouseUp(e) {
    if (__self.mouseIsDown) {
      if (insideGrid(e)) {
        getSquareCoords()
        if (squareIsFree()) {
          if (dimensionOK()) {
            drawSquare('end')
          }
        }
      } else {
        //alert('outside')
      }
      __self.mouseIsDown = 0
      __selected = 1;
      squareBorder()
    }
  }

  function insideGrid(e) {
    getMouseXY(e)
    if (__self.mouseXpos < getXorigin() || __self.mouseXpos >= getXorigin()+__self.width || __self.mouseYpos < getYorigin() || __self.mouseYpos >= getYorigin() + __self.height) {
      return false
    } else {
      return true
    }
  }

  function insideSelected(e) {
    if (__selected) {
    getMouseXY(e)

    var inizioX = getXorigin() + (__selStartC * __self.colW)
    var inizioY = getYorigin() + (__selStartR * __self.rowH)
    var fineX = getXorigin() + (__selEndC * __self.colW) + __self.colW
    var fineY = getYorigin() + (__selEndR * __self.rowH) + __self.rowH

    if (__self.mouseXpos < inizioX || __self.mouseXpos >= fineX || __self.mouseYpos < inizioY || __self.mouseYpos >= fineY) {
      return false
    } else {
      return true
    }
    } else {
      return false
    }
  }

  function dimensionOK() {
    var wOK = 1
    if (__self.maxWidth != 0) {
      var w = Math.abs(__self.squareC - __self.squareCstart) + 1
      if (w > __self.maxWidth) wOK = 0
    }
    var hOK = 1
    if (__self.maxHeight != 0) {
      var h = Math.abs(__self.squareR - __self.squareRstart) + 1
      if (h > __self.maxHeight) hOK = 0
    }
    return wOK && hOK
  }

  function getMouseXY(e) {
    if (__self.IE) {
      __self.mouseXpos = event.clientX + document.body.scrollLeft
      __self.mouseYpos = event.clientY + document.body.scrollTop
    } else {  // grab the x-y pos.s if browser is NS
      __self.mouseXpos = e.pageX
      __self.mouseYpos = e.pageY
    }
  }

  function getSquareCoords() {
    __self.squareC = parseInt((__self.mouseXpos - getXorigin()) / __self.rowH)
    __self.squareR = parseInt((__self.mouseYpos - getYorigin()) / __self.colW)
  }

  function squareIsFree() { // TODO
    if (__self.mouseIsDown) { // i'm drawing
      // is there busy square inside selected rectangle ??
      var minC = Math.min(__self.squareC, __self.squareCstart)
      var maxC = Math.max(__self.squareC, __self.squareCstart)
      var minR = Math.min(__self.squareR, __self.squareRstart)
      var maxR = Math.max(__self.squareR, __self.squareRstart)

      var foundBusy = false
      var i = 0
      while (i < __busyPoint && !foundBusy) {
        if (__busy[i][1] >= minC && __busy[i][1] <= maxC && __busy[i][0] >= minR && __busy[i][0] <= maxR) foundBusy = true
        else i++
      }

    } else { // initial down point

      var foundBusy = false
      var i = 0
      while (i < __busyPoint && !foundBusy) {
        if (__self.squareC == __busy[i][1] && __self.squareR == __busy[i][0]) foundBusy = true
        else i++
      }
      /*
      if(__self.squareC == 3 && __self.squareR == 3) return false
      else return true
      */
    }

    return !foundBusy

  }

  function drawSquare() {

    var thediv = document.getElementById('square')

    var minC = Math.min(__self.squareC, __self.squareCstart)
    var maxC = Math.max(__self.squareC, __self.squareCstart)
    var minR = Math.min(__self.squareR, __self.squareRstart)
    var maxR = Math.max(__self.squareR, __self.squareRstart)


    var inizioX = getXorigin() + (minC * __self.colW)
    var inizioY = getYorigin() + (minR * __self.rowH)
    var fineX = getXorigin() + (maxC * __self.colW) + __self.colW
    var fineY = getYorigin() + (maxR * __self.rowH) + __self.rowH


    // set selected area

    __selStartR = minR;
    __selStartC = minC;
    __selEndR = maxR;
    __selEndC = maxC;

    thediv.style.background = '#FFA000'
    thediv.style.position = 'absolute'
    thediv.style.left = inizioX
    thediv.style.top = inizioY

    thediv.style.width = fineX - inizioX
    thediv.style.height = fineY - inizioY

    var w = (fineX - inizioX)
    var h = (fineY - inizioY)
    var pxArea = w * h
    var prezzo = pxArea * __self.price
    if (prezzo == 0) prezzo = 'gratis'; else prezzo = prezzo + '€';

    thediv.style.cursor = 'hand'

    thediv.title = 'Clicca l\'area selezionata per acquistarla ! (' + w + ' x ' + h + ' px) '+ prezzo

    if (__self.IE)
      thediv.style.border = '1px dashed #000000';
    else
      thediv.style.border = '0px dashed #000000';

    thediv.style.visibility = 'visible'

  }

  function setBusy(row, col) {
    __busy[__busyPoint] = new Array(row, col)
    __busyPoint++
  }

  function setBusyArea(codbanner, row1, col1, row2, col2, title, url, banner, lock) {
    for(r=row1; r<=row2; r++)
      for (c=col1; c<=col2; c++)
        setBusy(r, c)
    if (url=='') codbanner = 0
    __area[__busyArea] = new Array(col1*__self.colW, row1*__self.rowH, (col2-col1+1)*__self.colW, (row2-row1+1)*__self.rowH, title, url, banner, codbanner, lock)
    __busyArea++
  }

  function buyArea() {
    //parent.outALLmenu()
    var w = (__selEndC - __selStartC + 1) * __self.colW
    var h = (__selEndR - __selStartR + 1) * __self.rowH
    document.location.href = 'bpTestAndLock.php?codgrid='+__self.codgrid+'&row1='+__selStartR+'&col1='+__selStartC+'&row2='+__selEndR+'&col2='+__selEndC+'&w='+w+'&h='+h
  }

  function squareBorder() {
    var thediv = document.getElementById('square')
    if (__self.IE)
      thediv.style.border = '1px dashed #FF0000';
    else
      thediv.style.border = '0px dashed #FF0000';
  }

  /** PUBLIC VARIABLES */
  this.name = name; // string used as object id inside DOM of page
  this.codgrid = codgrid;
  // layout
  this.xPos = 0; // grid up left corner
  this.yPos = 0;
  this.rows = 60;
  this.rowH = 10;
  this.cols = 80;
  this.colW = 10;
  this.width = 800;
  this.height = 600;
  this.maxWidth = 0;
  this.maxHeight = 0;

  // background image
  this.bckImage = ''

  // grid pixel price
  this.price = 0

  // browse stuff
  this.IE = document.all?true:false;

  // mouse position
  this.mouseXpos = 0;
  this.mouseYpos = 0;
  this.mouseIsDown = 0;

  // square coordinates
  this.squareR = 0; // current position during a draw
  this.squareC = 0;
  this.squareRstart = 0; // initial position during a draw
  this.squareCstart = 0;

  /** DECLARATION OF ALL PUBLIC METHODS */
  this.drawGrid = drawGrid;
  this.setBckImage = setBckImage;
  this.setRows = setRows;
  this.setCols = setCols;
  this.setRowHeight = setRowHeight;
  this.setColWidth = setColWidth;
  this.setPrice = setPrice;
  this.setOriginXY = setOriginXY;
  this.setBusy = setBusy;
  this.setBusyArea = setBusyArea;
  this.setMaxWidth = setMaxWidth;
  this.setMaxHeight = setMaxHeight;
  this.setGridLayout = setGridLayout;

  this.buyArea = buyArea;

  /** DECLARATION OF ALL PRIVATE METHODS */
  this.insideGrid = insideGrid;
  this.insideSelected = insideSelected;
  this.getMouseXY = getMouseXY;
  this.mouseDown = mouseDown;
  this.mouseMove = mouseMove;
  this.mouseUp = mouseUp;
  this.getSquareCoords = getSquareCoords;
  this.squareIsFree = squareIsFree;
  this.drawSquare = drawSquare;
  this.dimensionOK = dimensionOK;
  this.squareBorder = squareBorder;
  this.getXorigin = getXorigin;
  this.getYorigin = getYorigin;

  /** PRIVATE VARIABLES */
  var __self = this;
  // occupied space
  var __busy = new Array(); // row, column
  var __area = new Array(); // x, y, width, height, title, url, banner, codbanner, lock
  var __busyPoint = 0;
  var __busyArea = 0;
  // selected area coords
  var __selStartR = 0;
  var __selStartC = 0;
  var __selEndR = 0;
  var __selEndC = 0;

  // flag selected
  var __selected = 0;

};

