var hr = '<hr size="1"  style="height:1px;border-width:0;color:gray;background-color:gray" />';

function createXmlHttpRequest() {
  var xmlHttp = null;
  // Create the HttpRequest - abort if not possible
  try {
    xmlHttp = new XMLHttpRequest();  // Firefox, Opera 8.0+, Safari, IE7
  }
  catch(e) {
    try {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // Old IE
    }
    catch(e) {
      showAlert('Warning', 'Your browser does not allow webpage editing. We recommend that you use an up-to-date version of Firefox, downloadable from www.mozilla.com/firefox/');
      return null;
    }
  }
  return xmlHttp;
}

function restoreArchive() {
  var fileName = document.sel_backup_form.backupf.value;
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", 'do_restore.php', true);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        var resp = xmlHttp.responseText;
        if (resp == 'OK') {
          showAlert('Information', 'Your site content has been restored.');
        }
        else {
          showAlert('Error', 'Your site content could not be restored. Please try again later.');
        }
      }
      else {
        showAlert('Error', 'The server did not respond. This may be due to a temporary internet problem, so please try again later, but do let us know if the problem persists!');
      }
    }
  }
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send('archive=' + fileName);
}

function doBackup() {
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", 'do_backup.php', true);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        var resp = xmlHttp.responseText;
        if (resp == 'OK') {
          showAlert('Information', 'Your site content has been backed up.');
        }
        else {
          showAlert('Error', 'Your site content could not be backed up. Please try again later.');
        }
      }
      else {
        showAlert('Error', 'The system is not responding to your request.');
      }
    }
  }
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send(null);
}

// This function can be used to ensure that a domain either is or is not
// available, by issuing a whois command on the server. The argument (req)
// determines the polarity of the result. If req is true (the domain is
// required) the function will return true if the domain is available and false
// otherwise. If req is false (the domain is already owned, for example) the
// function will return true if the domain is not available and false
// otherwise. The remaining arguments specify the messages to be returned in an
// alert box depending on whether the result is true or false. If either of
// these arguments has the value false no message is displayed for that case.
function checkDomainAvailable(req, domain, msgSucceed, msgFail) {
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", 'do_whois.php', true);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        var resp = xmlHttp.responseText;
        if (resp == 'OK') { // available
          if (req) {
            if (msgSucceed) {
              showAlert('Information', msgSucceed);
            }
            return true;
          } else {
            if (msgFail) {
              showAlert('Error', msgFail);
            }
            return false;
          }
        } else { // unavailable
          if (req) {
            if (msgFail) {
              showAlert('Error', msgFail);
            }
            return false;
          } else {
            if (msgSucceed) {
              showAlert('Information', msgSucceed);
            }
            return true;
          }
        }
      }
      else {
        showAlert('Error', 'The server did not respond. This may be due to a temporary internet problem, so please try again later, but do let us know if the problem persists!');
      }
    }
  }
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send(null);
}

function checkDomain(nname) {
  var arr = new Array(
    '.com','.net','.org','.biz','.coop','.info','.museum','.name',
    '.pro','.edu','.gov','.int','.mil','.ac','.ad','.ae','.af','.ag',
    '.ai','.al','.am','.an','.ao','.aq','.ar','.as','.at','.au','.aw',
    '.az','.ba','.bb','.bd','.be','.bf','.bg','.bh','.bi','.bj','.bm',
    '.bn','.bo','.br','.bs','.bt','.bv','.bw','.by','.bz','.ca','.cc',
    '.cd','.cf','.cg','.ch','.ci','.ck','.cl','.cm','.cn','.co','.cr',
    '.cu','.cv','.cx','.cy','.cz','.de','.dj','.dk','.dm','.do','.dz',
    '.ec','.ee','.eg','.eh','.er','.es','.et','.fi','.fj','.fk','.fm',
    '.fo','.fr','.ga','.gd','.ge','.gf','.gg','.gh','.gi','.gl','.gm',
    '.gn','.gp','.gq','.gr','.gs','.gt','.gu','.gv','.gy','.hk','.hm',
    '.hn','.hr','.ht','.hu','.id','.ie','.il','.im','.in','.io','.iq',
    '.ir','.is','.it','.je','.jm','.jo','.jp','.ke','.kg','.kh','.ki',
    '.km','.kn','.kp','.kr','.kw','.ky','.kz','.la','.lb','.lc','.li',
    '.lk','.lr','.ls','.lt','.lu','.lv','.ly','.ma','.mc','.md','.mg',
    '.mh','.mk','.ml','.mm','.mn','.mo','.mp','.mq','.mr','.ms','.mt',
    '.mu','.mv','.mw','.mx','.my','.mz','.na','.nc','.ne','.nf','.ng',
    '.ni','.nl','.no','.np','.nr','.nu','.nz','.om','.pa','.pe','.pf',
    '.pg','.ph','.pk','.pl','.pm','.pn','.pr','.ps','.pt','.pw','.py',
    '.qa','.re','.ro','.rw','.ru','.sa','.sb','.sc','.sd','.se','.sg',
    '.sh','.si','.sj','.sk','.sl','.sm','.sn','.so','.sr','.st','.sv',
    '.sy','.sz','.tc','.td','.tf','.tg','.th','.tj','.tk','.tm','.tn',
    '.to','.tp','.tr','.tt','.tv','.tw','.tz','.ua','.ug','.uk','.um',
    '.us','.uy','.uz','.va','.vc','.ve','.vg','.vi','.vn','.vu','.ws',
    '.wf','.ye','.yt','.yu','.za','.zm','.zw'
  );

  var mai = nname;
  var val = true;

  var dot = mai.lastIndexOf(".");
  var dname = mai.substring(0,dot);
  var ext = mai.substring(dot,mai.length);
//alert(ext);

  if (dot > 2 && dot < 57) {
    for (var i = 0; i < arr.length; i++) {
      if (ext == arr[i]) {
        val = true;
        break;
      } else {
        val = false;
      }
    }
    if (val == false) {
      alert("Your domain extension " + ext + " is not correct");
      return false;
    } else {
      for (var j = 0; j < dname.length; j++) {
        var dh = dname.charAt(j);
        var hh = dh.charCodeAt(0);
        if ((hh > 47 && hh < 59) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123) || hh == 45 || hh == 46) {
          if ((j == 0 || j == dname.length - 1) && hh == 45) {
            alert("Domain names cannot begin or end with '-'");
            return false;
          }
        } else  {
          alert("Your domain name should not have special characters");
          return false;
        }
      }
    }
  } else {
    alert("The domain name is too short or too long");
    return false;
  }

  return true;
}


