function PreloadImages() {
 var d = document; 
 if (d.images) { 
  if (!d.PreloadedImages) d.PreloadedImages=new Array();
  var j=d.PreloadedImages.length, a=PreloadImages.arguments;
  for(var i=0; i < a.length; i++)
   if (a[i].indexOf("#") != 0){
    d.PreloadedImages[j] = new Image;
    d.PreloadedImages[j++].src = a[i];
   }
 }
}

function SubmitSearch() {
 //document.forms.searchportlettag.elements['search'].value = document.forms.searchfacia.elements['searchfaciainput'].value;
 //document.forms.searchportlettag.elements['go'].click();
 window.location.href="http://www.winebox.co.uk/products?search="+escape(document.forms.searchfacia.elements['searchfaciainput'].value); //"/s.nl?c=612123&sc=2&search="+escape(document.forms.searchfacia.elements['searchfaciainput'].value);
 return false;
}

function CustomiseCrumbTrail() {
 var sSpanHtml = document.getElementById("crumbtrail").innerHTML;
 sCurrentPage = sCurrentPage.replace(/&/g,"\x26amp;");
 document.getElementById("crumbtrail").innerHTML = sSpanHtml.replace("&nbsp;" + sCurrentPage + "&nbsp;"," <span class=\"currentcrumb\">" + sCurrentPage + "</span>&nbsp;");
}

function AppendCrumbTrail(str) {
 document.getElementById("crumbtrail").innerHTML += str;
}

function ValidateQuantity(obj) {
 var qty = parseInt(obj.form.qty.value);
 var packsize = parseInt(obj.form.packsize.value);
 packsize = (!isNaN(packsize)) ? packsize : 1;
 var qtyavailable = parseInt(obj.form.qtyavailable.value);
 qtyavailable = qtyavailable >= 0 ? qtyavailable : 0;
 if (isNaN(qty)) {
  alert("Quantity must be a positive number");
  obj.form.qty.value = packsize;
  obj.form.qty.select();
 }
 else if (qty > qtyavailable) {
  var qtycanbuy = qtyavailable - (qtyavailable % packsize);
  alert("Unfortunately the amount that you have ordered is more\nthan what is available from our London Distribution Centre.\nPlease send an email to sales@wbc.co.uk or call \n08000 85 85 95 if you have any queries.\n\n\tAvailable quantity is "+qtycanbuy);
  obj.form.qty.value = qtycanbuy;
  obj.form.qty.select();
 }
 else if (qty <= 0) {
  if (qtyavailable == 0) {
   alert("This item is currently out of stock");
   obj.form.qty.value = 0;
  }
  else {
   alert("Quantity must be greater than 0");
   obj.form.qty.value = packsize;
  }
  obj.form.qty.select();
 }
 else if ((qty % packsize) != 0) {
  alert("Quantity must be in multiples of " + packsize + "\nThe next valid quantity has been\nselected for you");
  obj.form.qty.value = qty + (packsize - (qty % packsize));
  obj.form.qty.select();
 }
 else {
  obj.form.submit();
 }
}

function WrapFeaturedItems() {
 var initialTables = document.getElementsByName("featureditemtable");
 var destinationDiv = document.getElementById("featureddiv");
 var parentDiv = document.createElement("div");
 parentDiv.style.overflow = "hidden";
 parentDiv.style.width = "100%";
 var childDiv, featureTable, spacerDiv, i;
 for (i = 0; i < initialTables.length; i++) {
  if (i % 3 == 0) {
   childDiv = document.createElement("div");
   childDiv.style.styleFloat = "left";
   childDiv.style.cssFloat = "left";
   //childDiv.style.width = "128px";
   //childDiv.style.height = "356px";
   childDiv.style.padding = "0px 15px 0px 0px";
  }
  featureTable = initialTables[i].cloneNode(true);
  featureTable.id = "feature" + i;
  childDiv.appendChild(featureTable);
  if ((i % 3 == 2) || (i == initialTables.length-1)) {
   parentDiv.appendChild(childDiv);
  }
  else
  {
   spacerDiv = document.createElement("div");
   spacerDiv.style.height = "13px";
   spacerDiv.style.width = "128px";
   childDiv.appendChild(spacerDiv);
  }
 }
 destinationDiv.appendChild(parentDiv);
 var oldTable = document.getElementById("featurelist");
 oldTable.parentNode.removeChild(oldTable);
}

function CalcStockLevel(obj, qtyavail, packqty) {
 if (typeof packqty != "number") packqty = 1;
 qtyavail = parseInt(qtyavail / packqty);
 if (isNaN(qtyavail)) obj.innerHTML = "N/A";
 else if (qtyavail <= 0) obj.innerHTML = "<span class=\"outofstock\">Out of stock</span>";
 else if (qtyavail <= 10) obj.innerHTML = "Low";
 else if (qtyavail <= 100) obj.innerHTML = "Medium";
 else if (qtyavail <= 1000) obj.innerHTML = "High";
 else obj.innerHTML = "Very High";
}

function WriteOutOfStockMsg(stockstatus) {
 if (stockstatus <= 0)
  document.write("<span class=\"outofstock\">OUT OF STOCK</span><br>");
}

function SetThumbVis(div) {
 var img = div.getElementsByTagName("IMG")[0];
 if ((img.src == location.href.substring(0, location.href.lastIndexOf("/")+1)) || img.src == location.href) {
  img.parentNode.removeChild(img);
 }
 else {
  img.src += "&resizeid=-5&resizew=100&resizeh=100";
 }
}

