// ############################################################################
// ################################# DEFAULT ##################################
// ############################################################################


// ###################################
// ############## PRINT ##############
// ###################################


String.prototype.toQueryParams = function() {
  var href = this;
  if (href.match(/#/)) href = href.split('#')[0];
  if (href.match(/\?/)) href = href.split('?')[1];
  else return false;
  href = href.split('&');
  var obj = {};
  var pair;
  for (var k in href) {
	pair = href[k].split('=');
	obj[pair[0]] = pair[1];
  }
  return obj;
}


$.fn.reverse = [].reverse;

/* PrintAction function to add Javascript window.print call */
/* Writes hyperlink in element n. Styling of print link in CSS!!
   Contents of listitem with class 'print_action' is recycled in the
   inserted link.
   So:
       <li class="print_action">Afdrukken</li>
   becomes:
       <li class="print_action">
         <a href="javascript:window.print();">Afdrukken</a>
       </li>

   Using this, you can flexibly implement this generic print action behaviour.
   */
function PrintAction(n) {
  var that = this;
  var oldContent = n.innerHTML;
  var link = document.createElement("a");
  link.href = "javascript:window.print();";
  $(link).html(oldContent);
  n.replaceChild(link, n.firstChild);
}
PrintAction.setup = function(nl) {
  if (!nl.size()) return;
  nl.each(function(i,n) {
    if (n) new PrintAction(n);
  });
};
/* PrintAction end */



// ###################################
// ############## FORMS ##############
// ###################################

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

/* Returns true if the given string matches the email address pattern. */
function validateEmail(s) {
  return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,6})+$/.test(s))
}

// ###################################
// ############## CLOSE ##############
// ###################################

function setupCloseButtons() {
  $("a.close_app").each(function() {
	  var a = this;
   $(a).bind('click', function() {
      window.close();
      return false;
    });
  });
}





if (!loader) {
	var loader = new Loader();
}
loader.schedule("foldout", setupFoldFromDefaultJS);
loader.schedule("default input values", function() {
  setDefaultInputValue($("#search_field"), "Zoeken");
  setDefaultInputValue($("#rq"), "Ingredi\u00EBnt of receptnaam");
});

loader.schedule("close buttons", setupCloseButtons);
loader.schedule("print", function() {
    PrintAction.setup($(".print_action")); });
loader.schedule("shoplist notices", function () {
    // ShopListResponses isn't always available (example: mail-a-friend page)
    if (typeof ShopListResponses !== "undefined") {
      // delay the creation, because this script is loaded /before/ shoplist...
      ShopListResponses.serverMessagesHandler();
    }
  });
loader.schedule("error notices", setupErrorNotices);
loader.schedule("warning notices", setupWarningNotices);
loader.schedule("login confirm", setupLoginConfirm);
loader.schedule("cookbook", setupCookbook);
loader.schedule("disabled image ie6", disabledImgIE6);
loader.schedule("banners", setupBannerStrips);

loader.schedule("Setup stickers", setupStickers, Loader.priority.HIGH);

loader.schedule("check secondary height", checkSecondaryHeight);

// Schedule loader for droppable of tertiary
loader.schedule("droppable tertiary", droppableTertiary);




var shoplist = null;


startLoader();

/* initialization end */



// ###################################
// ############### UTILS #############
// ###################################

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


// ###################################
// ############## DIALOG #############
// ###################################

var AHDialog = function(){this.initialize();};