function updatePassword() {
  // Attempt to change the password as requested, giving the current username
  // and password as entered for verification
  var userName = document.login_details_form.username.value.trim();
  var xDisp = 175;
  var yDisp = -40;
  if (userName.length == 0) {
    showAlert('Error', 'You did not enter a user name. Please correct this error and try again!', 'btn_new_pwd', xDisp, yDisp);
    return false;
  }
  var curPwd = document.login_details_form.cur_pwd.value.trim();
  if (curPwd.length == 0) {
    showAlert('Error', 'You did not enter your current password. Please correct this error and try again!', 'btn_new_pwd', xDisp, yDisp);
    return false;
  }
  var newPwd = document.login_details_form.new_pwd.value.trim();
  if (newPwd.length == 0) {
    showAlert('Error', 'You did not enter a new password. Please correct this error and try again!', 'btn_new_pwd', xDisp, yDisp);
    return false;
  }
  var confnewPwd = document.login_details_form.conf_new_pwd.value.trim();
  if (confnewPwd.length == 0) {
    showAlert('Error', 'You did not confirm the new password. Please correct this error and try again!', 'btn_new_pwd', xDisp, yDisp);
    return false;
  }
  if (confnewPwd != newPwd) {
    showAlert('Error', 'You entered different passwords each time. Please correct this error and try again!', 'btn_new_pwd', xDisp, yDisp);
    return false;
  }
  args  = 'username=' + userName;
  args += '&curpwd=' + curPwd;
  args += '&newpwd=' + newPwd;
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", 'do_update_pwd.php', true);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        var resp = xmlHttp.responseText;
        if (resp == 'OK') {
          showAlert('Information', 'Your password has been changed as requested.', 'btn_new_pwd', xDisp, yDisp);
        }
        else {
          showAlert('Error', '<p class="red"><strong>' + resp + '</strong></p>', 'btn_new_pwd', xDisp, yDisp);
        }
      }
      else {
        showAlert('Error', '<p class="red"><strong>The server could not be accessed for this operation. This may be due to a temporary internet problem, so please try again later, but do let us know if the problem persists!</strong></p>', 'btn_new_pwd', xDisp, yDisp);
      }
    }
  }
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send(args);
}

function validateEmail(emailAddr, fieldName) {
  if (emailAddr.length == 0) {
    showAlert('Error', 'Please enter a ' + fieldName + ' and try again!');
    return false;
  } else {
    var apos = emailAddr.indexOf("@");
    var dotpos = emailAddr.lastIndexOf(".");
    if (apos < 1 || dotpos - apos < 2) {
      showAlert('Error', 'The ' + fieldName + ' you entered was not valid. Please correct this error and try again!');
      return false;
    }
  }
  return true;
}