function CustomiseNav() {
 var starHTML = "<div class=\"navportlet-star\"></div>"; //"<IMG src=\"/core/media/media.nl?id=3576&c=612123&h=540800dde4d210b74c02\">";
 var navtableparent = document.getElementById("navtable");
 if (!navtableparent) return false;
 var navtable = navtableparent.getElementsByTagName("table");
 if (!navtable || navtable.length == 0) return false;
 var navRows = navtable[0].rows;
 var cRoot, cLvl1, cLvl2, cLvl3;
 for (var i = 0; i < navRows.length; i++) {
  var cell_imgs = navRows[i].cells[0].getElementsByTagName("img");
  if (cell_imgs && cell_imgs.length == 1) {
   if (navRows[i].cells[0].colSpan == 1) {
    cLvl1 = navRows[i].cells[2];
    cLvl1.className = "nav_lvl1";
    var clvl1_links = cLvl1.getElementsByTagName("a");
    if (clvl1_links && clvl1_links.length > 0 && clvl1_links[0].className  == "textboldnolink") {
     navRows[i].cells[1].innerHTML = starHTML;
     clvl1_links[0].className  = "";
     cLvl1.className  = "nav_lvl1_active";
     cRoot.className  = "nav_root_active";
    }
   }
   else if (navRows[i].cells[0].colSpan == 2) {
    cLvl2 = navRows[i].cells[2];
    cLvl2.className = "nav_lvl2";
    var clvl2_links = cLvl2.getElementsByTagName("a");
    if (clvl2_links && clvl2_links.length > 0 && clvl2_links[0].className  == "textboldnolink") {
     navRows[i].cells[1].innerHTML = starHTML;
     clvl2_links[0].className  = "";
     cLvl2.className  = "nav_lvl2_active";
     cLvl1.className  = "nav_lvl1_active";
     cRoot.className  = "nav_root_active";
    }
   }
   else if (navRows[i].cells[0].colSpan == 3) {
    cLvl3 = navRows[i].cells[2];
    cLvl3.className = "nav_lvl3";
    var clvl3_links = cLvl3.getElementsByTagName("a");
    if (clvl3_links && clvl3_links.length > 0 && clvl3_links[0].className  == "textboldnolink") {
     navRows[i].cells[1].innerHTML = starHTML;
     clvl3_links[0].className  = "";
     cLvl3.className  = "nav_lvl3_active";
     cLvl2.className  = "nav_lvl2_active";
     cLvl1.className  = "nav_lvl1_active";
     cRoot.className  = "nav_root_active";
    }
   }
  }
  else {
   cRoot = navRows[i].cells[1];
   cRoot.className = "nav_root";
   var croot_links = cRoot.getElementsByTagName("a");
   if ((croot_links.length > 0) && (croot_links[0].className  == "textboldnolink")) {
    navRows[i].cells[0].innerHTML = starHTML;
    croot_links[0].className  = "";
    cRoot.className  = "nav_root_active";
   }
  }
 }
}

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}

function IsLoggedIn() {
 if (custEntityID != "guest")
  return true;
 else
  return false;
}

function CheckCredentials(page) {
  if ((location.href != loginUrl) && (page == "brochure") && (custPriceLevel != "Trade Price")) {
   window.location = infoitemTradeOnly;
  }
  if ((location.href != loginUrl) && (page == "personalisation") && (!IsLoggedIn())) {
   window.location = loginUrl;
  }
  else if ((location.href == myAccountUrl) && (!IsLoggedIn())) {
   window.location = loginUrl;
 }
}

function ShowCart(formid, cartid, pricelabelid, pricevalueid, pricetext) {
 var bMustBeSignedInForPrices = false;
 var bMustBeSignedInToBuy = false;
 var cartdiv = document.getElementById(cartid);
 var form = document.forms[formid];
 var pricevalue = document.getElementById(pricevalueid);
 var price = parseFloat(pricevalue.innerHTML.replace(/<br>/gi,"").replace(/\xA3/gi,""));
 if (form.elements['storespecialorder'].value == "Yes") { //(sCurrentPage == "special order") //(!isNaN(price) && !(price > 0.0)) { //If special order then display message
  cartdiv.parentNode.removeChild(cartdiv);
  if (bMustBeSignedInForPrices && !IsLoggedIn()) {
   HidePrice(pricetext, pricelabelid, pricevalue);
  }
 }
 else if (!bMustBeSignedInToBuy || IsLoggedIn()) { //If logged in set default pack quantity and attach ValidateQty handler //(!bMustBeSignedIn || IsLoggedIn())
  if (form.elements['qtyavailable'].value > 0) {
   if (!isNaN(form.elements['packsize'].value))
    form.elements['qty'].value = form.elements['packsize'].value;
   form.qty.onkeypress = function(e) {
       e = e || window.event;
       if (e.keyCode == 13) {
        ValidateQuantity(form.qty);
        return false;
       }
      };
  }
  else {
   cartdiv.parentNode.removeChild(cartdiv);
  }
 }
 else { //If not logged in remove cart and prices
  cartdiv.parentNode.removeChild(cartdiv);
  if (bMustBeSignedInForPrices)
   HidePrice(pricetext, pricelabelid, pricevalue);
 }
}

function HidePrice(pricetext, pricelabelid, pricevalue) {
  if (pricetext == "") {
   if (pricelabelid != "") {
    var pricelabel = document.getElementById(pricelabelid);
    pricelabel.parentNode.removeChild(pricelabel);
   }
   pricevalue.parentNode.removeChild(pricevalue);
  }
  else {
   pricevalue.innerHTML = pricetext;
  }
}

function DisplayPageHeading(header) {
 document.write('<div class="catheading"><h1>'+header+'</h1></div>');
}

function SetupStaticNav() {
 var staticnav = document.getElementById('staticnav');
 var navportlet = document.getElementById('navsidebar');
 if (!navportlet) return;
 navportlet.rows[1].deleteCell(0);
 var navtable = navportlet.rows[1].insertCell(0);
 navtable.appendChild(staticnav.cloneNode(true));
 /*navportlet.rows[1].cells[0].removeChild(navportlet.rows[1].cells[0].firstChild);
 if (document.all)
  navportlet.rows[1].cells[0].appendChild(staticnav.cloneNode(true));
 else
  navportlet.rows[1].cells[0].firstChild.appendChild(staticnav.cloneNode(true));*/
 navportlet.style.visibility = "visible";
 CustomiseNav();
}

function InitCartQty() {
 var cartinput;
 if (sCurrentPage.toLowerCase() == "shopping basket") {
  var carttable = document.getElementById('carttable');
  for (var i = 1; i < carttable.rows.length-1; i++) {
   cartinputs = carttable.rows[i].cells[4].getElementsByTagName('input');
   if (cartinputs.length > 0) cartinputs[0].onblur = ValidateCartQty;
  }
 }
}