AHDialog.prototype = {

  title: "",
  text: false,
  dialogName: "ah_dialog",

  initialize: function() {
    this.buttons = document.createElement("form");
    this.buttons.id = "dialog_buttons";
  },

  // Add a button to the bottom button bar:
  addButton: function(button) {
    // Wrap the button in the generic rounded
    // corner solution for buttons:
    var wrapper = document.createElement('span');
    wrapper.className = 'button'; // script it
    CorneredBox(wrapper);
    wrapper.appendChild(button);
    this.buttons.appendChild(wrapper);
  },

  addTitle: function(title) {
    this.title = title;
  },

  /**
   * Set the message text of the dialog.
   *
   * @deprecated
   */
  addText: function(text) {
    this.text = document.createElement("p");
    this.text.appendChild(document.createTextNode(text))
  },

  /**
   * Set the message text of the dialog.
   *
   * @param text The given text can contain HTML tags. Applied with innerHTML or
   * a DOM element.
   */
  setText: function(text) {
		if(typeof(text) == 'object'){
			this.text = document.createElement('div').appendChild(text);
		}
		else{
			this.text = document.createElement('p');
      this.text.innerHTML = text;
		}
  },

  defineDialog: function(dialog) {
   this.dialogName = dialog;
  },

  /**
   * Handle the close_button events, removing the dialog.
   * Calls this.destroy in the end.
   */
  _onDestroyHandler: function (obj) {
	$('#ok_button, #close_button').unbind('click');

	obj.destroy();
  },

  /**
   * Adds a `Cancel` button with the given text label.
   */
  addDestroyer: function(label) {
    var button = document.createElement("input");
    button.value = label;
    button.id = "close_button";
    button.className = 'buttonelm';
    button.type = 'button';
    var obj = this;
    $(button).bind('click',function(){
    	obj._onDestroyHandler(obj);
    });
    this.addButton(button);
  },

  addAction: function(label, action, href) {
	var type;
	if (!href) type = 'input';
	else type = 'a';
    var button = document.createElement(type);
    if (!href) button.value = label;
    else {
    	button.href = href;
    	button.innerHTML = label;
    }
    button.id = "ok_button";
    button.className = 'buttonelm';
    button.type = 'button';
    $(button).bind('click',action);
    this.addButton(button);
  },

  destroy: function() {
    $('#'+this.dialogName + "_bg").remove();
    $('#'+this.dialogName).remove();

    if ($("#to_user_logout").size()) {
      var toUserLogger = $("#to_user_logout");
      if (toUserLogger && !toUserLogger.hasClass("deselected")) {
        // [KN] todo: see it happening
    	  /*
    	  new Effect.Highlight(toUserLogger, {
            duration: 0.5,
            startcolor: "#def0f8",
            endcolor: "#ffffff",
            afterFinish: function() {
              toUserLogger.style.background = "";
              toUserLogger.addClass("deselected");
            }
          });
          */
    	  
      }
	}
    // Show pluginelements
    var pluginElements = (ua.ie6) ? $("embed, object, div.kaart, select")
                                  : $("embed, object, div.kaart");
    pluginElements.each(function (i, pluginElement) {
      $(pluginElement).css({ "visibility": "visible" });
    });
  },

  /**
   * Position the given element vertically in center 'after' insertion into
   * the DOM
   */
  centerposition: function(elm) {
    // Get the viewport dimension height:
    var height;
    // Do some feature checks:
    if (window.innerHeight) {
      // All except Explorer
      height = window.innerHeight;
    } else if (document.documentElement
        && document.documentElement.clientHeight) {
      // Explorer 6 Strict Mode
      height = document.documentElement.clientHeight;
    } else if (document.body) {
      // Other Explorers
      height = document.body.clientHeight;
    }
    var pos = ((height - $(elm)[0].clientHeight) / 2);
    // Add scroll offset:
    if (window.scrollY) {
      pos += window.scrollY;
    } else if (window.pageYOffset) {
      pos += window.pageYOffset;
    } else if (document.documentElement.scrollTop) { // IE7
      pos += document.documentElement.scrollTop;
    } else if (document.body.scrollTop) { // IE6
      pos += document.body.scrollTop;
    }
    elm.style.top = pos + 'px';
  },

  build: function() {
    var body = $("body");
    var dialogBg = document.createElement("div");
    dialogBg.id = this.dialogName + "_bg";
    dialogBg.style.height = body.height() + "px";
    this.dialog = document.createElement("div");
    this.dialog.id = this.dialogName;
    if (this.title != "") {
      this.dialog.appendChild(document.createElement("h3")).appendChild(document.createTextNode(this.title));
    }
    if (this.text) {
      this.dialog.appendChild(this.text);
    }
    this.dialog.appendChild(this.buttons);

    body.css({position: "relative"})
    body[0].appendChild(dialogBg);
    $("#ah_dialog_bg").css({ opacity: 0.5 });

    // Hide pluginelements
    var pluginElements = (ua.ie6) ? $("embed, object, div.kaart, select")
                                  : $("embed, object, div.kaart");
    pluginElements.each(function () {
    	
      $(this).css({ "visibility": "hidden" });
    });

    this.dialog.style.visibility = 'hidden';
    body[0].appendChild(this.dialog);
    this.dialog.style.top = 0;
    this.centerposition(this.dialog);
    this.dialog.style.visibility = 'visible';
  }
}


// ###################################
// ########## MORE BORDERS ###########
// ###################################

function setupBorders(nl) {
  if (!nl) return;
  $(nl).each(function() {
	  var container = this;
    var className = container.className + "_border ";
    container.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";
    // move content into border_5:
    for (var n = container.firstChild; n; n = container.firstChild)
      n5.appendChild(n);
    n4.appendChild(n5);
    container.appendChild(n2);
    container.appendChild(n3);
    container.appendChild(n4);
  });
}

// ###################################
// ############# NOTICES #############
// ###################################
var ErrorNoticesZIndex = 1;

