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;
    //alert('subproduct_id = ' + subproduct_id);
  }
  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) {
  //alert('productId = ' + productId);
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", 'add_bundle_to_basket.php', true);
  var qty = 1;
  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);
          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 {
      }
    }
  }
  xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlHttp.send('product_id=' + productId + '&qty=' + qty);
}

function clearBasket() {
  alert('clearBasket called');
  var xmlHttp = createXmlHttpRequest();
  xmlHttp.open("POST", '/clear_basket.php', true);
  //xmlHttp.onreadystatechange = function() {
  //  alert('returned from clear_basket.php, readyState = ' + xmlHttp.readyState);
  //  if (xmlHttp.readyState == 2) {
  //    alert('status = ' + xmlHttp.status);
  //  }
  //}
  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 itemUnitDelCharge = new Array();
var fixedCharge = 0;

// The pp_seq array holds the current PayPal sequence numbers for the hidden
// fields on the checkout page (do_checkout.php). It is only created when the
// checkout page is displayed and has no meaning otherwise.
var pp_seq = new Array();

function initItem(itemId, prodName, unitPrice, qty, unitDelCharge) {
  //alert('itemId = ' + itemId + ', prodName = ' + prodName + ', unitPrice = ' + unitPrice + ', qty = ' + qty + ', unitDelCharge = ' + unitDelCharge);
  itemName[itemId] = prodName;
  itemQty[itemId] = qty;
  itemUnitPrice[itemId] = unitPrice;
  itemUnitDelCharge[itemId] = unitDelCharge;
}

function clearCheckoutItems() {
  pp_seq = new Array();
}

function registerCheckoutItem(id, seq) {
  pp_seq[id] = seq;
}

function registerFixedCharge(amount) {
  fixedCharge = amount;
}

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

function getTotalDelCharge() {
  var i;
  var tot = 0;
  for (i in itemQty) {
    if (itemQty[i] > 0) {
      tot += parseInt(itemQty[i]) * itemUnitDelCharge[i];
    }
  }
  return tot.toFixed(2);
}

function changeQty(id, vatRate, adjust) {

  // ****************************************
  // id can be negative
  // If qty not valid treat as zero
  var qty = document.getElementById('qty[' + id + ']').value.trim();
  if (qty.length == 0 || qty.length > 5 || isNaN(qty)) {
    qty = 0;
  }
  itemQty[id] = qty;

  // Update price
  var itemPrice = parseInt(qty) * itemUnitPrice[id];
  if (adjust) {
    itemPrice *= (1.00 + vatRate);
  }
  itemPrice = itemPrice.toFixed(2);
  document.getElementById('itemPrice[' + id + ']').innerHTML = itemPrice;
  document.getElementById('totalPrice').innerHTML = (adjust ? getTotalPrice() * (1.00 + vatRate) : getTotalPrice()).toFixed(2);

  // Repeat for delivery charge
  var itemDelCharge = parseInt(qty) * itemUnitDelCharge[id];
  itemDelCharge = itemDelCharge.toFixed(2);
  if (adjust) {
    itemDelCharge *= vatRate;
  }
  document.getElementById('itemDelCharge[' + id + ']').innerHTML = itemDelCharge;
  document.getElementById('totalDelCharge').innerHTML = (adjust ? getTotalDelCharge() * (1.00 + vatRate) : getTotalDelCharge());

  // 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 = (1.00 + vatRate) * (itemPrice + fixedCharge);
    }
  }
}

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;

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();
}

function returnToShop() {

  // 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();
}
