try {
  // prevent background flicker in IE:
  document.execCommand("BackgroundImageCache", false, true); 
} catch(e) {}


String.prototype.normalizeSpace = function() {
  // trim and replace repeated spaces, newlines and tabs with a single space:
  return this.replace(/^\s*|\s(?=\s)|\s*$/g, "");
}




/* user agent sniffing shortcuts */
var ua = {};
with (ua) {
  ua.toString = function() { return navigator.userAgent; };
  ua.test = function(s) { return toString().toLowerCase().indexOf(s.toLowerCase()) > -1; };
  ua.gecko = test("gecko") && !test("webkit");
  ua.webkit = test("webkit");
  ua.opera = test("opera");
  ua.ie = test("msie");
  ua.ie6 = test("msie 6");
  ua.mac = test("mac");
  ua.win = test("windows");
}




/* Scaling framework to handle viewport width/text size ratio */
var Scaling = {
  Node: function(n) {
    /* scaling node is returned by modifier function, using original properties
       of n to revert to previous state */
    var that = this;
    this.parentNode = n.parentNode;
    this.nextSibling = n.nextSibling;
    if (n.nodeType == 1) this.className = n.className;
    this.revert = function() {
      if (n.nodeType == 1) n.className = that.className;
      if (n != document.documentElement) {
        if (that.parentNode) { // look up original parentNode
          if (that.nextSibling) // move node before original nextSibling
            that.parentNode.insertBefore(n, that.nextSibling);
          else that.parentNode.appendChild(n);
        }
        else // node newly created, so remove it
          n.parentNode.removeChild(n);
      }
    }
  },
  Function: function(fn) {
    // scaling function using fn as reverting function
    this.revert = fn;
  },
  Rule: function(ratio, fn) {
    // rule handle depending on ratio of viewport width and font size
    var that = this;
    this.objects = null;
    this.run = function() { // activation of rule
      if (Scaling.getRatio() >= ratio) { // activate modifier functions in fn
        if (!that.objects) { // objects are returned by modifiers
          var r = fn();
          that.objects = r.length ? r : [r]; // return value of fn can be array
        }
      }
      else if (that.objects) { // revert modifiers in reverse order
        that.objects.reverse();
        that.objects.each (function(ob) {
          if(ob) ob.revert();
        });
        that.objects = null;
      }
    };
  },
  rules: [], // rules array
  addRule: function(width, fontSize, fn) {
    /* arguments: viewport width, computed font size on body element at default text zoom level,
       wrapper function containing modifiers */
    if (!(width && fontSize && fn)) return;
    Scaling.rules.push(new Scaling.Rule(width / fontSize, fn));
  },
  timerId: 0, // identifier for scaling loop
  runRules: function() { // scaling loop, checking conditions for each rule
    var r = Scaling.getRatio();
    if (r != Scaling.lastRatio) {
      var narrowing = r < Scaling.lastRatio; // is ratio smaller than last time, effectively narrowing readable area?
      if (narrowing) Scaling.rules.reverse(); // then run rules in reverse order
      Scaling.rules.each(function(sr) {
        sr.run();
      });
      if (narrowing) Scaling.rules.reverse(); // back to normal
      Scaling.lastRatio = r;
      if (typeof Scaling.onRatioChange == "function") // custom event trigger
        Scaling.onRatioChange();
    }
    Scaling.timerId = setTimeout(Scaling.runRules, 1000); // loop through rules every 1000 ms
  },
  ratioElement: null,
  createRatioElement: function() { // create element to calculate runtime ratio
    var n = document.body.appendChild(document.createElement("div"));
    n.style.position = "absolute";
    n.style.top = "0";
    n.style.left = "-1234em";
    n.style.width = n.style.height = "1em";
    n.style.overflow = "hidden";
    n.style.fontSize = "100%";
    Scaling.ratioElement = n;
  },
  lastRatio: null, // previous ratio
  getRatio: function() { // divide viewport width by font size
    var w = 0;
    if (document.documentElement && document.documentElement.clientWidth)
      w = document.documentElement.clientWidth;
    else if (document.body && document.body.clientWidth)
      w = document.body.clientWidth;
    else if (window.innerWidth)
      w = window.innerWidth - 18;
    return w / Scaling.ratioElement.offsetHeight; // height is 1em in pixels
  },
  setup: function() { // use setup function on DOM content loaded event
    if (Scaling.timerId == 0) { // only one instance of scaling loop allowed
      Scaling.createRatioElement();
      Scaling.runRules();
    }
  },
  // modifier functions below; return object to make reverting possible
  execute: function(fn1, fn2) {
    if (!(fn1 && fn2)) return;
    fn1();
    return new Scaling.Function(fn2);
  },
  appendChild: function(n, ref) {
    if (!(n && ref)) return;
    var sn = new Scaling.Node(n);
    ref.appendChild(n);
    return sn;
  },
  insertBefore: function(n, ref) {
    if (!(n && ref)) return;
    var sn = new Scaling.Node(n);
    ref.parentNode.insertBefore(n, ref);
    return sn;
  },
  insertAfter: function(n, ref) {
    if (!(n && ref)) return;
    var sn = new Scaling.Node(n);
    ref.parentNode.insertBefore(n, ref).parentNode.insertBefore(ref, n);
    return sn;
  },
  addClassName: function(n, s) {
    if (!(n && s)) return;
    var sn = new Scaling.Node(n);
    n.className += " " + s;
    return sn;
  },
  replaceClassName: function(n, s) {
    if (!(n && s)) return;
    var sn = new Scaling.Node(n);
    n.className = s;
    return sn;
  }
};
// add rules in ascending order of ratio
Scaling.addRule(300, 12, function() {
  return Scaling.addClassName(document.body, "size_s");
});
/*
Scaling.addRule(580, 12, function() {
  return Scaling.addClassName(document.body, "size_m");
});
*/
Scaling.addRule(580, 12, function() {
  return [
    Scaling.addClassName(document.body, "size_m"),
    Scaling.insertBefore($("user"), $("to_about"), $("to_customerservice"), $("to_delivery")),
    Scaling.appendChild($("nav_generic"), $("header")),
    Scaling.appendChild($("nav_main"), $("header"))
  ];
});
Scaling.addRule(760, 12, function() {
  return Scaling.addClassName(document.body, "size_l");
});
Scaling.addRule(900, 12, function() {
  return Scaling.addClassName(document.body, "size_xl");
});
Scaling.addRule(1100, 12, function() {
  return Scaling.addClassName(document.body, "size_xxl");
});
/* Scaling framework end */