function validateSiteData() {
  var siteName = document.site_generator_form.site_name.value;
  //alert('siteName = ' + siteName);
  //return false;
  siteName = document.site_generator_form.site_name.value.trim();
  if (siteName.length == 0) {
    showAlert('Error', 'Please enter a site title and try again!');
    document.site_generator_form.site_name.focus();
    return false;
  } else if (siteName.length > 255) {
    showAlert('Error', 'Please use a site name that is less than 256 characters long!');
    document.site_generator_form.site_name.focus();
    return false;
  }
  var siteType = document.site_generator_form.site_type.value.trim();
  if (siteType != 'ec1' && siteType != 'ec2' && siteType != 'ec3') {
    showAlert('Error', 'Your data is invalid - please check that your computer and browser are functioning correctly');
    return false;
  }
  var curPwd = document.site_generator_form.pwd.value.trim();
  if (curPwd.length < 8) {
    showAlert('Error', 'Your site-access password must contain at least eight characters. Please try again!');
    document.site_generator_form.pwd.focus();
    return false;
  }
  var emailAddr= document.site_generator_form.email_addr.value.trim();
  if (!validateEmail(emailAddr, 'contact email address')) {
    document.site_generator_form.email_addr.focus();
    return false;
  }
  var firstName = document.site_generator_form.first_name.value.trim();
  if (firstName.length == 0) {
    showAlert('Error', 'Please enter your first name and try again!');
    document.site_generator_form.first_name.focus();
    return false;
  } else if (firstName.length > 255) {
    showAlert('Error', 'Please use a first name that is less than 256 characters long!');
    document.site_generator_form.first_name.focus();
    return false;
  }
  var lastName = document.site_generator_form.last_name.value.trim();
  if (lastName.length == 0) {
    showAlert('Error', 'Please enter your last name and try again!');
    document.site_generator_form.last_name.focus();
    return false;
  } else if (lastName.length > 255) {
    showAlert('Error', 'Please use a last name that is less than 256 characters long!');
    document.site_generator_form.last_name.focus();
    return false;
  }
  var addr1 = document.site_generator_form.addr_1.value.trim();
  if (addr1.length == 0) {
    showAlert('Error', 'Please enter the first line of your address and try again!');
    document.site_generator_form.addr_1.focus();
    return false;
  } else if (addr1.length > 100) {
    showAlert('Error', 'Please enter your address with no more than 100 characters in the first line!');
    document.site_generator_form.addr_1.focus();
    return false;
  }
  var addr2 = document.site_generator_form.addr_2.value.trim();
  if (addr2.length > 100) {
    showAlert('Error', 'Please enter your address with no more than 100 characters in the second line!');
    document.site_generator_form.addr_2.focus();
    return false;
  }
  var addr3 = document.site_generator_form.addr_3.value.trim();
  if (addr3.length > 100) {
    showAlert('Error', 'Please enter your address with no more than 100 characters in the third line!');
    document.site_generator_form.addr_3.focus();
    return false;
  }
  var country = document.site_generator_form.country.value.trim();
  if (country.length == 0) {
    showAlert('Error', 'Please enter your country and try again!');
    return false;
  } else if (country.length > 100) {
    showAlert('Error', 'Please enter your country using no more than 100 characters!');
    document.site_generator_form.country.focus();
    return false;
  }

  var postcode = document.site_generator_form.postcode.value.trim();
  if (postcode.length == 0) {
    showAlert('Error', 'Please enter your postcode or zip code and try again!');
    return false;
  } else if (postcode.length > 10) {
    showAlert('Error', 'Please enter a valid postcode');
    document.site_generator_form.postcode.focus();
    return false;
  }

  var accepted = document.site_generator_form.cbx_tandc.checked;
  if (accepted == false) {
    showAlert('Error', 'Please indicate your agreement to the Terms and Conditions before continuing.');
    document.site_generator_form.cbx_tandc.focus();
    return false;
  }

  return true;
}

function cloneIt() {
  var userName = document.site_clone_form.username.value.trim();
  if (userName.length == 0) {
    showAlert('Error', 'You did not enter your user name. Please correct this error and try again!');
    return false;
  }
  var curPwd = document.site_clone_form.pwd.value.trim();
  if (curPwd.length == 0) {
    showAlert('Error', 'You did not enter your password. Please correct this error and try again!');
    return false;
  }
  var siteName = document.site_clone_form.site_name.value.trim();
  if (siteName.length == 0) {
    showAlert('Error', 'You did not enter a site name. Please correct this error and try again!');
    return false;
  }
  var emailAddr= document.site_clone_form.email_addr.value.trim();
  if (emailAddr.length == 0) {
    showAlert('Error', 'You did not enter the webmaster\'s email address. Please correct this error and try again!');
    return false;
  }
  var firstName = document.site_clone_form.first_name.value.trim();
  if (firstName.length == 0) {
    showAlert('Error', 'You did not enter the webmaster\'s first name. Please correct this error and try again!');
    return false;
  }
  var lastName = document.site_clone_form.last_name.value.trim();
  if (lastName.length == 0) {
    showAlert('Error', 'You did not enter the webmaster\'s last name. Please correct this error and try again!');
    return false;
  }
  var addr1 = document.site_clone_form.addr_1.value.trim();
  if (addr1.length == 0) {
    showAlert('Error', 'You did not enter the first line of the webmaster\'s address. Please correct this error and try again!');
    return false;
  }
  var addr2 = document.site_clone_form.addr_2.value.trim();
  var addr3 = document.site_clone_form.addr_3.value.trim();
  var country = document.site_clone_form.country.value.trim();
  if (country.length == 0) {
    showAlert('Error', 'You did not enter the webmaster\'s country. Please correct this error and try again!');
    return false;
  }
  var postcode = document.site_clone_form.postcode.value.trim();
  if (postcode.length == 0) {
    showAlert('Error', 'You did not enter the webmaster\'s postcode.\nPlease correct this error and try again!\n\nIf the address does not have a postcode, please enter \'NONE\'');
    return false;
  }

  document.site_clone_form.btn_clone_it.disabled = true;

  var args = 'username=' + userName;
  args += '&pwd=' + curPwd;
  args += '&site_name=' + siteName;
  args += '&email_addr=' + emailAddr;
  args += '&first_name=' + firstName;
  args += '&last_name=' + lastName;
  args += '&addr_1=' + addr1;
  args += '&addr_2=' + addr2;
  args += '&addr_2=' + addr3;
  args += '&country=' + country;
  args += '&postcode=' + postcode;

  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", 'clone_site.php', true);
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        var resp = xmlHttp.responseText;
        if (resp == 'OK') {
          showAlert('Information', 'Ths site has now been cloned.');
          document.site_clone_form.btn_clone_it.disabled = false;
        }
        else {
          showAlert('Error', resp);
          document.site_clone_form.btn_clone_it.disabled = false;
        }
      }
      else {
        showAlert('Error', 'The server could not be accessed for this operation. This may be due to a temporary internet problem, so please try again later, but do let us know if the problem persists!');
      }
    }
  }
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send(args);
}