function ValidateCartQty() {
 var cartinputs, packsizecells;
 if (sCurrentPage.toLowerCase() == "shopping basket") {
  var carttable = document.getElementById('carttable');
  for (var i = 1; i < carttable.rows.length-1; i++) {
   packsizecells = carttable.rows[i].cells[3].getElementsByTagName('td');
   cartinputs = carttable.rows[i].cells[4].getElementsByTagName('input');
   if ((packsizecells.length > 0) && (cartinputs.length > 0))  {
    var packsize = parseInt(packsizecells[0].innerHTML.replace(/Pack Qty: /gi,""));
    packsize = (!isNaN(packsize)) ? packsize : 1;
    ValidateQty2(cartinputs[0],packsize);
   }
  }
 }
}

function InitReorderQty() {
 var cartinput;
 var sPath = window.location.pathname;
 var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
 if (sPage == "itemsordered.nl") {
  var bodytab = document.getElementById('__tab');
  if (!bodytab) return;
  var item_forms = bodytab.getElementsByTagName('form');
  for (var f = 0; f < item_forms.length; f++) {
   var buyid = item_forms[f].elements['buyid'].value;
   var packsize = item_forms[f].elements['custcol_packsize'].value;
   if (item_forms[f].id == 'form'+buyid) {
    item_forms[f].nsonsubmit = item_forms[f].onsubmit;
    //item_forms[f].onsubmit = ValidateReorderQty;
    var qty_input = item_forms[f].elements['qty'];
    qty_input.value = packsize;
    qty_input.onchange = ValidateReorderQty;
   }
  }
  /*
  var carttable = document.getElementById('div__bodytab');
  carttable.onsubmit = ValidateReorderQty;
  var packsizecells = document.getElementsByName('custcol_packsize');
  for (var i = 1; i < carttable.rows.length-1; i++) {
   cartinputs = carttable.rows[i].cells[6].getElementsByTagName('input');
   if (cartinputs.length > 3) {
    cartinputs[2].value = packsizecells[i-1].value;
    cartinputs[2].onchange = ValidateReorderQty;
   }
  }
  */
 }
}

function ValidateReorderOnSubmit() {
 if (ValidateReorderQty())
  return this.onsubmit();
 else
  return false;
}

function ValidateReorderQty() {
 var bodytab = document.getElementById('__tab');
 var item_forms = bodytab.getElementsByTagName('form');
 for (var f = 0; f < item_forms.length; f++) {
  var buyid = item_forms[f].elements['buyid'].value;
  if (item_forms[f].id == 'form'+buyid) {
   var qty_input = item_forms[f].elements['qty'];
   var packsize = item_forms[f].elements['custcol_packsize'].value;
   ValidateQty2(qty_input, packsize);
  }
 }
 /*
 var cartinputs, packsizecells;
 var carttable = document.getElementById('div__bodytab');
 packsizecells = document.getElementsByName('custcol_packsize');
 for (var i = 1; i < carttable.rows.length-1; i++) {
  //packsizecells = carttable.rows[i].cells[5].getElementById('custcol_packsize');
  cartinputs = carttable.rows[i].cells[6].getElementsByTagName('input');
//  if ((packsizecells.length > 0) && (cartinputs.length > 3)) 
  ValidateQty2(cartinputs[2],packsizecells[i-1].value);
 }
 */
}

function ValidateQty2(qtyinput, packqty) {
 var qty = parseInt(qtyinput.value);
 var packsize = parseInt(packqty);
 if (isNaN(qty)) {
  alert("Quantity must be a positive number");
  qtyinput.value = packsize;
  qtyinput.select();
  return false;
 }
 else if (qty <= 0) {
  alert("Quantity must be greater than 0");
  qtyinput.value = packsize;
  qtyinput.select();
  return false;
 }
 else if ((qty % packsize) != 0) {
  alert("Quantity must be in multiples of " + packsize + "\nThe next valid quantity has been\nselected for you");
  qtyinput.value = qty + (packsize - (qty % packsize));
  qtyinput.select();
  return false;
 }
 return true;
}

function payMethHider() {
 var sPayMeth = document.getElementsByName('sPayMeth');
 var issueno = document.getElementById('debitcardissuenohider');
 var validfrom = document.getElementById('debitcardvalidfromhider');
 for (i = 0; i < sPayMeth.length; i++) {
  if (sPayMeth[i].checked) {
   switch (sPayMeth[i].value)
   {
     case "7":
     case "8":
     case "9":
      issueno.style.visibility = "visible"; 
      validfrom.style.visibility = "visible";
      break;
     default:
      issueno.style.visibility = "hidden"; 
      validfrom.style.visibility = "hidden"; 
      break;
   }
   return true;
  }
 }
}

function CalclDiscounts() {
 var aftable = document.getElementById('additionalfieldstable');
 if (aftable != null) {
  aftable.style.visibility = "hidden";
  if (custPriceLevel == "") { // Trade Price
   var promotext = aftable.rows[2].cells[1];
   if (promotext && promotext.innerHTML == "If you have a coupon or promotion code, enter it here") {
    var promocode = GetPromoCode(true);
    var discount = GetPromoCode(false);
    if (promocode != "") {
     promotext.innerHTML = "If you have a promotion code, enter it here.<br>If not, don&#39;t worry - <b>your order is eligible for " + discount + " discount.</b><br><input type=button class=btn-BuyOff value=\"Click here to receive your discount\" onclick=\"ApplyDiscount(\'" + promocode + "\');\" style=\"color: #D21044; margin-top: 5px;\"><br><br>";
    }
   }
   else if (aftable.rows[1].cells[0].childNodes[1] != null) {
    var pctext = aftable.rows[1].cells[0].childNodes[1].innerHTML;
    //pctext = pctext.replace(/ EXPORT/g,"");
    switch (pctext)
    {
     case "1) 0250-0499": case "2) 0500-0999": case "3) 1000-1999": case "4) 2000-":
     case "5) 0375-0750 EURO": case "6) 0750-1500 EURO": case "7) 1500-3000 EURO": case "8) 3000- EURO":
     case "9) 0250-0499 EXPORT": case "10) 0500-0999 EXPORT": case "11) 1000-1999 EXPORT": case "2000- EXPORT":
      aftable.rows[1].style.visibility = "hidden";
      break;
    }
   }
  }
  aftable.style.visibility = "visible";
 }
}