/* hide rendering of page to prevent layout jumping caused by scaling */
function addCssRule(selector, properties, media) {
  var nl = document.getElementsByTagName("style");
  var n, a;
  if (nl.length > 0) a = nl[nl.length - 1].getAttribute("media");
  if (nl.length == 0 || (nl.length > 0 && a != null && a != "" && a != "all")) {
    n = document.createElement("style");
    n.setAttribute("type", "text/css");
    n.setAttribute("media", "all");
    document.getElementsByTagName("head")[0].appendChild(n);
  }
  else n = nl[nl.length - 1];
  var cssRule = selector + " { " + properties + " }";
  if (media) cssRule = "@media " + media + " { " + cssRule + " }";
  if (n.styleSheet) n.styleSheet.cssText += cssRule; // IE
  else n.appendChild(document.createTextNode(cssRule));
}

function hideRendering() {
  if (!init.done) {
    addCssRule("body", "visibility: hidden;", "screen");
  }
}
function showRendering() { // paint page after scaling
  if (document.body) document.body.style.visibility = "visible";
}
if (screen.width >= 640) { // only on larger screens
  hideRendering();
  window.onunload = hideRendering;
}




/* CorneredBox function to add corners to any element */
function CorneredBox(n) {
  var that = this;
  var div = document.createElement("div");
  div.className = "corner corner_tl";
  this.tl = n.appendChild(div);
  div = document.createElement("div");
  div.className = "corner corner_tr";
  this.tr = n.appendChild(div);
  div = document.createElement("div");
  div.className = "corner corner_br";
  this.br = n.appendChild(div);
  div = document.createElement("div");
  div.className = "corner corner_bl";
  this.bl = n.appendChild(div);
  if (n.style.position != "relative" && n.style.position != "absolute")
    n.style.position = "relative";
  this.compensateIE = function() { // to compensate rounding error in IE 6
    if (ua.ie6) {
      that.tr.style.right = that.br.style.right = (n.offsetWidth % 2 == 1) ? "-1px" : "0";
      that.br.style.bottom = that.bl.style.bottom = (n.offsetHeight % 2 == 1) ? "-1px" : "0";
    }
  }
  this.compensateIE();
  CorneredBox.instances.push(this);
}
CorneredBox.compensateIEAll = function() {
  CorneredBox.instances.each(function(cb) {
    cb.compensateIE();
  });
};
CorneredBox.instances = [];
CorneredBox.setup = function(nl) {
  if (!nl.length) return;
  nl.each(function(n) {
    if (n) new CorneredBox(n);
  });
};
Scaling.onRatioChange = function() {
  if (ua.ie) CorneredBox.compensateIEAll();
};
/* CorneredBox end */