// --------------------------------------------
// The next two functions require mytinybox.js
// --------------------------------------------

function addToBasket(productId) {
  //alert('addToBasket(' + productId + ')');
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", 'add_to_basket.php', true);
  var qty =  document.getElementById('qty_' + productId).value;
  //alert('qty = ' + qty);
  // Get subproduct id
  //var selector = window.frames[0].document.getElementById('subprod_id_' + productId);
  var selector =  document.getElementById('subprod_id_' + productId);
  var subproduct_id = false;
  if (selector) {
    subproduct_id = selector.value;
  }
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        var resp = xmlHttp.responseText;
        if (resp != 'FAIL') {
          parent.TINY.page.showAlert('Basket updated', resp);
          //alert(resp);  // temporary
          basketSummary = document.getElementById('basket_summary');
          basketSummary.innerHTML = '<a href="index.php?379" target="_top">' + resp + '</a>';
          if (itemQty[productId] == undefined) {
            itemQty[productId] = 0;
          }
          itemQty[productId] = parseInt(itemQty[productId]) + parseInt(qty);
          // Restore the quantity field to one
          document.getElementById('qty_' + productId).value = '1'
        }
      }
      else {
      }
    }
  }
  var args = 'product_id=' + productId + '&qty=' + qty;
  if (subproduct_id) {
    args = args + '&subproduct_id=' + subproduct_id;
  }
  //alert('args = ' + args);
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send(args);
}

//function addBundleToBasket(productId) {

/*
 * Add each item in the bundle to the basket.
 */
function addBundleToBasket(optionsList) {

  //alert('optionsList = ' + optionsList);
  var idList = optionsList.split(',');

  /*
   * The first item in the list is the id of the parent product
   */
  var bundleId = idList[0];
  //alert('bundleId = ' + bundleId);

  /*
   * Check each of the remaining items in the list to see if there's a
   * corresponding subproduct_id and if so use that instead of the item.
   */
  var i;
  var newoptionsList = bundleId;
  for (i = 1; i < idList.length; i++)
  {
    //alert('Checking for subprod_id_' + idList[i]);
    newoptionsList += ',';
    var selector =  document.getElementById('subprod_id_b_' + idList[i]);
    if (selector) {
      newoptionsList += selector.value;
    }
    else
    {
      newoptionsList += idList[i];
    }

    //alert('optionsList = ' + optionsList + ', newoptionsList = ' + newoptionsList);
  }

  /*
   * Get server connection
   */
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", 'add_bundle_to_basket.php', true);

  /*
   * Handler function
   */
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        var resp = xmlHttp.responseText;
        if (resp == 'INVALID')
        {
          alert("Error: invalid items")
        }
        else
        {
          parent.TINY.page.showAlert('Basket updated', resp);
          basketSummary = document.getElementById('basket_summary');
          basketSummary.innerHTML = '<a href="index.php?379" target="_top">' + resp + '</a>';

          //alert(resp);

          /*
           * We now need to get all the items and their subproducts again and
           * set their quantities to 1. The following code need updating
           * accordingly
          if (itemQty[productId] == undefined) {
            itemQty[productId] = 0;
          }
          itemQty[productId] = parseInt(itemQty[productId]) + parseInt(qty);
          // Restore the quantity field to one
          // document.getElementById('qty_' + productId).value = '1'
           */
        }
      }
      else {
      }
    }
  }

  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  var args = 'bundle_id=' + bundleId + '&qty=1&options=' + newoptionsList;
  //alert('Calling add_bundle_to_basket.php?' + args);
  xmlHttp.send(args);
}

function clearBasket() {
  //alert('clearBasket called');
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", '/clear_basket.php', true);
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send(null);
}

var itemName = new Array();
var itemQty = new Array();
var itemUnitPrice = new Array();
var itemVAT = new Array();
var itemUnitDelCharge = new Array();
var fixedCharge = 0;

/*
 * This has now been adapted to allow for bundles (first argument). Other
 * changes will also be required. We now use a composite of the bundle id (zero
 * for non-bundled items) and the product (or sub-product) ids so we can cope
 * with bundles. This id also has to beused in the input fields. Hopefully no
 * other JS changes will be needed.
 */