function GetPromoCode(returnpromo) {
 var promocode = "";
 var discount = "";
 /*var totalprice = document.getElementById('ordersummary_itemtotal').cells[1].innerHTML;
 if (totalprice.search(/,\d\d$/) >= 0) // /,\d\d \x20AC$/
  totalprice = totalprice.replace(/,\d\d$/,".00");
 var re = /^\$|\xA3|\u20AC|,|\x20/g;
 var totalprice = totalprice.replace(re,"");
 totalprice = parseFloat(totalprice);*/
 var totalprice = CalcOrderTotal(true);
 if (custCurrency == "GBR") {
  var totaltax = document.getElementById('ordersummary_tax').cells[1].innerHTML;
  var re = /^\$|\xA3|\u20AC|,|\x20/g;
  var totaltax = parseFloat(totaltax.replace(re,""));
  if (totaltax > 0) {
   if ((totalprice >= 250) && (totalprice < 500)) {
    promocode = "1) 0250-0499";
    discount = "2%";
   }
   else if ((totalprice >= 500) && (totalprice < 1000)) {
    promocode = "2) 0500-0999";
    discount = "3%";
   }
   else if ((totalprice >= 1000) && (totalprice < 2000)) {
    promocode = "3) 1000-1999";
    discount = "5%";
   }
   else if (totalprice >= 2000) {
    promocode = "4) 2000-";
    discount = "7.5%";
   }
  }
  else {
   if ((totalprice >= 250) && (totalprice < 500)) {
    promocode = "9) 0250-0499 EXPORT";
    discount = "2%";
   }
   else if ((totalprice >= 500) && (totalprice < 1000)) {
    promocode = "10) 0500-0999 EXPORT";
    discount = "3%";
   }
   else if ((totalprice >= 1000) && (totalprice < 2000)) {
    promocode = "11) 1000-1999 EXPORT";
    discount = "5%";
   }
   else if (totalprice >= 2000) {
    promocode = "2000- EXPORT";
    discount = "7.5%";
   }
  }
 }
 else if (custCurrency == "Euro") {
  if ((totalprice >= 375) && (totalprice < 750)) {
   promocode = "5) 0375-0750 EURO";
   discount = "2%";
  }
  else if ((totalprice >= 750) && (totalprice < 1500)) {
   promocode = "6) 0750-1500 EURO";
   discount = "3%";
  }
  else if ((totalprice >= 1500) && (totalprice < 3000)) {
   promocode = "7) 1500-3000 EURO";
   discount = "5%";
  }
  else if (totalprice >= 3000) {
   promocode = "8) 3000- EURO";
   discount = "7.5%";
  }
 }
 if (returnpromo) return promocode;
 else return discount;
}

function CalcOrderTotal(excludeitems) {
 excludeitems = (excludeitems) ? true : false;
 var optionsindex = 3, amountindex = 5;
 var options, amount, totalamount = 0;
 var carttable = document.getElementById('carttable');
 if (carttable) {
  for (var i=0; i < carttable.rows.length; i++) {
   if (carttable.rows[i].id == "carttablerow"+(i-1)) {
    options = carttable.rows[i].cells[optionsindex].innerHTML;
    amount  = carttable.rows[i].cells[amountindex].innerHTML;
    amount  = amount.replace(/^(.*),(\d\d)$/,"$1.$2");
    //amount  = amount.replace(/,/,".");
    amount  = amount.replace(/[^0-9.]/g,"");
    if ((excludeitems) && (options.search(/Excluded from Overall Discount/i) == -1))
     totalamount += parseFloat(amount);
    else if (!excludeitems)
     totalamount += parseFloat(amount);
   }
  }
 }
 return totalamount;
}

function AppendExportTag() {
 var totaltax = document.getElementById('ordersummary_tax').cells[1].innerHTML;
 var re = /^\$|\xA3|\u20AC|,|\x20/g;
 var totaltax = parseFloat(totaltax.replace(re,""));
 if ((totaltax <= 0) && (custCurrency == "GBR"))
  return " EXPORT";
 else
  return "";
}

function ApplyDiscount(code) {
   var promoinput = document.getElementsByName('kReferralCode')[0];
   promoinput.style.visibility = "hidden";
   promoinput.value = code; //+AppendExportTag();
   var promoapply = document.getElementById('apply');
   promoapply.onclick();
}

function CheckPOMandatory() {
 var otherrefnum=document.getElementById('otherrefnum');
 if (otherrefnum) {
  otherrefnum.onblur = function(e) {
                                     if (this.value.length < 5) {
                                      alert("Please enter a Purchase Order Reference.");
                                      this.select();
                                     }
                                     else
                                      return true;
                                    }
 }
}

function PageInit() {
 //ResizeBanner();
 //MajesticDefaultInvoice();
 //MajesticSubmitOrder();
 InitCartQty();
 InitReorderQty();
 //CalclDiscounts(); no longer used AG 27-Mar-09
 //InitLoginPage();
 //HideShippingMethods();
 //StoreGACartLines();
 //EditCheckmandatoryFields();
 SavePromoCodeToken();
 ShowSCPopupMessage();
}

function FixFeaturesHeight() {
 var featuretable=document.getElementById('featurelist').getElementsByTagName('table')[0];
 featuretable.cellPadding = "0";
 for (i=0;i<featuretable.rows.length;i++)
  featuretable.rows[i].style.height="18px";
}

function InitLoginPage() {
 if ((queryString('login') == "T") && (queryString('forgotPasswd') != "T")) {
  var bodytable = document.getElementById('div__body').getElementsByTagName('table')[0];
  var logintable = bodytable.rows[0].cells[1].getElementsByTagName('table')[0];
  logintable.style.display = "none";
  document.getElementById('front_retemail').value = document.getElementById('retemail').value;
  var logindiv = document.getElementById('logindiv');
  if (queryString('viewHint') == "T") {
   document.getElementById('p_hint').style.display = "block";
   document.getElementById('span_email').style.display = "block";
   document.getElementById('span_hint').style.display = "none";
   var hintrow = document.getElementById('retemail_fs').parentNode.parentNode.parentNode.rows[0];
   if (hintrow.cells.length > 1)
    document.getElementById('front_hint').value = hintrow.cells[1].firstChild.innerHTML;
   else
    document.getElementById('front_hint').value = hintrow.cells[0].firstChild.rows[0].cells[1].innerHTML;
  }
  logindiv.style.display = "block";
  AutoLogin();
 }
}