function setupExternalLinks() {
  var nl = document.getElementsByClassName("external");
  nl.each(function(n) {
    n.target = "_blank";
  });
}




/* form initialization functions */
function setDefaultInputValue(input, defaultValue) {
  if (!(input && defaultValue)) return;
  input.defValue = defaultValue;
}

function setupForms() {
  $A(document.body.getElementsByTagName("form")).each(function(form) {
    if (form.getAttribute("id") != "shoplist_form") {
      var required = [];
      for (var i = 0, l = form.elements.length; i < l; i++) {
        var field = form.elements[i];
        if (field.tagName.toLowerCase() == "button" || field.type == "hidden") continue;
        var lbl = field.htmlLabel = $("label_" + field.id);
        //if (!lbl) continue;
        var text = (field.type == "text" || field.tagName.toLowerCase() == "textarea");
        var require = false;
        if (lbl && (lbl.className.indexOf("required") > -1
            || $A(document.getElementsByClassName("required", lbl)).length > 0)) {
          require = true;
          required.push(lbl);
        }
        var useDefault = function(n) {
          n.value = n.value.normalizeSpace();
          if (n.defValue && n.value == "") {
            n.value = n.defValue;
            n.className += " default_value";
          }
        };
        if (require) {
          field.onblur = function() {
            var lbl = this.htmlLabel;
            this.value = this.value.normalizeSpace();
            if (this.value == "" || this.value == this.defValue)
              lbl.className += " error";
            else
              lbl.className = lbl.className.replace(new RegExp("error\\b"), "");
            if (text) useDefault(this);
          };
        }
        else if (text) {
          field.onblur = function() {
            useDefault(this);
          };
        }
        if (text) {
          field.onfocus = function() {
            if (this.value == this.defValue) {
              this.value = "";
              this.className = this.className.replace(new RegExp(" default_value\\b"), "");
            }
          };
          useDefault(field);
        }
        // TODO: handle required checkboxes and radiobuttons!
      }
      form.onsubmit = function() {
        var error = [];
        required.each(function(lbl) {
          var field = $(lbl.id.substring(6));
          field.onblur();
          if (field.value == "") error.push(lbl);
        });
        if (error.length > 0) {
          var s = "Het formulier is niet correct ingevuld om de volgende reden:\n\n";
          error.each(function(lbl) {
            s += "- " + lbl.lastChild.nodeValue.normalizeSpace() + " is verplicht.\n";
          });
          alert(s);
          $(error[0].id.substring(6)).focus();
          return false;
        }
        else { // no errors, remove default values before submitting
          $A(this.getElementsByTagName("input")).each(function(field) {
            if (field.getAttribute("type") == "text")
              field.onfocus();
          });
          $A(this.getElementsByTagName("textarea")).each(function(field) {
            field.onfocus();
          });
        }
      };
    }
  });
}
/* form functions end */




function setupCloseButtons() {
  $A($$("a.close_app")).each(function(a) {
    a.onclick = function() {
      window.close();
      return false;
    }
  });
}




/* collapsing refinement of recipes */
function setupRefinement() {
  if (!$("refine")) return;
  var uls = $A($("refine").getElementsByTagName("ul"));
  uls.each(function(ul) {
    if (ul.parentNode.id != "refine_extra") {
      var lis = ul.getElementsByTagName("li");
      if (lis.length > 4) {
        var div = ul.parentNode;
        var a = div.appendChild(document.createElement("p")).appendChild(document.createElement("a"));
        a.appendChild(document.createTextNode("Meer"));
        a.className = "more";
        a.href = "#" + div.id;
        a.onclick = function() {
          var nl = this.parentNode.parentNode.getElementsByTagName("li");
          for (var i = 4; i < nl.length; i++) {
            nl[i].style.display = (this.showing) ? "block" : "none";
          }
          this.firstChild.nodeValue = (this.showing) ? "Minder" : "Meer";
          this.className = (this.showing) ? "less" : "more";
          this.showing = !this.showing;
          return false;
        };
        a.onclick();
      }
    }
  });
}