function initItem(bundleId, itemId, prodName, unitPrice, vat, qty, unitDelCharge) {
  //alert('initItem: itemId = ' + itemId + ', prodName = ' + prodName + ', unitPrice = ' + unitPrice + ', vat = ' + vat + ', qty = ' + qty + ', unitDelCharge = ' + unitDelCharge);
  itemName[bundleId + '.' + itemId] = prodName;
  itemQty[bundleId + '.' + itemId] = qty;
  itemVAT[bundleId + '.' + itemId] = vat;
  itemUnitPrice[bundleId + '.' + itemId] = unitPrice;
  itemUnitDelCharge[bundleId + '.' + itemId] = unitDelCharge;
}

function getTotalPrice(b2c) {
  var i;
  var tot = 0;
  for (i in itemQty) {
    if (itemQty[i] > 0) {
      var p = itemUnitPrice[i];
      if (b2c) {
        p = parseFloat(p) + itemVAT[i];
      }
      tot += parseInt(itemQty[i]) * p;
    }
  }
  return tot.toFixed(2);
}

function changeQty(
                   id, // (can be negative)
                   b2c // include VAT in display if true
                  )
{
  // alert('changeQty: id = ' + id + ', b2c = ' + b2c);
  // Get entered quantity from DOM
  var qty = document.getElementById('qty[' + id + ']').value.trim();

  // If not valid, treat as zero
  if (qty.length == 0 || qty.length > 5 || isNaN(qty)) {
    qty = 0;
  }

  // Update quantity for this id
  itemQty[id] = qty;

  // Calculate new price
  var item_price = parseInt(qty) * itemUnitPrice[id];
  var item_display_price = item_price;

  // Include VAT if B2C
  if (b2c) {
    var item_vat = parseInt(qty) * itemVAT[id];
    item_display_price = parseFloat(item_display_price) + item_vat;
  }

  // Update the display for price and total price
  document.getElementById('itemPrice[' + id + ']').innerHTML = item_display_price.toFixed(2);
  document.getElementById('totalPrice').innerHTML = getTotalPrice(b2c);

  /*
   * The remaining updates seem to be a legacy from the situation before we
   * split the checkout into two stages, and items were sent to Paypal in
   * sequence order. The Paypal posting is now just a summary and I think they
   * are redundant. Fields with the given ids no longer exist so the code
   * has been removed to prevent JS errors.
   */

  //// Update the hidden field
  //var fid = 'quantity_' + pp_seq[id];
  //var el = document.getElementById(fid);
  //el.value = qty;
  //
  //// Likewise for tax
  //if (vatRate) {
  //  // Get element containing VAT
  //  el = document.getElementById('tax_cart');
  //  if (el == undefined) {
  //    showAlert('Security Alert', 'Data inconsistency detected. Please close and restart your browser.');
  //    exit();
  //  } else {
  //    //alert('itemPrice = ' + itemPrice + ', fixedCharge = ' + fixedCharge);
  //    el.value = (parseFloat(itemPrice) + parseFloat(itemVAT)/* + parseFloat(fixedCharge) + parseFloat(fixedChargeVAT) */).toFixed(2);
  //  }
  //}
}

function changeProductImage() {
}

// Change the image associated with the product identified by id. The image can
// be uploaded and stored in the product table to avoid interfering with the
// main image library
var changeimageDlg = null;
function changeImage(id) {
  if (changeimageDlg != null) {
    changeimageDlg.destroy();
  }
  // Display a dialog containing the file upload form
  changeimageDlg = new StickyWinFx( {
    fadeDuration: 1000, // (fade in and out)
    draggable: false,
    content: StickyWin.ui('Upload product illustration', '<form name="uploadproductimageForm" action="do_product_list.php" method="POST" enctype="multipart/form-data" target="_self"><p><strong>Choose an image to upload:</strong></p><input name="userfile" type="FILE" size="50" style="font-size: 11px; font-family: Verdana" maxlength="255" /><br>Maximum file size: 100K<input type="hidden" name="MAX_FILE_SIZE" value="102400" /><input type="hidden" name="prodid" value="' + id + '" /><br><br></form><p>The uploaded image will be resized so that either the height or the width (whichever is the greater) is 100 pixels.</p>' + hr,
    {
      fadeDuration: 1000, // (fade in and out)
      cornerHandle: false,
      draggable: false,
      width: '400px',
      buttons: [
        {
          text: 'Upload',
          onClick: function() { document.forms.uploadproductimageForm.submit(); }
        },
        {
          text: 'Cancel'
        }
      ]
    } )
  } );
  changeimageDlg.position({
      position: 'top',
      offset: { x: 30, y: 50 },
      relativeTo: $('im_' + id),
      edge: 'left'
      //relFixedPosition: false
  });
}

var alertDlg = null;