function submitlogin() {
 var usr = document.getElementById('front_retemail').value;
 var pwd = document.getElementById('front_retpwd').value;
 RememberLoginCredentials(usr, pwd);
 document.getElementById('retemail').value = usr;
 document.getElementById('retpwd').value = pwd;
 document.getElementById('submitter').onclick();
}

function PageQuery(q) {
 if(q.length > 1) this.q = q.substring(1, q.length);
 else this.q = null;
 this.keyValuePairs = new Array();
 if(q) {
  for(var i=0; i < this.q.split("&").length; i++) {
   this.keyValuePairs[i] = this.q.split("&")[i];
  }
 }
 this.getKeyValuePairs = function() { return this.keyValuePairs; }
 this.getValue = function(s) {
  for(var j=0; j < this.keyValuePairs.length; j++) {
   if(this.keyValuePairs[j].split("=")[0] == s)
    return unescape(this.keyValuePairs[j].split("=")[1]);
  }
  return false;
 }
 this.getParameters = function() {
  var a = new Array(this.getLength());
  for(var j=0; j < this.keyValuePairs.length; j++) {
   a[j] = this.keyValuePairs[j].split("=")[0];
  }
  return a;
 }
 this.getLength = function() { return this.keyValuePairs.length; } 
}

function queryString(key){
 var page = new PageQuery(window.location.search); 
 return page.getValue(key); 
}

function HideShippingMethods() {
 var shippingmethodid = "";
 var shippingtable = document.getElementById('shippingmethodtable');
 if (shippingtable) {
  var addresstable = document.getElementById('shippingaddress');
  if (addresstable) {
   var address = addresstable.rows[1].cells[0].innerHTML;
   var addresslines =  address.split(/<br>/i);
   var country = addresslines[addresslines.length-1];
   switch (country) {
    case "United Kingdom": case "United Kingdom (GB)":
     shippingmethodid = "940";
     break;
    case "Albania": case "Andorra": case "Austria": case "Belarus": case "Belgium": case "Bosnia and Herzegovina": case "Bulgaria":
    case "Croatia/Hrvatska": case "Cyprus": case "Czech Republic": case "Denmark": case "Estonia": case "Faroe Islands": case "Finland":
    case "France": case "Germany": case "Gibraltar": case "Greece": case "Guernsey": case "Hungary": case "Iceland": case "Ireland":
    case "Isle of Man": case "Italy": case "Jersey": case "Latvia": case "Liechtenstein": case "Lithuania": case "Luxembourg": case "Macedonia":
    case "Malta": case "Moldova, Republic of": case "Monaco": case "Netherlands": case "Norway": case "Poland": case "Portugal":
    case "Romania": case "Russian Federation": case "San Marino": case "Serbia and Montenegro": case "Slovak Republic": case "Slovenia":
    case "Spain": case "Sweden": case "Switzerland": case "Ukraine":
    default:
     if (custCurrency == "GBR")
      shippingmethodid = "941";
     else if (custCurrency == "Euro")
      shippingmethodid = "1210";
   }
   var shippingmethods = document.checkout.sShipMeth;
   for (var i = shippingmethods.length-1; i >= 0 ; i--) {
    if ((shippingmethods[i].value != shippingmethodid) && (shippingmethods[i].value != "948")) {
     shippingmethods[i].parentNode.parentNode.removeChild(shippingmethods[i].parentNode);
    }
   }
  }
  else {
   var shippingmethods = document.checkout.sShipMeth;
   shippingmethods[3].checked = true;
   shippingtable.style.visibility = "hidden";
   shippingtable.parentNode.appendChild(document.createTextNode("Click the button to continue. You can select your Shipping Method later."));
  }
 }
}

function EditCheckmandatoryFields() { 
 if (document.getElementById('otherrefnum')) {
  var scripts=document.getElementsByTagName('script');
  for (i = 0; i<scripts.length; i++) {
   if (scripts[i].innerHTML.search(/function checkmandatoryfields\(\) \{ return true;\}/gi) >= 0)
    scripts[i].innerHTML = scripts[i].innerHTML.replace(/function checkmandatoryfields\(\) \{ return true;\}/gi,"function checkmandatoryfields() { return CheckPORef();}");
  }
 }
}

function CheckPORef() { 
 var otherrefnum=document.getElementById('otherrefnum');
 if (otherrefnum.value.length < 2) {
  alert("Please enter a Purchase Order Reference.");
  otherrefnum.select();
  return false;
 }
 else
  return true;
}

function ResizeBanner() {
 if (currentWidth != document.documentElement.clientWidth) {
  document.getElementById('itemheader').style.width = String(document.documentElement.clientWidth - 20) + "px";
 }
 currentWidth = document.documentElement.clientWidth;
}

function SetCookie(name, value, expires, path, domain, secure) {
 var today = new Date();
 today.setTime(today.getTime());
 if (expires) {
  expires = expires * 1000 * 60 * 60 * 24;
 }
 var expires_date = new Date(today.getTime() + (expires));
 document.cookie = name + "=" +escape(value) +
  ((expires) ? ";expires=" + expires_date.toGMTString() : "") + 
  ((path) ? ";path=" + path : "") + 
  ((domain) ? ";domain=" + domain : "") +
  ((secure) ? ";secure" : "" );
}

function GetCookie(name) {	
 var start = document.cookie.indexOf(name + "=");
 var len = start + name.length + 1;
 if ((!start) && (name != document.cookie.substring(0, name.length))) return null;
 if (start == -1) return null;
 var end = document.cookie.indexOf(";", len);
 if (end == -1) end = document.cookie.length;
 return unescape(document.cookie.substring(len, end));
}