/* initialize when DOM is loaded */
var initFunctions = [
  function() {
    document.body.className += " javascript-enabled";
    setDefaultInputValue($("search_field"), "Zoeken");
    setDefaultInputValue($("rq"), "Ingrediënt of receptnaam");
  },
  Scaling.setup,
  function() {
    if ($("shoplist") && ShopList)
      var shoplist = new ShopList($("shoplist"));
    var mailer = $("mail-a-friend");
    if (mailer) {
      mailer.onclick = function() {
        window.open(mailer.getAttribute("href"), "mailafriend", "width=420,height=560,modal");
        return false;
      };
    }
  },
  showRendering,
  setupExternalLinks,
  //setupForms,
  setupCloseButtons,
  setupRefinement,
  setupFAQ,
  function() { // set up corners
    CorneredBox.setup([$("to_home"), $("to_food"), $("to_life"),
      $("to_offerings"), $("to_shopping"), $("to_assortment"),
      $("to_main_site"), $("to_about"), $("to_service"), $("to_stores"), $("to_customerservice"), $("to_delivery"),
      $("user"), $("user_login"), $("to_user_login"), $("cookbook_sidebar"),
      $("cookbook_sidebar_me"), $("recipe_info"), $("recipe_shop_online")]);
    CorneredBox.setup($$(".paging"));
    CorneredBox.setup($$(".paging a"));
    CorneredBox.setup($$(".wat_is"));
    CorneredBox.setup($$(".wat_is p.singular a"));
    CorneredBox.setup(document.getElementsByClassName("button"));
    CorneredBox.setup(document.getElementsByClassName("recipe_category"));
    CorneredBox.setup($$(".round_it"));
    CorneredBox.setup(document.getElementsByClassName("block"));
    CorneredBox.setup($$(".actions_order"));
    CorneredBox.setup($$(".phone_item"));
    CorneredBox.setup($$("#tertiary .item"));
    CorneredBox.setup($$("#offers div.highlight"));
    CorneredBox.setup($$(".phone_offer"));
    CorneredBox.setup($$(".telecomshop.step2 .pay_method_ideal"));
    CorneredBox.setup($$("#telecom_banner"));
    CorneredBox.setup($$(".home_subbanner"));
  },
  function() {
    setupBorders(document.getElementsByClassName("error_notices"));
  },
  function() {
    setupBorders(document.getElementsByClassName("warning_notices"));
  },
  setupErrorNotices,
  setupWarningNotices,
  setupRecipe,
  setupLogin,
  setupCookbook,
  setupBannerStrips,
  setupSubHome
];
function addInit(fn) {
  if (typeof fn != "function") return;
  initFunctions.push(fn);
}
function init() {
  if (arguments.callee.done) return;
  arguments.callee.done = true;
  initFunctions.each(function(fn) {
    fn();
  });
}
if (document.addEventListener) document.addEventListener("DOMContentLoaded", init, false);
if (ua.ie) {
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") init();
  };
}
if (ua.webkit && document.readyState) {
  function checkReady() {
    if (document.readyState != "loading") init();
    else setTimeout(checkReady, 10);
  }
  checkReady();
}
window.onload = init;
/* initialization end */




/* sitestat functions */
function sitestat(s) {
  var n = new Image();
  //n.src = "http://nl.sitestat.com/ahold/ah/s?" + s + "&random=" + Math.round((Math.random() * 100000));
  n.src = "http://nl.sitestat.com/ahold/ah/s?" + s;
}

function sitestatSWF(localUser) {
  if (typeof com != "undefined"
		&& com.deconcept != "undefined"
		&& com.deconcept.SWFObjectUtil != "undefined") {
    var flashVersion = com.deconcept.SWFObjectUtil.getPlayerVersion();
    var n = new Image();
    n.src = "http://nl.sitestat.com/ahold/ah/s?meting."
      + (localUser ? "intern" : "publiek")
      + ".swf." + flashVersion.major + "."
      + flashVersion.minor + "."
      + flashVersion.rev
      + "&random=" + Math.round((Math.random() * 100000));
  }
}



/* innerHTML setter with CorneredBox setup */
function setInnerHTMLWithSauce(n, html) {
  n.innerHTML = html;
  CorneredBox.setup(document.getElementsByClassName("button", n));
  CorneredBox.setup(document.getElementsByClassName("block", n));
}