// ----------------------------------------------------------------------------
// Do not use this function. It uses Mootools and will probably be phased
// out eventually. Instead, use the corresponding function in mytinybox.js.
// ----------------------------------------------------------------------------
function showAlert(caption, msg, relTo, offsetX, offsetY) {
  //alert(relTo);
  //return;
  // Remove existing dialog if any
  if (alertDlg) {
    alertDlg.destroy();
  }
  // Create new one
  alertDlg = new StickyWinFx( {
    fadeDuration: 0, // No fade
    draggable: false,
    content: StickyWin.ui(caption, msg,
    {
      fadeDuration: 1000, // (fade in and out)
      cornerHandle: false,
      draggable: true,
      width: '400px',
      buttons: [
        {
          text: 'OK'
        }
      ]
    } )
  } );
  if (relTo == 'undefined') {
    alertDlg.position({
        position: 'top',
        offset: { x: 0, y: 150 },
        //relativeTo: $("optionList"),
        edge: 'center'
        //relFixedPosition: false
    });
  } else {
    if (offsetX == 'undefined') {
      offsetX = 100;
    }
    if (offsetY == 'undefined') {
      offsetY = 100;
    }
    alertDlg.position({
        position: 'top',
        offset: { x: offsetX, y: offsetY },
        relativeTo: $(relTo),
        edge: 'center'
        //relFixedPosition: false
    });
  }
  //alertDlg.show();
}

/*
 * This function is out-of-date and needs rewriting
 */
function returnToShop() {

  //alert('returnToShop() is out of date');

  // Create an HttpRequest
  var xmlHttp = createXmlHttpRequest();

  // Post the input data to a script that will save it in the session. Once
  // this has been done we can redirect to the required page, which must
  // retrieve the data from the session before displaying.
  if (xmlHttp != null) {
    xmlHttp.open("POST", 'save_basket.php', true);
    xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
          //alert('Seems to have worked so far - now redirecting');
          top.location.href = '/?0';
          return false;
        }
        else {
          alert('Invalid response');
        }
      }
    }

    // Get the field values and build argument string
    var args = null;
    for (i in itemQty) {
      var el = document.getElementById('qty[' + i + ']');
      if (el != null) {
        var qty = el.value;
        if (qty != null) {
          qty = qty.trim();
        }
        if (qty.length == 0 || qty.length > 5 || isNaN(qty)) {
          qty = 0;
        }
        itemQty[i] = qty;
        if (args == null) {
          args = '';
        } else {
          args += '&';
        }
        args += 'qty[' + i + ']=' + itemQty[i];
      }
    }

    // Send the args to the script
    //alert(args);
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlHttp.send(args);
  }
}

var editProductDlg = null;
function editProduct(id, delivery) {
  // Get product info
  var xmlHttp = createXmlHttpRequest();
  if (xmlHttp != null) {
    xmlHttp.open("POST", 'get_product_data.php', true);
    xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
          var resp = xmlHttp.responseText;
          //alert(resp);
          var attribs = unserialize(resp);
          if (attribs['res'] == 'OK') {
            var prodName = attribs['name'];
            var prodDescr = attribs['descr'];
            var prodPrice = attribs['price'];
            var prodUnits = attribs['units'];
            if (delivery) {
              var delCharge = attribs['del_charge'];
            }
            // Remove existing dialog, if any
            if (editProductDlg != null) {
              editProductDlg.destroy();
            }
            // Display new Edit dialog
            editProductDlg = new StickyWinFx( {
              fadeDuration: 1000, // (fade in and out)
              draggable: false,
              content: StickyWin.ui('Editing product details', '<form name="editproductForm" action="" method="POST" enctype="multipart/form-data" target="_self"><table border="0" cellpadding="4" cellspacing="0"><tr><td width="50%"><strong>Name of product</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prod_name" value="' + utf8_decode(prodName) + '" maxlength="100" /></td></tr><tr><td width="50%"><strong>Description</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prod_descr" value="' + prodDescr + '" maxlength="255" /></td></tr><tr><td style="width:50%"><strong>Price</strong></td><td style="width:50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prod_price" value="' + prodPrice + '" /></td></tr><tr><td style="width:50%"><strong>Units</strong></td><td style="width:50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prod_units" value="' + prodUnits + '" /></td></tr>' + (delivery ? '<tr><td style="width:50%"><strong>Delivery charge</strong></td><td style="width:50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="del_charge" value="' + delCharge + '" /></td></tr>' : '') + '</table><input type="hidden" name="prod_id" value="' + id + '" /><input type="hidden" name="btn_edit_product" id="btn_edit_product" value="1XtG4lK" /></form><br>' + hr,
              {
                fadeDuration: 1000, // (fade in and out)
                cornerHandle: false,
                draggable: false,
                width: '400px',
                buttons: [
                  {
                    text: 'OK',
                    onClick: function() { document.forms.editproductForm.submit(); }
                  },
                  {
                    text: 'Cancel'
                  }
                ]
              } )
            } );
            editProductDlg.position({
                position: 'top',
                offset: { x: 100, y: 100 },
                relativeTo: $('im_' + id),
                edge: 'left'
                //relFixedPosition: false
            });
          } else {
            return false;
          }
        }
        else {
          alert('Invalid response');
        }
      }
    }
  }
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send('product_id=' + id);
}