function DeleteCookie(name, path, domain) {
 if (GetCookie(name)) document.cookie = name + "=" +
  ((path) ? ";path=" + path : "") +
  ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function CheckInitialPwd() {
 var initialpwd = document.forms['main_form'].elements['custentity_initialpassword'];
 if (checkpassword(initialpwd,initialpwd,true,true,null,6))
  return true;
 else
  return false;
}

function CheckMajesticLogin() {
 if ((sMajesticWebOrder == "Yes") && (GetCookie("majestic") == "login")) {
  DeleteCookie("majestic", "/", "winebox.co.uk");
  window.location.href = "http://www.winebox.co.uk/majestic/";
 }
}

function MajesticDefaultInvoice() {
 var payterms = document.getElementsByName('sPayTerms');
 if ((payterms.length > 0) && (sMajesticWebOrder == "Yes")) {
  var placed_by = queryString("placedby");
  SetCookie("placedby", placed_by, null, "/", "checkout.netsuite.com", true);
  payterms[1].checked = true;
  document.getElementById('submitter').click();
 }
}

function MajesticSubmitOrder() {
 var ordersummary_total = document.getElementById('ordersummary_total');
 if ((ordersummary_total) && (sMajesticWebOrder == "Yes")) {
  if (GetCookie("orderplaced") == "true") {
   DeleteCookie("orderplaced", "/", "checkout.netsuite.com");
   window.location.href = "http://www.winebox.co.uk/site/majestic/orderplaced.html";
  }
  else {
   document.getElementById('otherrefnum').value = GetCookie("placedby");
   DeleteCookie("placedby", "/", "checkout.netsuite.com");
   SetCookie("orderplaced", "true", null, "/", "checkout.netsuite.com", true);
   document.getElementById('submitter').click();
  }
 }
}

function StoreGACartLines() {
 var ischeckout = document.getElementById('ordersummary_shipping');
 var carttable = document.getElementById('carttable');
 if (carttable && ischeckout) {
  SetGACartLines(carttable);
 }
}

function SetGACartLines(carttable) {
 var prefix = "UTM:I|<ORDERID>|";
 var itemidindex = 0;
 var qtyindex = 1;
 var descriptionindex = 2;
 var priceindex = 4;
 var itemid, qty, description, price;
 var cartlines = "";
 for (var i=0; i < carttable.rows.length; i++) {
  if (carttable.rows[i].id == "carttablerow"+(i-1)) {
   cartlines += prefix;
   itemid = carttable.rows[i].cells[itemidindex].firstChild.innerHTML;
   qty = carttable.rows[i].cells[qtyindex].innerHTML;
   qty = qty.replace(/[^0-9.]/g,"");
   description = carttable.rows[i].cells[descriptionindex].firstChild.innerHTML;
   price = carttable.rows[i].cells[priceindex].innerHTML;
   price = price.replace(/[^0-9.]/g,"");
   cartlines += itemid+"|"+description+"||"+price+"|"+qty;
  }
 }
 SetCookie("ga_cart_lines",cartlines,null,"/","checkout.netsuite.com","");
}

function AppendGACartLines(orderid) {
 var gacartlines = GetCookie("ga_cart_lines");
 gacartlines = gacartlines.replace(/<ORDERID>/g,orderid);
 var utmtrans = document.getElementById('utmtrans');
 if (utmtrans) utmtrans.value = utmtrans.value + gacartlines;
 DeleteCookie("ga_cart_lines","/","checkout.netsuite.com");
}

function SetGAAddress() {
 var utmtrans = document.getElementById('utmtrans');
 var address = document.getElementById('gadefaultaddress').value;
 if (utmtrans && address != "") {
  var addresslines =  address.split(/\n/i);
  var citycountry = addresslines[addresslines.length-2]+"|"+addresslines[addresslines.length-2]+"|"+addresslines[addresslines.length-1];
  var cartlines = utmtrans.value;
  utmtrans.value = cartlines.replace(/<CITY>\|<PROVINCE>\|<COUNTRY>/g,citycountry);
 }
}

function AddDonationToCart(form, itemid, qty) {
 if (form && itemid != "") {
  var qty = parseInt(qty);
  if (qty > 0) {
   var buystr = itemid + "," + qty + ";";
   form.elements['multi'].value = buystr;
   form.submit();
  }
  else {
   alert("Donations must be 1 pound or more");
   return false;
  }
 }
}

function Registration_SaveRecord() {
  if (!CheckInitialPwd()) return false;
  //if (!SetShippingItemOnRegistration()) return false;
  return true;
}

function SetShippingItemOnRegistration() {
  var shippingitem=document.getElementById('shippingitem'); 
  var countryselect=document.getElementById('country_fs'); 
  var country=countryselect.options[countryselect.selectedIndex].value;
  switch (country) {
   case "GB":
    var zipcode=document.getElementById('zipcode').value; 
    if (zipcode.search(/^(BT)|(IM)/i)==0)
     shippingitem.value = "941";
    else
     shippingitem.value = "940";
    break;
   default:
    shippingitem.value = "1210";
  }
  return true;
}

function AddOnLoadEvent(func) {
 if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", func, false);
 }
 else if (document.all) {
  attachEvent('onload', func);
 }
}

function DisplayItemIcon(icontext, imgsrc, imgurl) {
 if (!icontext || icontext=="") return;
 document.write('<a href="'+imgurl+'"><img src="'+imgsrc+'" border="0" alt="'+icontext+'" style="position: absolute; top: 66px; right: 0px; z-index: 100;"></a></div>');
}

function AutoLogin() {
 if (document.getElementById('login') && !IsLoggedIn()) {
  var usr = GetCookie("mm_username");
  var pwd = GetCookie("mm_password");
  if (usr && usr!="" && pwd && pwd!="") {
   usr = Decrypt(usr);
   pwd = Decrypt(pwd);
   document.getElementById('retemail').value = usr;
   document.getElementById('retpwd').value = pwd;
   SaveLoginCredentials(usr, pwd);
   document.getElementById('login').submit();
  }
 }
}

function RememberLoginCredentials(usr, pwd) {
 var d = document;
 var save_login = d.getElementById('save_login');
 if (save_login && save_login.checked) {
  SaveLoginCredentials(usr, pwd);
 }
 else {
  SaveLoginCredentials("", "");
 }
}