/* dialog function to create a nice layer on page */
function dialog(s, options) {
  /*if (false) {
    var div1 = document.createElement("div");
    div1.className = "dialog_wrapper";
    function remove() {
      Element.remove(div1);
    }
    var div2 = div1.appendChild(document.createElement("div"));
    div2.className = "dialog";
    div2.appendChild(document.createElement("p")).appendChild(document.createTextNode(s));
    var ul = div2.appendChild(document.createElement("ul"));
    var a1 = ul.appendChild(document.createElement("li")).appendChild(document.createElement("a"));
    a1.appendChild(document.createTextNode(options[0][0]));
    a1.href = "#";
    a1.onclick = function() {
      remove();
      options[0][1]();
    }
    var a2 = ul.appendChild(document.createElement("li")).appendChild(document.createElement("a"));
    a2.appendChild(document.createTextNode(options[1][0]));
    a2.href = "#";
    a2.onclick = function() {
      remove();
      options[1][1]();
    }
  }
  else*/ if (confirm(s)) options[0][1]();
  else if (typeof options[1][1] == "function") options[1][1]();
}


function validateEmail(s) {
  return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/.test(s))
}


function updateRecipes(cookbookShared) {
  if (!cookbookShared) {
    var sharedChecked = false;
    var shares = $$("input.share");
    shares.each(function(share) {
      if (share.checked) {
        sharedChecked = true;
      }
    });
    if (sharedChecked && confirm('Wilt u ook uw kookschrift delen met anderen? (anders zijn uw gedeelde recepten nog steeds niet zichtbaar)')) {
      document.my_recipes.share_cookbook.value = 'Y';
    }
  }
  $('my_recipes').submit();
}

var AHDialog = Class.create();
AHDialog.prototype = {
  title: "",
  text: "",
  initialize: function() {
    this.buttons = document.createElement("form");
    this.buttons.id = "dialog_buttons";
  },
  addTitle: function(title) {
    this.title = title;
  },
  addText: function(text) {
    this.text = text;
  },
  addDestroyer: function(label) {
    var button = document.createElement("input");
    button.value = label;
    button.id = "close_button";
    button.className = 'button';
    button.type = 'button';
    Event.observe(button,'click',function() {
      if($('ok_button')) {
        Event.stopObserving($('ok_button', 'click'));
      }
      Event.stopObserving(button,'click');
      $("primary").removeChild($('ah_dialog'));
    });
    this.buttons.appendChild(button);
  },
  addAction: function(label, action) {
    var button = document.createElement("input");
    button.value = label;
    button.id = "ok_button";
    button.className = 'button';
    button.type = 'button';
    Event.observe(button,'click',action);
    this.buttons.appendChild(button);
  },
  build: function() {
    this.dialog = document.createElement("div");
    this.dialog.id = "ah_dialog";
    if(this.title != "") {
      this.dialog.appendChild(document.createElement("h1")).appendChild(document.createTextNode(this.title));
    }
    if(this.text != "") {
      this.dialog.appendChild(document.createElement("p")).appendChild(document.createTextNode(this.text));
    }
    this.dialog.appendChild(this.buttons);
    $("primary").appendChild(this.dialog);
  }
}

// FAQ
function setupFAQ() {
  resetFAQ();
  var nl = $$("p.question a");
  nl.each(function(n) {
    var id = n.href.substr(n.href.lastIndexOf('#') + 1);
    n.href = "javascript:openQuestion('" + id + "');";
  });
}
function resetFAQ(excluding) {
  var nl = $$("p.question");
  nl.each(function(n) {
    Element.removeClassName(n.parentNode, "answered");
  });
  nl = $$("div.answer");
  nl.each(function(n) {
    if (n != excluding) Effect.BlindUp(n);
  });
}
function openQuestion(id) {
  var n = $(id);
  if (!n) return;
  if (n.style.display != "none") {
    resetFAQ();
    return;
  }
  resetFAQ(n);
  Element.addClassName(n.parentNode, "answered");
  Effect.BlindDown(n);
}

function setupBorders(nl) {
  if (!nl) return;
  nl.each(function(n1) {
    var className = n1.className + "_border ";
    n1.className += " " + className + "border_1";
    var n2 = document.createElement("div");
    n2.className = className + "border_2";
    var n3 = document.createElement("div");
    n3.className = className + "border_3";
    var n4 = document.createElement("div");
    n4.className = className + "border_4";
    var n5 = document.createElement("div");
    n5.className = className + "border_5";
    for (var n = n1.firstChild; n; n = n1.firstChild)
      n5.appendChild(n);
    n4.appendChild(n5);
    n1.appendChild(n2);
    n1.appendChild(n3);
    n1.appendChild(n4);
  });
}