var addProductDlg = null;
function addProduct(id) {
  // Remove existing dialog, if any
  if (addProductDlg != null) {
    addProductDlg.destroy();
  }
  // Display new Edit dialog
  addProductDlg = new StickyWinFx( {
    fadeDuration: 1000, // (fade in and out)
    draggable: false,
    content: StickyWin.ui('Add a new product', '<form name="addproductForm" action="" method="POST" enctype="multipart/form-data" target="_self"><table border="0" cellpadding="4" cellspacing="0"><tr><td width="50%"><strong>Name of product</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prod_name" value="" maxlength="100" /></td></tr><tr><td width="50%"><strong>Description</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prod_descr" value="" maxlength="255" /></td></tr><tr><td style="width:50%"><strong>Price</strong></td><td style="width:50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prod_price" value="" /></td></tr><tr><td style="width:50%"><strong>Units</strong></td><td style="width:50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prod_units" value="" /></td></tr><tr><td style="width:50%"><strong>Delivery charge</strong></td><td style="width:50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="del_charge" value="" /></td></tr></table><input type="hidden" name="prod_id" value="" /><input type="hidden" name="btn_add_product" id="btn_add_product" value="GrmP2cYF" /></form><br>' + hr,
    {
      fadeDuration: 1000, // (fade in and out)
      cornerHandle: false,
      draggable: false,
      width: '400px',
      buttons: [
        {
          text: 'OK',
          onClick: function() { document.forms.addproductForm.submit(); }
        },
        {
          text: 'Cancel'
        }
      ]
    } )
  } );
  addProductDlg.position({
      position: 'top',
      offset: { x: 100, y: 30 },
      relativeTo: $('edit_link'),
      edge: 'left'
      //relFixedPosition: false
  });
}

var deleteProductDlg = null;
function deleteProduct(id) {
  //alert('Deleting product');
  // Remove existing dialog, if any
  if (deleteProductDlg != null) {
    deleteProductDlg.destroy();
  }
  // Display new Edit dialog
  deleteProductDlg = new StickyWinFx( {
    fadeDuration: 1000, // (fade in and out)
    draggable: false,
    content: StickyWin.ui('Delete this product', '<form name="deleteProductForm" action="" method="POST" enctype="multipart/form-data" target="_self"><p><strong>Are you sure you want to delete this product?</strong></p><input type="hidden" name="btn_delete_product" id="btn_delete_product" value="Yu4Sxc7"><input type="hidden" name="prodid" id ="prodid" value="' + id + '"></form><br>' + hr,
    {
      fadeDuration: 1000, // (fade in and out)
      cornerHandle: false,
      draggable: false,
      width: '400px',
      buttons: [
        {
          text: 'Yes',
          onClick: function() { document.forms.deleteProductForm.submit(); }
        },
        {
          text: 'No'
        }
      ]
    } )
  } );
  deleteProductDlg.position({
    position: 'top',
    offset: { x: 100, y: 100 },
    relativeTo: $('im_' + id),
    edge: 'left'
      //relFixedPosition: false
  });
}

var editProdcatDlg = null;
function editProdcat(id) {
  // Get product info
  var xmlHttp = createXmlHttpRequest();
  if (xmlHttp != null) {
    //xmlHttp.open("POST", 'dummy.php', true);
    xmlHttp.open("POST", 'get_prodcat_data.php', true);
    xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
          var resp = xmlHttp.responseText;
          var attribs = unserialize(resp);
          if (attribs['res'] == 'OK') {
            var prodcatName = attribs['name'];
            var prodcatDescr = attribs['descr'];
            var prodcatParent = attribs['parent'];
            var menuCaption = attribs['caption'];
            var parentMenuCaption = attribs['parent_caption'];
            // Remove existing dialog, if any
            if (editProdcatDlg != null) {
              editProdcatDlg.destroy();
            }
            var pmc, catTypeLC, catTypeUC;
            if (parentMenuCaption == null) {
              pmc = '';
              catTypeLC = 'department';
              catTypeUC = 'Department';
            } else {
              pmc = '<tr><td width="50%"><strong>Parent menu caption*</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="parent_menu_caption" value="' + parentMenuCaption + '" maxlength="16" /></td></tr>';
              catTypeLC = 'sub-department';
              catTypeUC = 'Sub-department';
            }
            var catType = (parentMenuCaption == null ? 'department' : 'sub-department');
            // Display new Edit dialog
            editProdcatDlg = new StickyWinFx( {
              fadeDuration: 1000, // (fade in and out)
              draggable: true,
              content: StickyWin.ui('Editing ' + catTypeLC + ' details', '<form name="editprodcatForm" action="" method="POST" enctype="multipart/form-data" target="_self"><table border="0" cellpadding="4" cellspacing="0"><tr><td width="50%"><strong>' + catTypeUC + ' name</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prodcat_name" value="' + prodcatName + '" maxlength="100" /></td></tr><tr><td width="50%"><strong>Menu caption*</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="menu_caption" value="' + menuCaption + '" maxlength="16" /></td></tr>' + pmc + '<tr><td width="50%"><strong>Description</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prodcat_descr" value="' + prodcatDescr + '" maxlength="255" /></td></tr></table><input type="hidden" name="btn_edit_prodcat" id="btn_edit_prodcat" value="mTRk1q4" /></form><br>' + hr,
              {
                //fadeDuration: 1000, // (fade in and out)
                cornerHandle: false,
                //draggable: false,
                width: '400px',
                buttons: [
                  {
                    text: 'OK',
                    onClick: function() { document.forms.editprodcatForm.submit(); }
                  },
                  {
                    text: 'Cancel'
                  }
                ]
              } )
            } );
            //alert(editProdcatDlg);
            editProdcatDlg.position({
                position: 'top',
                offset: { x: 100, y: 30 },
                relativeTo: $('edit_link'),
                edge: 'left'
                //relFixedPosition: false
            });
          } else {
            return false;
          }
        }
        else {
          alert('Invalid response (' + xmlHttp.status + ')');
        }
      }
    }
    xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlHttp.send('prodcat_id=' + id);
  } else {
    alert('Could not create XmlHttpRequest');
  }
}