function SaveLoginCredentials(usr, pwd) {
 if (usr!="" && pwd!="") {
  SetCookie("mm_username", Encrypt(usr), 12, "/", "checkout.netsuite.com");
  SetCookie("mm_password", Encrypt(pwd), 12, "/", "checkout.netsuite.com");
 }
 else {
  DeleteCookie("mm_username");
  DeleteCookie("mm_password");
 }
}

function Encrypt(theText) {
 output = new String;
 Temp = new Array();
 Temp2 = new Array();
 TextSize = theText.length;
 for (i = 0; i < TextSize; i++) {
  rnd = Math.round(Math.random() * 122) + 68;
  Temp[i] = theText.charCodeAt(i) + rnd;
  Temp2[i] = rnd;
 }
 for (i = 0; i < TextSize; i++) {
  output += String.fromCharCode(Temp[i], Temp2[i]);
 }
 return output;
}

function Decrypt(theText) {
 output = new String;
 Temp = new Array();
 Temp2 = new Array();
 TextSize = theText.length;
 for (i = 0; i < TextSize; i++) {
  Temp[i] = theText.charCodeAt(i);
  Temp2[i] = theText.charCodeAt(i + 1);
 }
 for (i = 0; i < TextSize; i = i+2) {
  output += String.fromCharCode(Temp[i] - Temp2[i]);
 }
 return output;
}

function OpenOnlineBrochure(url) {
 if (document.getElementById) {
  var width = screen.availWidth;
  var height = screen.availHeight;
  var windowFeatures = "width=" + width + ",height=" + height + ",status=no,resizable=yes,left=0,top=0screenX=0,screenY=0";
  myWindow = window.open(url, "subWind", windowFeatures);
  myWindow.focus();
  return false;
 }
 else {
  return true;
 }
}

function SavePromoCodeToken() {
 var promocode = queryString('wbpromocode');
 var redirect = queryString('wbredirect');
 if (promocode && promocode!='') {
  var page_url = document.location.href;
  if (page_url.search(/checkout\.netsuite\.com/gi) != -1)
   SetCookie("wbpromocode", promocode, null, "/", 'checkout.netsuite.com', true);
  //else
  // AddOnLoadEvent(function () { LoadHiddenPage(CheckoutUrl, 'wbpromocode', promocode); });
  if (redirect && redirect!='') location.href = redirect;
 }
}

function LoadHiddenPage(url, name, value) {
 url = url+((url.search(/\?/g)==-1)?'?':'&')+name+'='+encodeURI(value);
 /*var xmlrequest = createXMLHttpRequest();
 xmlrequest.open("GET", url, true);
 xmlrequest.onreadystatechange = function() {
  var done = 4, ok = 200;
  if (xmlrequest.readyState == done && xmlrequest.status != ok) {
   alert("There was an error trying to add the gift certificate to your cookies. Please contact us at sales@thewbc.co.uk.");
  }
 };*/
 var body = document.getElementsByTagName('body')[0];
 var iframe = document.createElement('iframe');
 iframe.width = 0;
 iframe.height = 0;
 iframe.style.display = 'none';
 iframe.src = url;
 body.appendChild(iframe);
}

function createXMLHttpRequest() {
 if (typeof XMLHttpRequest != "undefined") {
  return new XMLHttpRequest();
 }
 else if (typeof ActiveXObject != "undefined") {
  try {
   return new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
   try {
    return new ActiveXObject("Microsoft.XMLHTTP");
   } catch (E) {
    throw new Error("Microsoft.XMLHTTP not supported");
   }
  }
 } 
 else if (window.createRequest) {
 	return window.createRequest();
 }
 else {
  throw new Error("XMLHttpRequest not supported");
 }
}

function SetPromoCodeToken() {
 var order_minimum = 150;
 var promocode = GetCookie('wbpromocode');
 var ordertotal = CalcOrderTotal(false);
 if (promocode && promocode!='' && ordertotal>=order_minimum) {
  //document.location.href='/app/site/backend/setcheckoutvalue.nl?c=612123&n=1&sc=4&sNumber='+giftcert;
  document.location.href='/app/site/backend/setcheckoutvalue.nl?c=612123&n=1&sc=4&kReferralCode='+promocode;
  DeleteCookie('wbpromocode',"/","checkout.netsuite.com");
 }
}

function RunAtSubmitAndReview(parms) {
 AddShippingMethodMessage();
 AddDeliverySignTickbox();
 AddMsgToDeliveryInstructions();
 SetPromoCodeToken();
 CustomiseDeliveryContactName();
 ShowVATRegMessage(parms);
}

function CustomiseDeliveryContactName() {
 var d = document;
 var shipaddress = d.getElementById("shippingaddress");
 if (!shipaddress) shipaddress = d.getElementById("address");
 if (shipaddress) {
  var val = "";
  var field = d.getElementById("custbody9");
  if (field) {
   bb1FindParentNodeByTag(field, "tr").style.display = "none";
   val = field.value;
  }
  var div = d.createElement("DIV");
  div.className = "delivery-contact-name";
  div.innerHTML = '<label>Delivery Contact Name</label><input type="text" id="mm_deliverycontactname" onchange="return DeliveryContactName_OnChange(this);" value="' + val + '" /><p>Fill in this box if a contact name <br />is needed on the courier label</p>';
  if (shipaddress.id == "shippingaddress")
   shipaddress.parentNode.insertBefore(div, shipaddress);
  else
   shipaddress.rows[1].cells[0].insertBefore(div, shipaddress.rows[1].cells[0].firstChild);
 }
}

function DeliveryContactName_OnChange(obj) {
 setWindowChanged(window, true);
 var field = document.getElementById("custbody9");
 if (field) field.value = obj.value;
 document.getElementById('server_commands').contentWindow.location.replace('/app/site/backend/setcheckoutvalue.nl?sc=4&redirect=none&custbody9='+encode(obj.value));
}

function AddMsgToDeliveryInstructions() {
 var d = document;
 var deliveryinstructions = d.getElementById("custbody_web_deliveryinstructions_fs");
 if (deliveryinstructions) {
  var msg_div = d.createElement("DIV");
  msg_div.style.margin = "10px 0 0 0";
  msg_div.style.color = "red";
  msg_div.style.fontSize = "12px";
  msg_div.innerHTML = "* Please note that parcels cannot be left by the driver without a signature.";
  deliveryinstructions.parentNode.appendChild(msg_div);
 }
}