var ErrorNoticesZIndex = 1;
function setupErrorNotices() {
  var nl = document.getElementsByClassName("error_notices");
  if (nl) nl.reverse();
  nl.each(function(n) {
    n.parentNode.style.zIndex = ErrorNoticesZIndex++;
    var onFieldFocus = function(e) {
      var that = Event.element(e);
      for (var parent = that.parentNode; parent; parent = parent.parentNode) {
        if (parent.hasClassName("fields")) {
          parent.style.zIndex = ErrorNoticesZIndex++;;
          break;
        }
      }
    };
    var iterator = function(field) {
      Event.observe(field, "focus", onFieldFocus);
    }
    var inputs = $A(n.parentNode.getElementsByTagName("input"));
    inputs.each(iterator);
    var selects = $A(n.parentNode.getElementsByTagName("select"));
    selects.each(iterator);
    var textareas = $A(n.parentNode.getElementsByTagName("textarea"));
    textareas.each(iterator);
    n.onclick = function(e) {
      if (inputs.length > 0) inputs[0].focus();
      else if (selects.length > 0) selects[0].focus();
      else if (textareas.length > 0) textareas[0].focus();
    }
  });
}

var WarningNoticesZIndex = 1;
function setupWarningNotices() {
  var nl = document.getElementsByClassName("warning_notices");
  if (nl) nl.reverse();
  nl.each(function(n) {
    n.parentNode.style.zIndex = WarningNoticesZIndex++;
    var onFieldFocus = function(e) {
      var that = Event.element(e);
      that.parentNode.style.zIndex = WarningNoticesZIndex++;;
    };
    var iterator = function(field) {
      Event.observe(field, "focus", onFieldFocus);
    }
    var inputs = $A(n.parentNode.getElementsByTagName("input"));
    inputs.each(iterator);
    var selects = $A(n.parentNode.getElementsByTagName("select"));
    selects.each(iterator);
    var textareas = $A(n.parentNode.getElementsByTagName("textarea"));
    textareas.each(iterator);
    n.onclick = function(e) {
      if (inputs.length > 0) inputs[0].focus();
      else if (selects.length > 0) selects[0].focus();
      else if (textareas.length > 0) textareas[0].focus();
    }
  });
}

// Enable nederland
function enableNederland(value){
  if(typeof(value) == 'undefined'){
    var element = $("country_nl");
    if(element){
      if(element.checked){
        enableNederland(true);
      } else {
        enableNederland(false);
      }
    }
   } else {
    var nl = document.getElementsByClassName('netherlands');
    var abroad = document.getElementsByClassName('abroad');
    if(value) {
      nl.each(function(it) {
        it.style.display = "";
      });
      abroad.each(function(it) {
        it.style.display = "none";
      });
    } else {
      nl.each(function(it) {
        it.style.display = "none";
      });
      abroad.each(function(it) {
        it.style.display = "";
      });
    }
  }
}

function setupRecipe() {
  if($('ing_table')) {
    writeIngredientsTable();
  }
}

function setupLogin() {
  if (!$("to_user_login")) return false;
  var trigger = $("to_user_login");
  if (!trigger) return;
  trigger.addClassName("deselected");
  var form = $("user_login");
  form.style.display = "none";
  var clickAway = function(e) {
    if (!Element.descendantOf(Event.element(e), $("user")))
      trigger.onclick();
  };
  trigger.onclick = function() {
    if (form.style.display == "none") {
      trigger.removeClassName("deselected");
      trigger.style.background = "#DEF0F8"; // fix IE
      Effect.BlindDown(form, {duration: 0.25});
      setTimeout(function() {
        $("login_userName").focus();
      }, 500);
      Event.observe(document.body, "click", clickAway);
    }
    else {
      Event.stopObserving(document.body, "click", clickAway);
      Effect.Fade(form, {duration: 0.5});
      new Effect.Highlight(trigger, {duration: 0.5, startcolor: "#DEF0F8", endcolor: "#DEF0F8", afterFinish: function() {
        trigger.style.background = "";
      }});
      trigger.addClassName("deselected");
    }
    return false;
  };
}

