function createRequestObject() {
  try {
    request_o = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (ex) {
    //either this is not IE, or it is a version of IE which does not support XMLHTTP
    var notIECompatibleXMLHTTP = true;
  }

  if (notIECompatibleXMLHTTP == true) {
    try {
      request_o = new XMLHttpRequest();
    } catch (ex) {
      //we can't use AJAX because this browser is not compatible.
      request_o = false;
    }
  }
  return request_o;
}

var http = createRequestObject();

boxFull = false;
alreadyAdded = 0;
var output;

function selectBox(str){
  var chocBoxID = new Array();
  chocBoxID[3] = "Box3";
  chocBoxID[6] = "Box6";
  chocBoxID[15] = "Box15";
  chocBoxID[35] = "Box35";
  
  currentbox = chocBoxID[str];
  if (str == '35') {
    productId = 4;
  } else if (str == '15') {
    productId = 3;
  } else if (str == '6') {
    productId = 2;
  } else if (str == '3') {
    productId = 1;
  }
}

tableReference = new Array();
tableReference['Box15'] = 3;
tableReference['Box35'] = 7;
tableReference['Box6'] = 2;
tableReference['Box3'] = 1;

tableCols = new Array();
tableCols['Box15'] = 5;
tableCols['Box35'] = 5;
tableCols['Box6'] = 3;
tableCols['Box3'] = 3;

numberofChocs = new Array();
chocCount = numberofChocs['Box35'] = 35;
chocCount = numberofChocs['Box15'] = 15;
chocCount = numberofChocs['Box6'] = 6;
chocCount = numberofChocs['Box3'] = 3;

var transfer;
var chocCounter = 0;

function addChoc (str, attributeId, zenid) {
  if(chocCounter == chocCount){
    alert('Your box is full\nPlease click "Add to Cart"\n(Button at the bottom of the page)');
    // clear $_SESSION['choc_added_id']
    clear_choc_added_id();
    boxFull = true;
    document.getElementById('image_submit').disabled = false;
    return;
  } // end if (imgLen == chocCount){

  selectBox(str);
  transfer = "Ready"; // reset transfer for next addition
  // split attributeId
  attrArray = attributeId.split("-");
  chocCount = numberofChocs[currentbox]; // total of chocs that fit in box

  var TargetTable = document.getElementById(currentbox);
  var rowCount = tableReference[currentbox];
  var colCount = tableCols[currentbox];

  // get col num
  for (var i = 1; i <= rowCount; i++) {
    var TargetCell = TargetTable.rows.item(i); // row element

    colsLength = TargetCell.cells.length;
    for (var j = 0; j < colsLength; j++) {
      cellContent = TargetCell.cells[j].innerHTML; // content of cell
      if(transfer == "done"){
        break;
      }
      if(cellContent == "Slot empty"){
        // need to work out if 2 cells remain
        slotsTaken = ((i-1) * colCount) + j;

        var sendHtml = '<a href="javascript:removeChoclate(\'command\')">';

        // get right img
        // get into anchor
        rightAnchor = document.getElementById("divImg" + attributeId).getElementsByTagName('a');
        rightImg = rightAnchor[0].innerHTML;
        sendHtml +=  rightImg;
        sendHtml += '</a><input type="hidden" name="id[' + attrArray[0] + '][' + attrArray[1] + ']" value="' + attrArray[1] + '" id="attrib-' + attributeId + '" />';
//        alert("i: " + i + ", j: " + j + ", chocCount: " + chocCount + ", slotsTaken : " + slotsTaken);
//        alert("prod_id: " + attrArray[0] + "  attrib_id: " + attrArray[1]);
        // add choc to 2 slots if attributeId = 1-2

        if (attrArray[1] == '2') {
//					alert(chocCount + ':- ' + typeof(chocCount));
          if (chocCount == 35 && alreadyAdded == 2) {
            alert("Only two chocolate of this type per box please...");
						return;
          } else if (chocCount != 35 && alreadyAdded == 1) {
            alert("Only one chocolate of this type per box please...");
						return;
          } else {
            alreadyAdded ++;
          }
        }
/*
        if (attrArray[1] == '2') {
//          if (chocCount - slotsTaken < 2) {
//            alert('This item takes 2 slots, there is not enough space for it. \nPlease remove an item and then add it, or choose another item.');
//            return;
//          }
          cellId1 = TargetCell.cells[j].id
          cellContent.innerHTML = sendHtml;
          //addAttributeToCart2(productId, attributeId, sendHtml, i, j, currentbox, cellId, colCount, rowCount, zenid);
          i1 = i;
          j1 = j;

          j++;

          if (j >= colsLength) { // start on new row
            i++;
            TargetCell = TargetTable.rows.item(i);
            j = 0;
            cellId2 = TargetCell.cells[j].id
            cellContent.innerHTML = sendHtml;
            i2 = i;
            j2 = j;
            addAttributeToCart2(productId, attributeId, sendHtml, i1, j1, i2, j2, currentbox, cellId1, cellId2, colCount, rowCount, zenid);
//            setCellHTML(i, j, currentbox, cellId, sendHtml, colCount, rowCount);
            transfer = "done";
          } else {
            cellId2 = TargetCell.cells[j].id
            cellContent.innerHTML = sendHtml;
            i2 = i;
            j2 = j;
            addAttributeToCart2(productId, attributeId, sendHtml, i1, j1, i2, j2, currentbox, cellId1, cellId2, colCount, rowCount, zenid);
//            setCellHTML(i, j, currentbox, cellId, sendHtml, colCount, rowCount);
            transfer = "done";
          }
*/

//        } else { // any choc/truffle but not the one that takes 2 slots
          cellId = TargetCell.cells[j].id
          cellContent.innerHTML = sendHtml;
//          alert(cellContent);
          addAttributeToCart(productId, attributeId, sendHtml, i, j, currentbox, cellId, colCount, rowCount, zenid);
//          alert(output);
//          setCellHTML(i, j, currentbox, cellId, sendHtml, colCount, rowCount);
          transfer = 'done';
//        }
        // update cart session
//        alert("pId = " +productId + " and attrId = " + attributeId + " and sendHtml = " + sendHtml);
      } // end if(cellContent == "Slot empty")
    } // end col loop
  } // end row loop
  var tableElem = document.getElementById(currentbox); // table element
  var imgLen = tableElem.getElementsByTagName('img').length // number of images in table
//alert(chocCounter);

  if(chocCounter == chocCount){
    alert('Your box is full\nPlease click "Add to Cart"\n(Button at the bottom of the page)');
    // clear $_SESSION['choc_added_id']
    clear_choc_added_id();
    boxFull = true;
    document.getElementById('image_submit').disabled = false;
  } // end if (imgLen == chocCount){
  transfer = "";
}

function setCellHTML(rowNum, colNum, str, cellId, sendHtml, colCount, rowCount) {
  var tableElem = document.getElementById(cellId);

  document.getElementById(cellId).innerHTML = sendHtml;

  var updatedHTML = sendHtml.replace(/command/g, cellId);
  var targetCell = tableElem;
  targetCell.innerHTML = updatedHTML;
}

function removeChoclate(str){

  // search for next/last cell and remove double sized choc

  var TargetTable = document.getElementById(currentbox);
  var rowCount = tableReference[currentbox];
  var colCount = tableCols[currentbox];

  currentId = str.substr(cellId.indexOf('cell') + 4, 2) ;

  // split currentId into rowNum and colNum
  currentRowNum = currentId.substr(0, 1);
  currentColNum = currentId.substr(1, 1);

  nextId = parseInt(currentId) + 1;
  lastId = parseInt(currentId) - 1;

  if (nextId % 10 > colCount) { // look in next row
    nextId = "" + (currentRowNum + 1) + "1";
    if (Math.floor(nextId / 10) > rowCount) {
      nextId = null;
    }
  }

  if ((lastId % 10) == 0) { // look in last row
    lastId = (parseInt(currentId) - 10) + colCount - 1;
    if (parseInt(lastId) < 10) {
      lastId = null;
    }
  }

  // see if boyenberry & whisky is next or last and remove
  if (nextId != null) {
    nextHTML = document.getElementById("cell" + nextId).innerHTML;
    //alert(nextHTML.indexOf('Boysenberry and Whisky'));
    if (nextHTML.indexOf('Boysenberry and Whisky') > 0) {

      var emptyCell = "Slot empty";
      document.getElementById("cell" + nextId).innerHTML = emptyCell;

      var tableElem = document.getElementById(currentbox);
      var imgLen = tableElem.getElementsByTagName('img').length;
    }
  }

  if (lastId != null) {
    lastHTML = document.getElementById("cell" + lastId).innerHTML;
//alert(lastHTML.indexOf('Boysenberry and Whisky'));
    if (lastHTML.indexOf('Boysenberry and Whisky') > 0) {
      var emptyCell = "Slot empty";
      document.getElementById("cell" + lastId).innerHTML = emptyCell;

      var tableElem = document.getElementById(currentbox);
      var imgLen = tableElem.getElementsByTagName('img').length;
    }
  }
  // get product_id and attribute_id
  cellHTML = document.getElementById("cell" + currentId).innerHTML;
  product_id = parseInt(cellHTML.substr(cellHTML.indexOf('attrib-') + 7, 2));
  attribute_id = parseInt(cellHTML.substr(cellHTML.lastIndexOf('-') + 1, 2));
  // remove correct choc from products_attributes_cart
  removeAttributeToCart(product_id, attribute_id);

  var emptyCell = "Slot empty";
  document.getElementById(str).innerHTML = emptyCell;

  var tableElem = document.getElementById(currentbox);
  var imgLen = tableElem.getElementsByTagName('img').length;
}

function addAttributeToCart(productId, attributeId, sendHtml, i, j, currentbox, cellId, colCount, rowCount, zenid) {
  http.abort();

  http.open('GET', 'AddAttributesToCart.php?productId=' + productId + '&attributeId=' + attributeId + '&sendHtml=' + strip_tags(sendHtml, null) + '&zenid=' + zenid, true);
  http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  http.send(null);
  //alert('productId=' + productId + '&attributeId=' + attributeId + '&sendHtml=' + sendHtml);
  http.onreadystatechange = function() {
    if (http.readyState == 4 && http.status == 200) {
      //alert('here')
      callbackFunction(http.responseText, i, j, currentbox, cellId, sendHtml, colCount, rowCount);
    }
  }
}

function callbackFunction(input, i, j, currentbox, cellId, sendHtml, colCount, rowCount) {
//  alert(input);
  if (input == 'Done') {
    setCellHTML(i, j, currentbox, cellId, sendHtml, colCount, rowCount);
    chocCounter++;
    if(chocCounter == chocCount){
      alert('Your box is full\nPlease click "Add to Cart"\n(Button at the bottom of the page)');
      // clear $_SESSION['choc_added_id']
      clear_choc_added_id();
      boxFull = true;
      document.getElementById('image_submit').disabled = false;
    } // end if (imgLen == chocCount){
  }
}

function callbackFunction2(input, i1, j1, i2, j2, currentbox, cellId1, cellId2, sendHtml, colCount, rowCount) {
//  alert(input);
  if (input == 'Done') {
    setCellHTML(i1, j1, currentbox, cellId1, sendHtml, colCount, rowCount);
    chocCounter++;
    setCellHTML(i2, j2, currentbox, cellId2, sendHtml, colCount, rowCount);
    chocCounter++;
    if(chocCounter == chocCount) {
      alert('Your box is full\nPlease click "Add to Cart"\n(Button at the bottom of the page)');
      // clear $_SESSION['choc_added_id']
      clear_choc_added_id();
      boxFull = true;
      document.getElementById('image_submit').disabled = false;
    } // end if (imgLen == chocCount){
  }
}

function addAttributeToCart2(productId, attributeId, sendHtml, i1, j1, i2, j2, currentbox, cellId1, cellId2, colCount, rowCount, zenid) {
  http.abort();

  http.open('GET', 'AddAttributesToCart2.php?productId=' + productId + '&attributeId=' + attributeId + '&sendHtml=' + strip_tags(sendHtml, null) + '&zenid=' + zenid, true);
  http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  http.send(null);
  //alert('productId=' + productId + '&attributeId=' + attributeId + '&sendHtml=' + sendHtml);
  http.onreadystatechange = function() {
    if (http.readyState == 4 && http.status == 200) {
      //alert('here')
      callbackFunction2(http.responseText, i1, j1, i2, j2, currentbox, cellId1, cellId2, sendHtml, colCount, rowCount);
    }
  }
}


function removeAttributeToCart(productId, attributeId) {
  http.abort();

  http.open('GET', 'RemoveAttributesFromCart.php?productId=' + productId + '&attributeId=' + attributeId, true);
  http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  http.send(null);

  http.onreadystatechange = function() {
    if (http.readyState == 4 && http.status == 200) {
      var response = http.responseText;
      if (response == 'Done') {
        // all good, stored
        //alert(response);
			} else {
        //alert(response);
      }
    }
  }
}

function clear_choc_added_id() {
  http.abort();

  http.open('GET', 'clear_choc_added_id.php', true);
  http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  http.send(null);

  http.onreadystatechange = function() {
    if (http.readyState == 4 && http.status == 200) {
      var response = http.responseText;
      if (response == 'Done') {
        // all good, session destoyed
        //alert(response);
			}
    }

  }
}

function strip_tags(str, allowed_tags) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Alex
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Marc Palau
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brettz9.blogspot.com)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Eric Nagel
    // +      input by: Bobby Drake
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
    // *     example 4: strip_tags('1 < 5 5 > 1');
    // *     returns 4: '1 < 5 5 > 1'
 
    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';
 
    var replacer = function(search, replace, str) {
        return str.split(search).join(replace);
    };
 
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
    }
  
    str += '';
 
    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
 
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
 
        // Save HTML tag
        html = matches[key].toString();
 
        // Is tag not in allowed list? Remove from str!
        allowed = false;
 
        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;
 
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
 
            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }
 
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
 
    return str;
}
function pause(ms) {
  var date = new Date();
  var currDate = null;
  do { currDate = new Date(); }
  while ( currDate < ms );
}