var deleteProdcatDlg = null;
function deleteProductCategory(id) {
  //alert('deleting product category(' + id + ')');
  // Remove existing dialog, if any
  if (deleteProdcatDlg != null) {
    deleteProdcatDlg.destroy();
  }
  // Display new Edit dialog
  deleteProdcatDlg = new StickyWinFx( {
    fadeDuration: 1000, // (fade in and out)
    draggable: false,
    content: StickyWin.ui('Remove this department', '<form name="deleteProdcatForm" action="" method="POST" enctype="multipart/form-data" target="_self"><p style="font-weight:bold; color:red;"><strong>Are you sure you want to remove this department and all the products it contains?</strong></p><input type="hidden" name="btn_delete_prodcat" id="btn_delete_prodcat" value="se4TMpyF"><input type="hidden" name="prodcat_id" id ="prodcat_id" value="' + id + '"></form><br>' + hr,
    {
      fadeDuration: 1000, // (fade in and out)
      cornerHandle: false,
      draggable: false,
      width: '400px',
      buttons: [
        {
          text: 'Yes',
          onClick: function() { document.forms.deleteProdcatForm.submit(); }
        },
        {
          text: 'No'
        }
      ]
    } )
  } );
  deleteProdcatDlg.position({
      position: 'top',
      offset: { x: 100, y: 30 },
      relativeTo: $('edit_link'),
      edge: 'left'
      //relFixedPosition: false
  });
}

var addSubcatDlg = null;
function addSubcat(id) {
  // Remove existing dialog, if any
  if (addSubcatDlg != null) {
    addSubcatDlg.destroy();
  }
  // Display new Edit dialog
  addSubcatDlg = new StickyWinFx( {
    fadeDuration: 1000, // (fade in and out)
    draggable: false,
    content: StickyWin.ui('Add a new sub-department', '<form name="addSubcatForm" action="" method="POST" enctype="multipart/form-data" target="_self"><table border="0" cellpadding="4" cellspacing="0"><tr><td width="50%"><strong>Name of sub-department</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prodcat_name" value="" maxlength="100" /></td></tr><tr><td width="50%"><strong>Menu caption</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="menu_caption" value="" maxlength="16" /></td></tr><tr><td width="50%"><strong>Description</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prodcat_descr" value="" maxlength="255" /></td></tr></table><input type="hidden" name="btn_add_subcat" id="btn_add_subcat" value="Y0o6Gfm2" /></form><br>' + hr,
    {
      fadeDuration: 1000, // (fade in and out)
      cornerHandle: false,
      draggable: false,
      width: '400px',
      buttons: [
        {
          text: 'OK',
          onClick: function() { document.forms.addSubcatForm.submit(); }
        },
        {
          text: 'Cancel'
        }
      ]
    } )
  } );
  addSubcatDlg.position({
      position: 'top',
      offset: { x: 100, y: 30 },
      relativeTo: $('edit_link'),
      edge: 'left'
      //relFixedPosition: false
  });
}

var addSiblingDlg = null;
function addSibling(id) {
  // Remove existing dialog, if any
  if (addSiblingDlg != null) {
    addSiblingDlg.destroy();
  }
  // Display new Edit dialog
  addSiblingDlg = new StickyWinFx( {
    fadeDuration: 1000, // (fade in and out)
    draggable: false,
    content: StickyWin.ui('Add a new department or sub-department', '<form name="addSiblingForm" action="" method="POST" enctype="multipart/form-data" target="_self"><table border="0" cellpadding="4" cellspacing="0"><tr><td width="50%"><strong>Name of department</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prodcat_name" value="" maxlength="100" /></td></tr><tr><td width="50%"><strong>Menu caption</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="menu_caption" value="" maxlength="16" /></td></tr><tr><td width="50%"><strong>Description</strong></td><td width="50%"><input type="text" style="font-size:11px; font-family:Verdana; width:150px;" name="prodcat_descr" value="" maxlength="255" /></td></tr></table><input type="hidden" name="btn_add_sibling" id="btn_add_sibling" value="Rqw397fGW" /></form><br>' + hr,
    {
      fadeDuration: 1000, // (fade in and out)
      cornerHandle: false,
      draggable: false,
      width: '400px',
      buttons: [
        {
          text: 'OK',
          onClick: function() { document.forms.addSiblingForm.submit(); }
        },
        {
          text: 'Cancel'
        }
      ]
    } )
  } );
  addSiblingDlg.position({
      position: 'top',
      offset: { x: 100, y: 30 },
      relativeTo: $('edit_link'),
      edge: 'left'
      //relFixedPosition: false
  });
}

function printpage() {
  window.print();
}