function setupCookbook() {
  // Setup the Cookbook dropzone
  var cb = $("cookbook_sidebar") ? $("cookbook_sidebar") : $("temp_recipe_holder");
  if (cb && (typeof Droppables !== "undefined")) {
    Droppables.add(cb, {
      accept: ["recipe", "result_recipe"],
      onDrop: function(element) {
        var cookbooks = $$("#recept_to_shoplist .cookbook a");
        if (cookbooks.length > 0) {
          for (var i = 0; i < cookbooks.length; i++) {
            location.replace(cookbooks[i].href.toString());
          }
          return false;
        }

        return false;
      }
    });
  }
  
  /*
  if ($("cookbook_sidebar")) {
    var openCloseHolder = document.createElement("p");
    var myCbInfo = document.createElement("a");
    var closeMyCbInfo = document.createElement("a");
    openCloseHolder.className = "open_close_holder";
    openCloseHolder.style.borderTop = "1px dotted #A3A3A3;";
    myCbInfo.id = "my_cb_info";
    myCbInfo.className = "opener";
    myCbInfo.onclick = function() {
      if (!$("hide_my_cb_info")) return false;
      Effect.BlindDown('hide_my_cb_info');
      setTimeout("$(\"my_cb_info\").style.display = \"none\"; $(\"close_my_cb_info\").style.display = \"block\";",900);
      return false;
    };
    myCbInfo.style.display = "none";
    myCbInfo.style.cursor = "pointer";
    
    closeMyCbInfo.id = "close_my_cb_info";
    closeMyCbInfo.className = "closer";
    closeMyCbInfo.onclick = function() {
      if (!$("hide_my_cb_info")) return false;
      Effect.BlindUp('hide_my_cb_info');
      setTimeout("$(\"my_cb_info\").style.display = \"block\"; $(\"close_my_cb_info\").style.display = \"none\";",900);
      return false;
    };
    closeMyCbInfo.style.display = "block";
    closeMyCbInfo.style.cursor = "pointer";
    
    myCbInfo.appendChild(document.createTextNode("Openen"));
    closeMyCbInfo.appendChild(document.createTextNode("Sluiten"));
    openCloseHolder.appendChild(myCbInfo);
    openCloseHolder.appendChild(closeMyCbInfo);
    $("cookbook_sidebar").appendChild(openCloseHolder);
  }
  */
}

function setAnimatedHover(n, startcolor, endcolor) {
  if (!n) return;
  function hover(e) {
    if (n.effect) n.effect.cancel();
    n.effect = new Effect.Highlight(n, {duration: 0, startcolor: startcolor, endcolor: endcolor, restorecolor: endcolor});
  }
  function unhover(e) {
    if (n.effect) n.effect.cancel();
    n.effect = new Effect.Highlight(n, {duration: 0.25, startcolor: endcolor, endcolor: startcolor, afterFinish: function() {
      n.style.background = "";
    }});
  }
  Event.observe(n, "mouseover", hover);
  Event.observe(n, "focus", hover);
  Event.observe(n, "mouseout", unhover);
  Event.observe(n, "blur", unhover);
}
/*
addInit(function() {
  if (!document.body.hasClassName("home")) setAnimatedHover($("to_home"), "#FFFFFF", "#CBEDFC");
  if (!document.body.hasClassName("food")) setAnimatedHover($("to_food"), "#FFFFFF", "#DEEBBD");
  if (!document.body.hasClassName("life")) setAnimatedHover($("to_life"), "#FFFFFF", "#F8F0CC");
  if (!document.body.hasClassName("assortment")) setAnimatedHover($("to_assortment"), "#FFFFFF", "#DDC8DE");
  if (!document.body.hasClassName("offerings")) setAnimatedHover($("to_offerings"), "#FFFFFF", "#FFE4CD");
  if (!document.body.hasClassName("shopping")) setAnimatedHover($("to_shopping"), "#FFFFFF", "#CBEDFC");
  if (!document.body.hasClassName("about")) setAnimatedHover($("to_about"), "#FFFFFF", "#CBEDFC");
  if (!document.body.hasClassName("service")) setAnimatedHover($("to_service"), "#FFFFFF", "#CBEDFC");
  if (!document.body.hasClassName("stores")) setAnimatedHover($("to_stores"), "#FFFFFF", "#CBEDFC");
});
*/

addInit(function() {
  var n = $("voorbeeld_nieuwsbrief");
  if (n) {
    n.onclick = function() {
      window.open(n.getAttribute("href"), "voorbeeld_nieuwsbrief", "width=743,height=575,scrollbars=yes,modal");
      return false;
    };
  }
});