function setupErrorNotices() {
  var nl = $("div.error_notices");
  setupBorders(nl);
  if (nl) nl.reverse();
  nl.each(function() {
	  var n =this;
    n.parentNode.style.zIndex = ErrorNoticesZIndex++;
    var onFieldFocus = function(e) {
      var that = this;
      for (var parent = that.parentNode; parent; parent = parent.parentNode) {
        if (parent.nodeType == 1 && $(parent).hasClass("fields")) {
          ErrorNoticesZIndex++;
          $(parent).css({zIndex: ErrorNoticesZIndex});
          break;
        }
      }
    };
    var iterator = function(field) {
      $(field).bind("focus", onFieldFocus);
    }
    var inputs = $(n.parentNode.getElementsByTagName("input"));
    inputs.each(function(){iterator(this)});
    var selects = $(n.parentNode.getElementsByTagName("select"));
    selects.each(function(){iterator(this)});
    var textareas = $(n.parentNode.getElementsByTagName("textarea"));
    textareas.each(function(){iterator(this)});
    $(n).bind('click', 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 = $("div.warning_notices");
  setupBorders(nl);
  if ( ! nl) return;
  if (nl) nl.reverse(); // makes the notices overlap in the right order
  nl.each(function(i,n) {
    n.parentNode.style.zIndex = WarningNoticesZIndex++;
    var onFieldFocus = function(e) {
      var that = this;
      that.parentNode.style.zIndex = WarningNoticesZIndex++;;
      // get to the notice field (it's a div preceding the input
      // and label):
      $(that).parent().find('div.error_notices').hide();
      $(that).parent().find('div.warning_notices').css({
    	  left: ($(that).width() + that.offsetLeft + 7) + 'px',
    	  visibility: 'visible'
      });
    };
    var onFieldBlur = function(e) {
      var that = this;
      $(that).parent().find('div.warning_notices').css({visibility: 'hidden'});
    };
    
    
    var iterator = function(field) {
      $(field).bind("focus", onFieldFocus);
      $(field).bind("blur", onFieldBlur);
    }
    var inputs = $(n.parentNode.getElementsByTagName("input"));
    inputs.each(function(){iterator(this)});
    var selects = $(n.parentNode.getElementsByTagName("select"));
    selects.each(function(){iterator(this)});
    var textareas = $(n.parentNode.getElementsByTagName("textarea"));
    textareas.each(function(){iterator(this)});
    $(n).bind('click', 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();
    });
  });
}

/*
Login confirm
Displays an extra AHDialogbox in case a shoppinglist or a unsaved cookbook is about to be overwritten.
*/
function setupLoginConfirm() {
  var loginForms = $("form#loginForm");
  loginForms.each(function() {
	  var loginForm = this;
    $(loginForm).bind('submit', function(event) {
      checkUserStatus(this);
      return false;
    });
  });
}

// Checking the user's gathered items and whether (s)he has a status C/D or not
function checkUserStatus(submittedForm) {
  $.ajax({
	url: "/rev05/requests/cookbook_check.jsp",
    type: "GET",
    complete: function(transport) {
      var responseXML = null;
      if (window.ActiveXObject){
        responseXML = new ActiveXObject("Microsoft.XMLDOM");
        responseXML.async = "false";
        responseXML.loadXML(transport.responseText);
      } else {
        var parser = new DOMParser();
        responseXML = parser.parseFromString(
            transport.responseText, "text/xml");
      }

      var status = responseXML.getElementsByTagName("status")[0];
      if (typeof responseXML.getElementsByTagName("status")[0] == "undefined"){
        // Something went wrong, don't show cookbook-alert, just login
        submittedForm.submit();
      }
      else if ($(status).find(':first').text() !== "empty") {
        // There is something added to the shoplist or to the cookbook, show
        // cookbook-alert
        if (!$("#user").size() || ($("#user").size()
            && !$("#user").hasClass("registered"))) {
          var loginDialog = new AHDialog();
          loginDialog.addText("Hiermee gaan de zojuist ingevoerde gegevens in de Boodschappenlijst en Mijn Bewaarde recepten verloren. Wanneer u eerder ingelogd bent geweest en een Boodschappenlijst aangemaakt hebt, zal deze automatisch getoond worden. Wilt u doorgaan?");
          loginDialog.addTitle("Inloggen");
          loginDialog.addAction("Ja",function(){
            submittedForm.submit();
            loginDialog.destroy();
          });
          loginDialog.addDestroyer("Nee");
          loginDialog.build();
        }
        else {
          submittedForm.submit();
        }
      }
      else {
        // Nothing added to the shoplist or to the cookbook, show cookbook-alert
        submittedForm.submit();
      }
    }
  });
}

// ###################################
// ############ COOKBOOK #############
// ###################################

/*
Setup Cookbook (Mijn bewaarde recepten) drag & drop
The form has to be added to the DOM in order to make it work in all browsers
*/
function setupCookbook() {
  // Setup the Cookbook dropzone
  $("#cookbook_sidebar, #temp_recipe_holder").css({position: 'relative'});

  // Setup cookbookrecipes mouseoverstyles for ie6
  $("div#hide_my_cb_info ul li").hover(function(){$(this).addClass('hover')},function(){$(this).removeClass('hover')});

  var saveToCookBookAnchors = $("ul.options li.cookbook a.add_to_cookbook_link");
  saveToCookBookAnchors.each(function(i) {
	  $(saveToCookBookAnchors[i]).bind('click', function(event) {
		var saveToCookBookHref = saveToCookBookAnchors[i];
		if ((getCookie("ah_collected_recipe") != 1) &&
			 (!$("#user").size() || ($("#user").size() && !$("#user").hasClass("registered")))) {
		  setupSaveToCookbookDialog(saveToCookBookHref);
		  return false;
		} else {
		  return true;
		}
	  });
	  
  });
}

function cookbookDrop() {

	var saveToCookBookAnchors = $("ul.options li.cookbook a.add_to_cookbook_link");
    saveToCookBookAnchors.each(function(i) {
        // IE drag misbehaviour fix to make ondrop actions work.
		var saveToCookBookHref = $(saveToCookBookAnchors[i]).attr("href");
		if ((getCookie("ah_collected_recipe") != 1) &&
			 (!$("#user").size() || ($("#user").size() && !$("#user").hasClass("registered")))) {
			setupSaveToCookbookDialog(saveToCookBookHref);
			return false;
		} else {
			return true;
		}
      });
}

function setupSaveToCookbookDialog(continueSaveHref) {
  var saveToCookbookDialog = new AHDialog();
  saveToCookbookDialog.addText("Klik op OK om het recept aan de Bewaarde Recepten toe te voegen. "
		  + "Als u een Kookschrift heeft, log dan eerst in. "
		  + "Na het inloggen kunt u vervolgens het recept aan uw Kookschrift toevoegen.");
  saveToCookbookDialog.addTitle("Recept opslaan");
  saveToCookbookDialog.addAction("Ok",function(){},continueSaveHref);
  saveToCookbookDialog.addDestroyer("Annuleren");
  saveToCookbookDialog.build();
  setCookie("ah_collected_recipe", 1, 7);
}

// ###################################
// ######### MORE INIT ???? ##########
// ###################################

/* Convert anchors to popup buttons: */
loader.schedule("multiple non-related setup topics", function() {
  // logoff
  var l = $("#to_user_logout");
  if (l) {
    l.addClass("deselected");
    l.bind('click', function(evt) {
       l.removeClass("deselected");
       var logoutDialog = new AHDialog();
      logoutDialog.addText("U logt nu uit. Alle privacy gevoelige onderdelen zijn hierdoor afgeschermd. Na het uitloggen kunt u nog steeds gebruik maken van uw Boodschappenlijst.");
      logoutDialog.addTitle("Uitloggen");
      // only use this function if you want to create a unique dialog (default
      // dialog is called ah_dialog)
      logoutDialog.addAction("Uitloggen",function(){
        removeCookie("ah_collected_recipe");
        document.location.href = l.attr('href');
      });
      logoutDialog.addDestroyer("Annuleren");
      logoutDialog.build();
      return false;
    });
  }

  

  // mail-a-friend links (may appear more than once on a page):
  var mailers = $("a.mail-a-friend");
  mailers.each(function () {
	  var mailer = this;
    $(mailer).bind('click', function(event) {
      window.open($(mailer).attr("href"),
        "_blank", "width=420,height=660,top=0,left=0,scrollbars=yes,location=no,modal");
      return false;
    });
  });

  // Generic popup
  var popups = $("a.popup");
  popups.each(function () {
	  var popup = this;
    $(popup).bind('click', function(event) {
      window.open($(popup).attr("href"), "_blank", "width=480,height=575,scrollbars=yes");
      return false;
    });
  });

});


/**
 * Setup stickers
 */
function setupStickers() {
  var i = 0;
  var stickerContainers = $('.sticker');
  stickerContainers.each(function() {
	  var stickerContainer = this;
	  // [KN] still working?
    if (deconcept.SWFObjectUtil.getPlayerVersion().major >= 8
        && (stickerContainer.tagName == 'DIV' || stickerContainer.tagName == 'LI') ) {
      var stickertypes = new Array();
      stickertypes['stickertype1'] = new Array();
      stickertypes['stickertype2'] = new Array();
      stickertypes['stickertype3'] = new Array();
      stickertypes['stickertype4'] = new Array();
      stickertypes['stickertype1']['alt'] = '/_ui/jokers/jokersticker.png';
      stickertypes['stickertype1']['animation'] = '/_swf/jokers/jokersplakken_m.swf';
      stickertypes['stickertype1']['width'] = '120';
      stickertypes['stickertype1']['height'] = '113';

      stickertypes['stickertype2']['alt'] = '/_ui/jokers/jokersticker.png';
      stickertypes['stickertype2']['animation'] = '/_swf/jokers/jokersplakken_l.swf';
      stickertypes['stickertype2']['width'] = '172';
      stickertypes['stickertype2']['height'] = '160';

      stickertypes['stickertype3']['alt'] = '/_ui/jokers/jokerstickerslimmekeus.png';
      stickertypes['stickertype3']['animation'] = '/_swf/jokers/jokersslimmekeuze_m.swf';
      stickertypes['stickertype3']['width'] = '120';
      stickertypes['stickertype3']['height'] = '113';

      stickertypes['stickertype4']['alt'] = '/_ui/jokers/jokersticker.png';
      stickertypes['stickertype4']['animation'] = '/_swf/jokers/jokersslimmekeuze_l.swf';
      stickertypes['stickertype4']['width'] = '172';
      stickertypes['stickertype4']['height'] = '160';

      var stickertype = stickertypes['stickertype1'];
      var elClassNames = stickerContainer.className.split(' ');
      for(var i = 0; i < elClassNames.length; i++) {
        if(typeof stickertypes[elClassNames[i]] !== 'undefined')
          stickertype = stickertypes[elClassNames[i]];
      }

      var sticker = document.createElement('div');
      var stickerId = 'sticker_' + i;
      sticker.setAttribute('id', stickerId);
      sticker.className = 'theme_sticker';
      var stickerSrc = stickertype['animation'];
      var stickerWidth = stickertype['width'];
      var stickerHeight = stickertype['height'];

      var stickerAlt = document.createElement('img');
      stickerAlt.src = stickertype['alt'];
      if(ua.ie6) {
        stickerAlt.style.visibility = 'hidden';
      }
      sticker.appendChild(stickerAlt);
      stickerContainer.appendChild(sticker);

      var fo = new SWFObject(stickerSrc, "sticker" + i, stickerWidth, stickerHeight, "8", "#FFFFFF");
      fo.addParam("quality", "high");
      fo.addParam("menu", "false");
      fo.addParam("flashvars", "");
      fo.addParam("wmode", "transparent");
      fo.addParam("allowScriptAccess", "always");
      writeSWFObject(fo, stickerId);
      i++;
    }
  });
}




/* Banners animator ************/
var bannerReels = new Object();
var bannerFadeDuration = 2000;
var bannerFadeInterval = 6000;

function spinSingleBanner(bannerId) {
  var bannerReel = bannerReels[bannerId];

  if (bannerReel.timer) clearTimeout(bannerReel.timer);

  if (((bannerReel.currentBanner+1) >= bannerReel.banners.length)
        || (typeof bannerReel.currentBanner == "undefined")) {
    if (typeof bannerReel.banners[bannerReel.currentBanner] !== "undefined")
      $(bannerReel.banners[bannerReel.currentBanner]).fadeOut(bannerFadeDuration);
    bannerReel.currentBanner = 0;
    if (typeof bannerReel.banners[bannerReel.currentBanner] !== "undefined")
      $(bannerReel.banners[bannerReel.currentBanner]).fadeIn(bannerFadeDuration);
  }
  else {
    if (typeof bannerReel.banners[bannerReel.currentBanner] !== "undefined")
      $(bannerReel.banners[bannerReel.currentBanner]).fadeOut(bannerFadeDuration);
    bannerReel.currentBanner++;
    if (typeof bannerReel.banners[bannerReel.currentBanner] !== "undefined")
      $(bannerReel.banners[bannerReel.currentBanner]).fadeIn(bannerFadeDuration);
  }

  // Recursively call this function for the current banner.
  var timedCall = "spinSingleBanner('" + bannerId + "')";
  bannerReel.timer = setTimeout(timedCall, bannerFadeInterval);

  // Clean up!
  timedCall = bannerReel = null;
}

function setupBannerStrips() {
  // Fetch all bannerstrips.
  bannerReels = $(".bannerstrip .banner_reel");

  var bannerFadeOffset = 2000;
  var bannerId = -1;
  bannerReels.each(function() {
	  var bannerReel = this;
	 bannerId++;
    var winBannerReel = bannerReels[bannerId];

    winBannerReel.banners = bannerReel.getElementsByTagName("a");

    if (winBannerReel.banners.length > 1) {
      // Turn off all banners except the first within this reel.
      for(var j = 1; j < winBannerReel.banners.length ; j++) {
        winBannerReel.banners[j].style.display = "none";
      }
      // Set starting point for the animation.
      winBannerReel.currentBanner = 0;

      // Build timer function call.
      var timedCall = "spinSingleBanner('" + bannerId + "')";
      winBannerReel.timer = setTimeout(timedCall, bannerFadeOffset);
      if(bannerFadeOffset < 5000) {
        bannerFadeOffset = (bannerFadeOffset + 2000);
      }
    }
  });
}
/* Banners animator - End ************/

// ###################################
// ###########  FOLDOUT  #############
// ###################################

// Stepping stone for real foldout loader, to start foldout setup
// before shoplist.
function setupFoldFromDefaultJS() {
  if (typeof setupFold == 'function') {
    setupFold();
    
  }
}


// ##########################################################
// ######## CHECK IF SECONDARY IS BIGGER THAN PRIMARY #######
// ##########################################################

function checkSecondaryHeight() {
	if (!$('#secondary')) return;
	var secondaryHeight = $('#secondary').height();
	var primaryPlusFooterHeight = $('#primary').height() + 100;
	if (secondaryHeight > primaryPlusFooterHeight) {
		var bodyIncrease = secondaryHeight - primaryPlusFooterHeight;
		var newBodyHeight = $('body').height() + bodyIncrease;
		document.body.style.height = newBodyHeight + 'px';
	}
}

// ###################################
// ######## DROPPABLE TERTIARY #######
// ###################################
//
// Make tertiary column droppable for recipes and products.
function droppableTertiary() {
  // Only build droppable tertiary if primary and shoplist exist.
  if (!$('#primary').size() || !$('#shoplist').size()) return;

  // For now, disable on household pages to prevent large whitespace
  // after folding of tips.
  if ($('body')[0].className.indexOf('household') > -1) return;

  var primaryHeight = $('#primary').height();
  var shoplistHeight = ($('#shoplist').size()) ? $('#shoplist').height() : 0;
  var lekkerHeight = ($('#lekkers').size()) ? $('#lekkers').height() : 0;
  var cookbookHeight = ($('#cookbook_sidebar_container').size()) ? $('#cookbook_sidebar_container').height() : 0;

  if ((primaryHeight > $('#tertiary').height()) && $('#shoplist').size()) {
	$('#tertiary').append("<div id=\"tertiary_droppable_outer\"><div id=\"tertiary_droppable_inner\">&nbsp;</div></div>");
    var dropAreaHeight = (primaryHeight - shoplistHeight - lekkerHeight - cookbookHeight - 50) + "px";
    $('#tertiary_droppable_inner').css({'height': dropAreaHeight, 'margin-top': "10px"});
  }
}


// ########################################
// # Recipe results enhanced view IE6 fix #
// ########################################

/*
(IE 6 Bugfix, absolute positioned images on hover)
*/
function disabledImgIE6() {
  if(!ua.ie6)
    return;
  var sli = $("ul.enhanced li");
  sli.each(function() {
	  var li = this;
    $(li).bind('mouseover', function(e) {
      if (!$(li)[0].nextSibling) {
        return false;
      }

      var nextElem = $(li)[0].nextSibling;
      while(typeof nextElem != "object")
        nextElem = nextElem.nextSibling;
      nextElem.getElementsByTagName("img")[0].style.visibility = "hidden";
    });

    $(li).bind('mouseout', function(e) {
      if (!$(li)[0].nextSibling) {
        return false;
      }
      var nextElem = $(li)[0].nextSibling;
      while(typeof nextElem != "object") nextElem = nextElem.nextSibling;
        nextElem.getElementsByTagName("img")[0].style.visibility = "visible";
    });
  });
}

try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(e) {}

/* function used to detect flash and hide container if not available */
function flashContentNoAlternative(id, flashVersion) {
	if ((typeof deconcept!="undefined") && deconcept.SWFObjectUtil.getPlayerVersion().major < flashVersion) {
		if (document.getElementById(id)) document.getElementById(id).style.display = 'none';
	}
}

// ###################################
// ######## process news block #######
// ###################################
//
// process news blocks in supertheme.

function NewsBlocks(n) {

	// get date
	var newsdate = $(n).find('p.datum')[0];
	if (!newsdate) return;

	var newstitle = $(n).find('h2')[0];
	if (!newstitle) return;
	$(newstitle).remove();


	n.id = 'news_' + newsdate.innerHTML;

	n.innerHTML = '<h2>'+newstitle.innerHTML+'</h2><div class="newsBody" id="body_'+n.id+'">'+n.innerHTML+'</div>';

	if (getCookie(n.id)=='hidden') {
		$(n).addClass('hidden');
		$('#body_'+n.id).hide();
	}

	// add controller
	var closeButton = document.createElement('a');
	closeButton.className = 'close';
	closeButton.innerHTML = 'sluiten';
	n.appendChild(closeButton);

	$('#'+n.id+' a, #'+n.id+' h2').each(function(){
		var a = this;
		$(a).bind('click', function() {
			if (!$(n).hasClass('hidden')) {
				$(n).addClass('hidden');
				$('#body_'+n.id).slideUp(400);
				// set in cookie
				setCookie(n.id,'hidden',365);
			}
			else {
				$(n).removeClass('hidden');
				$('#body_'+n.id).slideDown(400);
			}

  		});
	});

}
NewsBlocks.setup = function(nl) {
  if (!nl.length) return;
  nl.each(function() {
	  var n = this;
    if (n) new NewsBlocks(n);
  });
};

loader.schedule("newsblokken verrijking", function(){
  NewsBlocks.setup($('.themapagina .section.news'));
});

AHEnlargeImages = new Object();

AHEnlargeImages.processImageBlocks = function() {
	$('#primary p.vergroter').each(function(imageBlock){
		var imageBlock = this
		var img1 = $(imageBlock).find('img')[0];
		var img2 = $(imageBlock).find('img')[1];

		if (!img1 || !img2) return;
		img1.enlarged = img2.attr('src');
		img1.enlargedWidth = img2.attr('width');
		img1.enlargedHeight = img2.attr('height');

		var enlargeButton = document.createElement('a');
		enlargeButton.className = 'enlarge';
		enlargeButton.innerHTML = 'Vergroten';
		imageBlock.appendChild(enlargeButton);

		$(img2).remove();

		$(imageBlock).bind('click', function(e) {

			var img = $(this).find('img')[0];


			if ($('#imageEnlarger')) {
				$('#imageEnlarger').remove();
				$(AHEnlargeImages.openImage).removeClass('imageEnlarged');
				if (AHEnlargeImages.openImage==this) {
					AHEnlargeImages.openImage = null;
					return;
				}

			}
			AHEnlargeImages.openImage = this;
			$(AHEnlargeImages.openImage).addClass('imageEnlarged');
			var div = document.createElement('div');
			div.className = 'imageEnlarger';
			div.id = 'imageEnlarger';
			if (img.alt) div.innerHTML = '<h4>'+img.alt+'</h4>';
			div.innerHTML += '<a class="close">sluiten</a>';
			div.innerHTML += '<img src="' + img.enlarged + '" width="'+img.enlargedWidth+'"  height="'+img.enlargedHeight+'"/>';

			// [KN] find viewport alternative
			var offsets = document.viewport.getScrollOffsets();

    		var top = (document.viewport.getHeight() - img.enlargedHeight)/2 + offsets.top;
    		var left = (document.viewport.getWidth() - img.enlargedWidth)/2 + offsets.left;

    		if (top < (offsets.top+50)) top = (offsets.top+50);
    		if (left < (offsets.eft+20)) left = (offsets.left+20);

    		div.style.left = left + 'px';
    		div.style.top = top + 'px';


			$(div).bind('click', function(e) {
				$(this).remove();
				$(AHEnlargeImages.openImage).removeClass('imageEnlarged');
				AHEnlargeImages.openImage = null;
			});
			document.body.appendChild(div);
  		});

  		$(imageBlock).addClass('enlargeProcessed');

	});
}

if (loader) {
	loader.schedule("plaatjes vergroter", AHEnlargeImages.processImageBlocks);
}

AHAnimation = new Object();

AHAnimation.Animation = function(elementId, startPoint, flightPlans) {
	
	this.elementId = elementId;
	this.startPoint = startPoint;
	this.flightPlans = flightPlans;

	var executeFlightPlans = function(from, index) {
		if (index >= flightPlans.length || (flightPlans[index] == null)) {
			$('body').removeClass('dragging');
			return;
		}

		
		
	
		setTimeout(function() {
			$('#'+elementId).animate({
					curve: new BezierCurve(
						from.x, from.y,
						flightPlans[index].fromDir.x, flightPlans[index].fromDir.y,
						flightPlans[index].toDir.x, flightPlans[index].toDir.y,
						flightPlans[index].to.x, flightPlans[index].to.y
					)
			},flightPlans[index].duration*1000,'',function(){
				executeFlightPlans(flightPlans[index].to, index + 1);
			});
		}, flightPlans[index].timeBefore);
		
	}

	this.start = function() {
		$('body').addClass('dragging');
		$('#'+elementId).css({
			display:	'block',
			position:	'absolute',
			left:		startPoint.x + 'px',
			top:		startPoint.y + 'px',
			zIndex:	10000
		});
		executeFlightPlans(startPoint, 0);
	}

}

AHAnimation.Coordinates = function(x, y) {
	this.x = x;
	this.y = y;
}

AHAnimation.FlightPlan = function(fromDir, toDir, to, duration, timeBefore) {
	this.fromDir = fromDir;
	this.toDir = toDir;
	this.to = to;
	this.duration = duration;
	this.timeBefore = timeBefore;
}

AHAnimation.coordinatesForElement = function(element, offsetX, offsetY) {

	var x;
	var y;
	if (typeof element == 'undefined') {
		x = 0;
		y = 0;
	} else {
		
		x = $(element).offset().left;
		y = $(element).offset().top;
	}
	if (offsetX != null) {
		x += offsetX;
	}
	if (offsetY != null) {
		y += offsetY;
	}

	return new AHAnimation.Coordinates(x, y);
}

/**
 * Clear the value of an input element and then remove its onclick.
 */
function clearInput(inputElement) {
	inputElement.value = "";
	inputElement.onclick = null;
}

function videoMailAFriendLightbox(groupId, videoId) {
	AHLightBox.createLighboxContent('video_mail_a_friend',
			'/video/verstuur?videoId=' + videoId + '&groupId=' + groupId,
			{width:420,voffset:25,close:true});
}



$(document).ready(function(){
	// Handle Ajax Submit for news banner module
	$('#newsletter-module-form').live('submit',function() {
		var form = $(this);
		var params = form.serialize();
		$.ajax({type: 'post', url: form.attr('action'), dataType:"html", data: params, success: function(data) {
			var module = $('<div>' + data + '</div>');
			module = module.find('#newsletter-module-container').html();
			if (module != null) {
				$('#newsletter-module-container').html(module);
				placeholderAlternative();
			} else {
				form.html('<span class="error">Technische fout!</span>'); 
				//$('body').html($(data).find('body'));
			}
		}, error: function(xhr, ajaxOptions, thrownError) {
			form.html('<span class="error">Technische fout!</span>');
			//$('body').html($(xhr.responseText).find('body'));
		}});
		return false;
	});
	
	function placeholderAlternative() {
		// Add support for input placehoder in older browsers
		if (!('placeholder' in document.createElement('input'))) {
			$('input[placeholder]:not(.processed)').each(function() {
				$(this).addClass('processed');
				var pl = $(this).attr('placeholder');
				if ($(this).val() == '') {
					$(this).val(pl).addClass('placeholded');
				}
				$(this).focus(function() {
					if ($(this).val() == pl) {
						$(this).val('').removeClass('placeholded');
					}
				}).blur(function() {
					if ($(this).val() == '') {
						$(this).val(pl).addClass('placeholded');
					}
				}).closest('form').live('submit',function(){
					if ($(this).val() == pl) $(this).val('');
				});
			});
		}
	}
	placeholderAlternative();
});

function calcPwdStrength(fieldName){
	var fieldId = '#' + fieldName;
	$(fieldId).keyup(function(){
		  var thePassword = document.getElementById(fieldName).value
			  $.ajax({
			    url: '/data/json/member/passwordStrength',
			    type: 'post',
			    data: {password: thePassword},
			    dataType: 'json',
			    context: document.body,
			    success: function(data, textStatus, xhr) {
			        var jsonStr = data.jsonObject
			        var jsonObj = JSON.parse(jsonStr)
			    	
//			    	pwdStr = '<fmt:message key="passwordmeter.message.' + jsonObj.passwordStrength + '" />'
			        
			        var pwdStr = '';
			    	if (jsonObj.passwordStrength=='INVALID') {
			    		pwdStr = 'Ongeldig';
			    	}
			    	if (jsonObj.passwordStrength=='EMPTY') {
			    		pwdStr = 'Leeg';
			    	}
			    	if (jsonObj.passwordStrength=='SHORT') {
			    		pwdStr = 'Kort';
			    	}
			    	if (jsonObj.passwordStrength=='VERY_WEAK') {
			    		pwdStr = 'Zwak';
			    	}
			    	if (jsonObj.passwordStrength=='WEAK') {
			    		pwdStr = 'Matig';
			    	}
			    	if (jsonObj.passwordStrength=='GOOD') {
			    		pwdStr = 'Goed';
			    	}
			    	if (jsonObj.passwordStrength=='STRONG') {
			    		pwdStr = 'Sterk';
			    	}
			    	if (jsonObj.passwordStrength=='VERY_STRONG') {
			    		pwdStr = 'Uitstekend';
			    	}
					var score = jsonObj.score

//					document.getElementById("strength").innerHTML = pwdStr;
										
					document.getElementById('scorebar').style.backgroundPosition = '-' + parseInt(score * 4) + 'px';
			    	$('#strength').text(pwdStr);
			    	$('#score').text(score + '%');
			    	
			    	if (document.getElementById('passwordmeter_change')){
						document.getElementById('passwordmeter_change').style.visibility = 'visible';
			    	}
					
			    }
		   });
	});
}

$(document).ready(function(){
	if (document.getElementById('passwordmeter_new')){
		calcPwdStrength('password');
	}
});

$(document).ready(function(){
	if (document.getElementById('passwordmeter_change')){
		calcPwdStrength('newPassword');
	}
});