function DeliveryTermsPopup() {
 var w=window.open ('','deliveryterms','scrollbars=yes,resizable=yes,width=600,height=400');
 w.document.write('<h4>Deliveries</h4><p>Parcel deliveries are made by our courier DHL and pallet orders by our pallet company Palletline. Deliveries are made between  08:30am &ndash; 6:00pm. It is essential that your order is consigned to a &lsquo;manned&rsquo; address, where our courier can obtain a signature on delivery. If the courier is unable to make the delivery to the specified address and has to return at a later date, a supplementary charge may have to be made.</p><h4>Delivery within UK Mainland</h4><p>We aim for next working day delivery, however please allow up to 2 &ndash; 3 working days during busy periods. A next day delivery services is not available for the following Scottish postcodes, please allow 2 to 4 days for delivery: FK17-22, G83, IV33-39, KW1-3, KW5-14, PA21-33, PA35-40, PH18-26, PH30-42.</p><h4>Deliveries outside UK Mainland</h4><p>Please allow up to 5 working days for delivery.</p>');
}

function AddDeliverySignTickbox() {
 if (getRadioValue(document.getElementsByName("sShipMeth"))!="948") {
  var row = document.getElementById("additionalfieldstable").insertRow(8);
  var cell = row.insertCell(0);
  cell.colSpan = 2;
  cell.className = "text";
  cell.innerHTML = '<input type="checkbox" id="deliveryterms" class="checkbox">I understand that someone must be present to sign for this delivery <a onclick="DeliveryTermsPopup(); return false" href="#">?</a>';
  
  function CheckDeliveryTerms() {
   if (!document.getElementById("deliveryterms").checked) {
    alert('Please read and agree to the delivery terms');
    return false;
   }
   return true
  }
  
  var checkout = document.forms['checkout'];
  checkout.ns_onsubmit = checkout.onsubmit;
  checkout.onsubmit = function(e) {
   if (!CheckDeliveryTerms())
    return false;
   else if (typeof this.ns_onsubmit == "function")
    return this.ns_onsubmit();
  }
  
  var submitter = checkout.submitter;
  submitter.ns_onclick = submitter.onclick;
  submitter.onclick = function(e) {
   if (!CheckDeliveryTerms())
    return false;
   else if (typeof this.ns_onclick == "function")
    return this.ns_onclick();
  }
  
 }
}

function ShowVATRegMessage(parms) {
 var eccountries = parms.eccountries.split(", ");
 var vatregnumber = parms.vatregnumber;
 var vatregnumber_msg = parms.vatregnumber_message;
 var billcountry = parms.billcountry;
 
 // Set default vat reg number
 var vatregnumber_input = document.getElementById('custbody_web_vatregnumber');
 if (vatregnumber_input) {
  vatregnumber_input.value = vatregnumber;
 }
 
 // Display message below VAT Reg Number field
 var vatregnumber_span = document.getElementById('custbody_web_vatregnumber_fs');
 if (vatregnumber_span) {
  var message = document.createElement("DIV");
  message.innerHTML = vatregnumber_msg;
  vatregnumber_span.parentNode.appendChild(message);
 }
 
 // Show/hide VAT Reg Number if country is in EC
 var billingaddress_tbl = document.getElementById("billingaddress");
 if (vatregnumber_input && billingaddress_tbl) {
   var found = false;
   var billingaddress = billingaddress_tbl.rows[1].cells[0].innerHTML;
   var country = billingaddress.split("<br>");
   country = country[country.length-1];
   for (var i=0, l=eccountries.length; i < l; i++) {
    if (country == eccountries[i]) {
     found = true;
     break;
    }
   }
   if (!found)
    bb1FindParentNodeByTag(vatregnumber_input, "tr").style.display = "none";
 }
}

function AddShippingMethodMessage() {
 
 function DisplayMessage(msg) {
  var table = document.getElementById("shippingmethodtable");
  var cell = table.insertRow(table.rows.length).insertCell(0);
  cell.className = "text";
  cell.innerHTML = msg;
 }
 
 var shipmethod = getRadioValue(document.getElementsByName("sShipMeth"));
 
 switch (shipmethod) {
  case "940": // UK Mainland
   DisplayMessage('<p style="color:#AF344C;">Please note that even though orders are despatched on a next working day service for UK Mainland we do not guarantee this. Please allow up 2 &ndash; 3 working days for delivery. View our <a href="http://www.wbc.co.uk/faq/delivery-and-discounts">Delivery FAQs</a> to learn more.</p>');
   break;
  case "948": // Collection
   DisplayMessage('<p style="color:#AF344C;">You have selected to collect your order from our London Warehouse.<br>Orders can be collected Monday to Friday 09:00 to 17:00 from:<br><br>WBC<br>Unit 11 Ellerslie Square<br>Lyham Road<br>London<br>SW2 5DZ</p>');
   break;
  default: // Others
   DisplayMessage('<p style="color:#AF344C;">Please note that even though orders are despatched on a 2 to 3 working day service, we do not guarantee this. Please allow up to 5 working days for delivery. View our <a href="http://www.wbc.co.uk/faq/delivery-and-discounts">Delivery FAQs</a> to learn more.</p>');
 }
 
}

function ShowSCPopupMessage() {
 
 if (!IsEmpty(custbody_sc_popupmessage)) alert(custbody_sc_popupmessage);
 
}

// Utility functions
function bb1FindParentNodeByTag(node, target_tag) {
 var max_iterations = 50, count = 0;
 if (!node || !target_tag || target_tag=='') return null;
 var found = false, parent_node = node.parentNode;
 do {
  count++;
  if (!parent_node) break;
  if (target_tag.toUpperCase() == parent_node.tagName)
   found = true;
  else
   parent_node = parent_node.parentNode;
 } while (!found && count <= max_iterations)
return (count <= max_iterations) ? parent_node : null;
}

function AddOnLoadEvent(func) {
 if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", func, false);
 }
 else if (document.all) {
  attachEvent('onload', func);
 }
}

function IsEmpty(val) {

 return (val == null || val == "");
 
}