// tbv geanimeerde banner balkjes
function setupBannerStrips()
{
  var elements = document.getElementsByClassName('banner_strip');
  window.bannerStrips = new Array();
  for (var i=0; i< elements.length; i++)
  {
    bannerStrips.push(new BannerStrip(elements[i]));
  }
}
function BannerStrip(node)
{
  this.timer = null;
  this.container = node;
  this.banners = $A(node.getElementsByTagName('A'));
  this.reflow();
  Event.observe(window,'resize',this.reflow.bindAsEventListener(this));
}
BannerStrip.prototype.reflow = function()
{
  if (this.timer)
    this.timer.stop();

	this.banners = $A(this.container.getElementsByTagName('A'));
	
  var width = this.container.getWidth();
  var maxBanners = Math.floor( width / BannerStrip.bannerWidth );
  var visisbleBannerCount = maxBanners < this.banners.length ? maxBanners : this.banners.length;
  var padding = Math.floor( (width % (BannerStrip.bannerWidth * visisbleBannerCount)) / (visisbleBannerCount-1) );
  for (var i=0; i<this.banners.length; i++)
  {
    this.banners[i].style.left = ((BannerStrip.bannerWidth + padding) * i) + 'px';
    if (i < visisbleBannerCount)
      this.banners[i].style.display = 'block';
    else
      this.banners[i].style.display = 'none';
  }
  if (maxBanners < this.banners.length && maxBanners > 0 )
  {
    this.timer = new PeriodicalExecuter(this.fade.bind(this,visisbleBannerCount+0), 5);
  }
}
BannerStrip.prototype.fade = function(offset)
{
  var options = {
    duration: 0.5,
    afterFinish: this.appear.bind(this,offset)
  }
  new Effect.Fade(this.banners[0], options);
  this.banners[offset].style.left = this.banners[0].style.left;
  
}
BannerStrip.prototype.appear = function(offset)
{
  new Effect.Appear(this.banners[offset], {duration: 0.5});
  var banner = this.banners.shift()
  this.banners.push(banner);
}
BannerStrip.bannerWidth = 173;

// only test
function setupSubHome() {
  if($('banners')) {
    setTimeout(changeBanner, 8000);
  }
  if($('banners2')) {
    setTimeout(changeBanner2, 8000);
  }
  if($('banners3')) {
    setTimeout(changeBanner3, 8000);
  }
}
var currentPosition = -1;
function changeBanner() {
  var main_el = $('banners');
  var found_hidden = false;
  var visible_count = $$("div.banner_holder").length;
  currentPosition++;
  if(currentPosition >= visible_count) currentPosition = 0;
  var holder = null;
  var first_shown = null;
  var count = 0;
  $$("div.single_banner").each(function(elm) {
    if(elm.style.display != "none" && first_shown == null) {
      if(count == currentPosition) {
        first_shown = elm;
        holder = elm.parentNode;
      } else {
        count++;
      }
    }
    if(elm.style.display == "none" && !found_hidden) {
      found_hidden = true;
      holder.insertBefore(elm, first_shown);
      Effect.Fade(first_shown,{afterFinish: function() {
        new Effect.Appear(elm);
        holder.removeChild(first_shown);
        main_el.appendChild(first_shown);
      }});
      setTimeout(changeBanner, 8000);
    }
  });
}
function changeBanner2() {
  var main_el = $('banners2');
  var found_hidden = false;
  var visible_count = $$("div.banner_holder").length;
  currentPosition++;
  if(currentPosition >= visible_count) currentPosition = 0;
  var holder = null;
  var first_shown = null;
  var count = 0;
  $$("div.single_banner").each(function(elm) {
    if(elm.style.display != "none" && first_shown == null) {
      if(count == currentPosition) {
        first_shown = elm;
        holder = elm.parentNode;
      } else {
        count++;
      }
    }
    if(elm.style.display == "none" && !found_hidden) {
      found_hidden = true;
      holder.insertBefore(elm, first_shown);
      Effect.Shrink(first_shown,{afterFinish: function() {
        new Effect.Grow(elm);
        holder.removeChild(first_shown);
        main_el.appendChild(first_shown);
      }});
      setTimeout(changeBanner2, 8000);
    }
  });
}
function changeBanner3() {
  var main_el = $('banners3');
  var found_hidden = false;
  var visible_count = $$("div.banner_holder").length;
  currentPosition++;
  if(currentPosition >= visible_count) currentPosition = 0;
  var holder = null;
  var first_shown = null;
  var count = 0;
  $$("div.single_banner").each(function(elm) {
    if(elm.style.display != "none" && first_shown == null) {
      if(count == currentPosition) {
        first_shown = elm;
        holder = elm.parentNode;
      } else {
        count++;
      }
    }
    if(elm.style.display == "none" && !found_hidden) {
      found_hidden = true;
      holder.insertBefore(elm, first_shown);
      Effect.SlideUp(first_shown,{afterFinish: function() {
        new Effect.SlideDown(elm);
        holder.removeChild(first_shown);
        main_el.appendChild(first_shown);
      }});
      setTimeout(changeBanner3, 8000);
    }
  });
}

