/**
* (c) InfoProjects bv. - www.infoprojects.nl
*
* $Revision: 1.54 $
* $Date: 2012/01/19 08:32:45 $
* $Author: Ad $
*/

var menuTimer;
var navTimer;
var navOpen;
var initialNavOpen;

var movers = new Array();
var eltsMoving = false;

var headerHeight;
var tabbarHeight;
var navHeight;
var sitepadHeight;
var visibleNavHeight;
var iconbarHeight;

var pageReloadWhenLoggedIn = false;
var pageRefresh = true;
var pageBuilt = true;
var personalizable = false;

var orgColors = new Object();

var mediaType = "all";
var configSectionOpen = false;

var querystring = location.search.replace('?', '').split('&');
var queryObj = {};

function GetQueryString() {
  for (var i = 0; i < querystring.length; i++) {
    // get name and value
    var name = querystring[i].split('=')[0];
    var value = querystring[i].split('=')[1];
    // populate object
    queryObj[name] = value;
  }
}

function setTwitLink(title, longUrl, orgUrl, summ) {
  var shortUrl;
  var lv_tweet = title + ' - ' + summ;
  var tweet = lv_tweet.replace("%2c", ",");
  // uitgeklede functionaliteit voor IE6
  if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
    var tw_link = 'http:/' + '/twitter.com/home?status=' + encodeURIComponent(tweet + ' ' + orgUrl);
    window.open(tw_link);
  }
  // volledige functionaliteit voor 'echte' browsers. Let op: klant moet account hebben bij bit.ly!
  else {
    $.getJSON("http://api.bit.ly/v3/shorten?login=infoprojects&apiKey=R_717e2333b4c8b3c5ce9e324011d3ff3a&longUrl=" + longUrl + "&format=json&callback=?",
    function(data) {
      shortUrl = data.data.url;
      var limit = 140 - (shortUrl.length + 1);
      if (tweet.length > limit) {
        tweet = tweet.substr(0, (limit - 3)) + '...';
      }
      var tw_link = 'http:/' + '/twitter.com/home?status=' + encodeURIComponent(tweet + ' ' + shortUrl);
      // window.open(tw_link);
      window.location = tw_link;
      return false;
    });
  }
}

function initPage(focusIt) {
  if (mediaType != "handheld" && mediaType != "minimal") {
    if (focusIt || (window.opener && window.opener != self)) {
      window.focus();
    }

    checkStylesheets();

    headerHeight = $("#Header").height() > 0 ? $("#Header").height() : $(".header_normal").height();
    navHeight = $(".mainmenu").height();
    sitepadHeight = $("#Sitepad").height();
    tabbarHeight = $("#Tabs").height();
    iconbarHeight = $("#Icons").height();

    visibleNavHeight = navOpen ? navHeight : sitepadHeight;

    if (fontSizeCookie && getCookie('fontSize')) {
      changeFontsize(getCookie('fontSize'), "");
    }

    initPageLayout();
    initInterfaceElts();
    initPageBehaviour();
    initPageFunctions();
    initMenu($('#Mainmenu'));
    initIndexFeatures();
  }
}

function initPageLayout() {
  // header_popup vullen (popup)
  $(".header_popup[id=Header]").each(function() {
    if (!$(this).hasClass('headerhasbackground')) {
      var titleText = $(this).attr("title");
      var titleHtml = '<div class="header_popup_title">' + titleText + '</div>';
      $(this).append(titleHtml);
    }
  });

  $(".zipalf").blur(function() {
    $(this).val($(this).val().toUpperCase());
  });

  $(".zipprt").blur(function() {
    $(this).val($(this).val().toUpperCase().replace(' ', ''));
  });

  $(".scorebar").each(function() {
    var curClass = $(this).attr("class");
    var curScore = curClass.substring(curClass.indexOf("score_") + 6, curClass.length);
    var barHtml = '<div class="scorebar_result" style="width:' + curScore + 'px"></div>';
    $(this).append(barHtml);
  });

  $("select.dd, select.mm, select.jjjj").change(function() {
    var eltName = $(this).attr("name");
    if (eltName.indexOf('Dummy') == -1) {
      var eltId = $(this).attr("id");
      if (eltId.indexOf("_d") > -1) {
        eltId = eltId.substring(0, eltId.indexOf("_d"));
      } else if (eltId.indexOf("_m") > -1) {
        eltId = eltId.substring(0, eltId.indexOf("_m"));
      } else if (eltId.indexOf("_y") > -1) {
        eltId = eltId.substring(0, eltId.indexOf("_y"));
      }
      fixDate($(this).get(0).form.id, eltId);
    }
  });


  $(".daterange input.dd, .daterange input.mm, .daterange input.jjjj").blur(function() {
    var eltName = $(this).attr("name");
    if (eltName.indexOf('Dummy') == -1) {
      var eltId = $(this).attr("id");
      if (eltId.indexOf("_d") > -1) {
        eltId = eltId.substring(0, eltId.indexOf("_d"));
      } else if (eltId.indexOf("_m") > -1) {
        eltId = eltId.substring(0, eltId.indexOf("_m"));
      } else if (eltId.indexOf("_y") > -1) {
        eltId = eltId.substring(0, eltId.indexOf("_y"));
      }
      fixDate($(this).get(0).form.id, eltId);
    }
  });

  $("select.hours, select.minutes").change(function() {
    var eltId = $(this).attr("id");
    if (eltId.indexOf("_h") > -1) {
      eltId = eltId.substring(0, eltId.indexOf("_h"));
    } else if (eltId.indexOf("_m") > -1) {
      eltId = eltId.substring(0, eltId.indexOf("_m"));
    }
    fixTime($(this).get(0).form.id, eltId);
  });

  $(".rowhasimage").each(function() {
    var maxModuleHeight = 0;
    var moduleCount = 0;
    $(this).find(".module").each(function() {
      maxModuleHeight = $(this).height() > maxModuleHeight ? $(this).height() : maxModuleHeight;
      moduleCount++;
    });

    if (moduleCount > 0 && maxModuleHeight > 0) {
      $(this).find(".module").each(function() {
        $(this).css({ position: 'relative', height: maxModuleHeight + (document.all ? 15 : 0) + 'px' });
        $(this).find(".rowimg, .rowimg_breed2, .rowimg_breed3, .rowimg_breed4").css({ position: 'absolute', bottom: '0px' });
      });
    }
  });

  $(".footer_popup .button_close").each(function() {
    if (window.opener) {
      $(this).click(function() { window.close(); });
    }
    else {
      $(this).remove();
    }
  });

  $(".koppeling.superlink:not(:has(.contentblok))").each(function() {
    $(this).remove();
  });

  var into_frame_active = false;
  $("a.into_frame").click(function() {
    if (!into_frame_active) {
      var href = $(this).attr('href');
      var iFrameHtml = '<iframe allowtransparency="true" frameborder="0" width="' + $('#Contents').width() + '" height="100" src="' + href + '"></iframe>';
      $('#Contents').before('<div class="frame_above_content"></div>');
      $(".frame_above_content").animate({ height: '100px' }, 500).html(iFrameHtml);
    }
    else $(".frame_above_content").remove();
    into_frame_active = !into_frame_active;
    return false;
  });

  $("a.iproxLink")
    .mouseover(function() {
      $(this).find(".iproxLinkLabel").show();
    }).mouseout(function() {
      $(this).find(".iproxLinkLabel").hide();
    });

  $("a.iproxLink.add_pagina").click(function() {
    var curPagFun = $(this);
    $.dimScreen(256, 0.5, function() {
      openBox(curPagFun);
    });
    return false;
  });

  $("a.iproxLink:not(.into_frame):not(.add_pagina)").attr("target", "mainWindow").click(function() {
    var href = $(this).attr('href');
    if (window.opener) {
      try {
        window.opener.document.location = href;
        window.close();
      }
      catch (e) {
        document.location = href;
      }
      return false;
    }
    else if (window.referer) {
      try {
        window.referer.document.location = href;
        window.close();
      }
      catch (e) {
        document.location = href;
      }
      return false;
    }
    else {
      window.close();
    }

    if ($("#" + $("#goto_bookmark").attr("name")).length) {
      $("#" + $("#goto_bookmark").attr("name")).get(0).scrollIntoView(true);

      var content_class = $(".contents").attr("class");
      var content_html = $(".contents").html();

      var content_div = "<div class='" + content_class + "'>" + content_html + "</div>";
      $(".contents").remove();
      $(".page_contents").prepend(content_div);
    }
  });

  $("area.open_in_iframe").click(function() {
    var href = $(this).attr('href');
    var iFrameHtml = '<iframe allowtransparency="true" frameborder="0" width="' + $('#Contents').width() + '" height="750" src="' + href + '"></iframe>';
    $('#Contents').html(iFrameHtml);
    return false;
  });

  //als een contentblok leeg is hide hem dan. Anders neemt hij in IE7 ruimte in.
  $('.subhome .contentrow .inside .contentblok, .subhome .contentrow .inside .contentblok .index_item .reactieLink').each(function() {
    if ($(this).children().length == 0) {
      $(this).hide();
    }
  });

  $('.nieuwsbrief .linkpointer').each(function() {
    $(this).parent().find("br").remove();
  });

  $('.contentrow').each(function() {
    if ($(this).find("embed").html() != null) {
      $('.subhome .contentrow .afbeelding .inside').each(function() {
        $(this).parent().css("line-height", "100%");
        $(this).find("embed").css("margin-top", "0px");
        $(this).find("embed").parent().css("margin-bottom", "-1px");
      });
    }
  });

  $('.page_blocks').each(function() {
    if ($(this).find(".smoelenwand") == null) {
      $(this).css("padding-top", "1px");
    }
  });
}

function initInterfaceElts(eltId, obj) {
  // eltId kan vanuit een ajax partial call komen (bv. subhome.js)
  if (!obj && eltId) {
    obj = $(eltId);
  }
  else if (!obj) {
    obj = $(document);
  }

  // linkpointers
  obj.find(".symbol_plus").text("[+]");
  obj.find(".symbol_minus").text("[-]");
  obj.find(".symbol_download").text("[~]");
  obj.find(".symbol_extern").text("[>]");
  obj.find(".symbol_pagina").text("[<]");
  obj.find(".symbol_change").text("[^]");
  obj.find(".symbol_folder").text("[/]");

  obj.find(".activate_handheld").animate({ opacity: 0 }, 10000, null, function() { $(this).hide(); });

  obj.find(".formulier .rij .ongeldig").each(function() {
    $(this).closest(".label").addClass("invalid");
    $(this).removeClass("ongeldig");
  });

  obj.find(".formulier .rij .verplicht").each(function() {
    $(this).closest(".label").addClass("required");
    $(this).remove();
  });

  obj.find(".formulier .rij.captcha .label label").each(function() {
    $(this).text('captcha');
  });


  // printversie voorbereiding ('Beeldmerk print')
  obj.find(".header_normal").each(function() {
    var bgImg = $(this).css('backgroundImage');
    if (bgImg && bgImg != "none") {// && $("h1").is(":visible")
      $(this).prepend('<img class="header_normal_image" src="' + backgroundToSrc(bgImg) + '"/>');
      $(this).css({ 'background-image': 'none' });
    }
  });

  // printversie voorbereiding ('Titel print')
  obj.find(".header_normal .textlogo").each(function() {
    var bgImg = $(this).css('backgroundImage');
    if (bgImg && bgImg != "none") {// && $("h1").is(":visible")
      $(this).prepend('<img class="textlogo_image" src="' + backgroundToSrc(bgImg) + '"/>');
      $(this).css({ 'background-image': 'none' });
    }
  });

  // printversie voorbereiding: links uitschrijven
  obj.find(".contents a[href^=http]:not(:has(img)), .contents a[href^=/publish]:not(:has(img)), .contents a[href^=/contents]:not(:has(img))").each(function() {
    var href = $(this).attr('href');
    if (href && href.indexOf("http") == 0 && href.length > 64) {
      href = href.substring(href.indexOf('://') + 3).split('/').join('/&#173;');
    }
    $(this).append('<span class="linkDesc">(' + href + ')</span>');
  });

  // printversie voorbereiding: email adressen uitschrijven
  obj.find(".contents a[href^=mailto]:not(:has(img))").each(function() {
    var address = $(this).attr('href').substring(7);
    if (address != '') {
      $(this).append('<span class="linkDesc">(' + $(this).attr('href').substring(7) + ')</span>');
    }
  });

  // printversie voorbereiding: uitgeschreven link naar nieuwe regel
  obj.find(".contents .module a .linkDesc, .contents .linkpointer a .linkDesc, .contents li a .linkDesc").prepend('<br/>');

  // superlinks sizen (subhome)
  obj.find(".superlink").each(function() {
    var curAfbWidth = $(this).find(".afbeelding img").width();
    var curAfbDivWidth = $(this).find(".afbeelding").width();
    var curCntDivWidth = $(this).find(".contentblok").width();
    if (curAfbWidth > curAfbDivWidth) {
      $(this).find(".contentblok").width(curCntDivWidth - (curAfbWidth - curAfbDivWidth));
      $(this).find(".afbeelding").width(curAfbWidth);
    }
  });

  // leads vullen (subhome)
  obj.find(".leadblock[title], .leadblock_breed[title], .leadblock_breed2[title], .leadblock_breed3[title], .leadblock_breed4[title]").each(function() {
    var leadText = $(this).attr("title");
    var leadHtml = '<div class="lead">' + leadText + '</div>';
    $(this).html(leadHtml);
  });

  // titels laten linken ("Lees meer niet linken")
  obj.find(".wachtwoord-vergeten a")
    .addClass('pointer_symbol')
    .prepend('<span class="symbol symbol_plus">[+]</span>');

  // titels laten linken ("Lees meer niet linken")
  obj.find("h3.linkpointer a").each(function() {
    $(this).prepend('<span class="symbol symbol_plus">[+]</span>');
  });

  // titels laten linken (in paginatype "index")
  obj.find(".resultaten dl dt a").each(function() {
    $(this).prepend('<span class="symbol symbol_plus">[+]</span>');
  });

  // titels laten linken (in paginatype "index")
  obj.find(".resultaten dl.download dt div.label").each(function() {
    $(this).prepend('<span class="symbol symbol_plus">[+]</span>');
  });

  // titels van modules met maar 1 link laten linken
  obj.find("h3.linking:not(.linkpointer)").each(function() {
    var titleHtml = $(this).html();
    var titleLinkHref = $(this).parents(".module:first").find("a:not([href*='PagClsRange']):not([class*='siteLink']):last").attr("href");
    var titleLinkClass = $(this).parents(".module:first").find("a:not([href*='PagClsRange']):not([class*='siteLink']):last").attr("class");
    if (titleLinkHref) {
      titleHtml = '<a href="' + titleLinkHref + '">' + titleHtml + '</a>';
      $(this).html(titleHtml);
      if (titleLinkClass.indexOf("externLink") > -1) {
        $(this).find("a").addClass("externLink");
      }
    }
  });

  // hotspot imagmeaps maken
  obj.find(".hotspot_image_container").each(function() {
    var hotspotImg = $(this).find("img");
    var hotspotPic = "url('" + hotspotImg.attr("src") + "')";
    $(this).css({ width: hotspotImg.css("width"), height: hotspotImg.css("height"), backgroundImage: hotspotPic });
    hotspotImg.attr("src", "/views/shared/images/layout/transp.gif");
  });

  // js kalenders maken
  obj.find(".small_calendar").each(function() {
    var calendarDate = $(this).attr("title").split("-");
    $(this).attr("title", "");
    buildCalendar(calendarDate[0], calendarDate[1], calendarDate[2], $(this).attr("id"));
  });

  obj.find(".toggle").click(function() {
    if ($(this).attr("class").indexOf("inactive") == -1) {
      return toggleList(this);
    }
    else return false;
  });

  var contra_black = "red";
  var contra_grey = "black";
  var contra_red = "black";
  var contra_transp = "black";

  // swapknoppen definieren
  obj.find("button img").each(function() {
    var curCol = $(this).attr("src").split("_")[1].split(".")[0];
    var conCol = eval("contra_" + curCol);
    $(this).parent("button")
    .mouseover(function() {
      $(this).addClass("highlight");
      var swapSrc = $(this).find("img").attr("src");
      $(this).find("img").attr("src", swapSrc.replace("_" + curCol, "_" + conCol));
    })
    .mouseout(function() {
      $(this).removeClass("highlight");
      var swapSrc = $(this).find("img").attr("src");
      $(this).find("img").attr("src", swapSrc.replace("_" + conCol, "_" + curCol));
    });
  });

  // swapknoppen definieren
  obj.find("input.with_image, button[class*='with_image'], a.button[class*='with_image'], .knoppen input[type='submit'], TD[class='with_image']").each(function() {
    if ($(this).css("background-image") != 'none' && !$(this).hasClass('csshover')) {
      var curCol = $(this).css("background-image").split("_")[1].split(".")[0];
      var conCol = eval("contra_" + curCol);
      $(this)
      .mouseover(function() {
        $(this).addClass("highlight");
        var swapSrc = $(this).css("background-image");
        $(this).css("background-image", swapSrc.replace("_" + curCol, "_" + conCol));
      })
      .mouseout(function() {
        $(this).removeClass("highlight");
        var swapSrc = $(this).css("background-image");
        $(this).css("background-image", swapSrc.replace("_" + conCol, "_" + curCol));
      });
    }
  });

  // fotoalbum lightbox navigatie
  obj.find(".dialog_foto img").css({ 'cursor': 'hand' }).click(function(e) {
    if (e.pageX < 250) {
      $(".dialog_foto .button_previous").click();
    }
    else {
      $(".dialog_foto .button_next").click();
    }
  });

  // fotoalbum lightbox navigatie
  obj.find(".dialog_foto .button_previous, .dialog_foto .button_next, ").click(function() {
    obj.find(".dialog_foto img").animate({ opacity: 0.1 }, 1000);
  });

  obj.find(".widget_configure a").click(function() {
    var curPagFun = $(this);
    checkProfile(curPagFun, function() {
      if (configSectionOpen) {
        openConfigSection(curPagFun);
      } else {
        $.dimScreen(256, 0.5, function() {
          openConfigSection(curPagFun);
        });
      }
    });
    return false;
  });

  obj.find(".widget_profile a").click(function() {
    var curPagFun = $(this);
    if (configSectionOpen) {
      openConfigSection(curPagFun);
    } else {
      $.dimScreen(256, 0.5, function() {
        openConfigSection(curPagFun);
      });
    }
    return false;
  });

  //links in dialoog waarvoor gespecificeerd is in de dialoog te blijven
  $(".dialog_contents .stay_in_dialog a").click(function() {
    if ($(this).attr("title") != "") {
      $(".dialog_title").text($(this).attr("title"));
    }
    fillBox($(this).attr("href"), false, null, null, true);
    return false;
  });

  //links in section waarvoor gespecificeerd is in de section te blijven
  $(".stay_in_section a").click(function() {
    openConfigSection($(this));
    return false;
  });

  //link verrijken met ajax-dialoog gedrag
  obj.find(".inloggen_link a").click(function() {
    var curPagFun = $(this);
    $.dimScreen(256, 0.5, function() {
      if (personalizable) {
        var profileUrl = extendUrl(read_Url, "profile=true&mode=login");
        openBox(curPagFun, profileUrl, "Profiel");
      }
      else {
        openBox(curPagFun);
      }
    });
    return false;
  });

  //link verrijken met ajax-dialoog gedrag
  obj.find("a.logout").click(function() {
    setProfile("");
  });

  // Google Analytics tracking voor downloads
  obj.find("a.downloadLink").click(function() {
    if (_gaq != null) {
      _gaq.push(['_trackPageview', $(this).attr('href')]);
    }
  });
}

function hideHiddenWebNotes(animated) {
  $('.webnote').each( function() {
    var webNoteId = $(this).attr('id');
    if (getCookie('hideNote_'+webNoteId) && getCookie('hideNote_'+webNoteId) == webNoteId) {
      animated?$(this).animate({ opacity: 0 }, 1000, null, function() { $(this).hide(); }):$(this).hide();
    }
  });
}

function initPageFunctions() {
  //webnotities sluiten
  $('a.webnote_close').click(function() {
    var webNoteId = $(this).closest('.webnote').attr('id');
    var expDate = new Date();  
    expDate.setDate(expDate.getDate() + 7); 
    setCookie('hideNote_'+webNoteId, webNoteId, expDate, '/');
    hideHiddenWebNotes(true);
    return false;
  });
  hideHiddenWebNotes();

  //links verrijken met ajax-dialoog gedrag
  $(".widget_crew a, .widget_mail a, .widget_feeds a, .widget_addtolinks a, .widget_share a, .widget_print_dialog a, .tab_virtual a").click(function() {
    var curPagFun = $(this);
    $.dimScreen(256, 0.5, function() {
      openBox(curPagFun);
    });
    return false;
  });

  $(".widget_print_dummy a").click(function() {
    var print_Url = $(this).attr('href').indexOf('#') == 0 ? document.location.href : $(this).attr('href');
    return !window.open(extendUrl(print_Url, 'media=print'), 'print');
  });

  $(".widget_feedback_in_subhome a, .widget_responses a").click(function() {
    var curPagFun = $(this);
    $.dimScreen(256, 0.5, function() {
      openBox(curPagFun, null, curPagFun.text(), true);
    });
    return false;
  });

  //menu open functie
  $(".open_menu")
    .append('<a href="#Navigatie">open menu</a>')
      .mouseover(function() { initOpenNav(); })
      .mouseout(function() { cancelOpenNav(); });

  $(".externForm").attr("target", "_blank");

  // zoeklinks
  $(".zoek_label a, .zoek_label_visual a").click(function() {
    if ($(this).attr("href") != $(this).attr("title") && !$(this).parents("form").find("input[name=Zoe]").hasClass('defaulttext')) {
      $(this).attr("href", $(this).attr("href") + "?PreZoe=" + $(this).parents("form").find("input[name=Zoe]").attr("value"));
    }
  });
}

function initPageBehaviour() {
  // mouseX en mouseY bijhouden
  if (!navOpen) {
    $(document).mousemove(function(e) {
      updateXY(e);
      updateNav(e);
    });
  }
  else {
    $(document).mousemove(function(e) { updateXY(e); });
  }

  // onscroll komt het "naar boven" blokje in beeld
  $(window).scroll(function() {
    $("#naar_boven").show();
  });
}

function openConfigSection(elt, ref, callback) {
  /* met ajax de inhoud ophalen */
  var href = ref ? ref : elt.attr("href");
  href = href.indexOf("#") != -1 ? href.substring(0, href.indexOf("#")) : href;
  href = completePersonalizedUrl(href);

  if (elt.is("form")) {
    $(".personalize").load(href + " .personalize_contents", elt.fastSerialize(), fillConfigSection);
  }
  else {
    href = extendUrl(href, "section=true");
    $(".personalize").load(href + " .personalize_contents", fillConfigSection);
  }
}

function fillConfigSection() {
  $(".personalize").css({ height: "auto", position: "absolute", "z-index": "1000", "left": "0px" });
  $("#Contents .contents").css({ "margin-top": $(".personalize").height() + 10 + "px" });
  $(".personalize .eval").each(function() {
    eval($(this).text());
  });
  initInterfaceElts(".personalize");
  configSectionOpen = true;
  if (typeof callback == 'function') callback();
  $(".button_cancel").click(function() {
    closeConfigSection();
    return false;
  });
}

function closeConfigSection() {
  var href = extendUrl(my_Url, "configured=true");
  $(".personalize").load(href + " .personalize_contents", function() {
    $(".personalize").css({ height: "30px", position: "static", overflow: "hidden" });
    $("#Contents .contents").css({ "margin-top": "0px" });
    initInterfaceElts(".personalize");
  });
  configSectionOpen = false;
  $.dimScreenStop();
}

function openBox(elt, ref, tit, wide, callback) {
  /* dialoogje bouwen, en met ajax de inhoud ophalen */
  var href = ref ? ref : elt.attr("href");
  href = href.indexOf("#") != -1 ? href.substring(0, href.indexOf("#")) : href;
  var title = tit ? tit : (elt.attr("title") ? elt.attr("title") : elt.text());
  var boxContents = '<div class="header_dialog"><div class="dialog_title">' + title + '</div><div class="dialog_close">Sluiten</div></div><div class="body_dialog"></div>';
  var bWidth = wide ? 500 : 250;
  var bStyle = wide ? "wide_dialog" : "small_dialog";
  var slotX = Math.floor(elt.offset().left / bWidth) * bWidth;
  if (slotX == 0) slotX = 25;
  if (slotX == 750) slotX = 725;
  if (slotX == 500 && bWidth == 500) slotX = 475;
  $("#dialog").remove();
  $('<div id="dialog" class="' + bStyle + '"></div>').css({
    left: slotX + 'px',
    top: curMouseY + 'px'
  }).appendTo(document.body).html(boxContents);
  $(".dialog_close").click(function() {
    closeBox();
  });
  fillBox(href, true, null, callback);
}

function fillBox(ref, init, params, callback, keepOpen) {
  var dialogUrl = ref;
  dialogUrl = dialogUrl.indexOf("#") != -1 ? dialogUrl.substring(0, dialogUrl.indexOf("#")) : dialogUrl;

  if (!params) {
    dialogUrl = extendUrl(dialogUrl, "dialog=true");
    if (dialogUrl.indexOf("login") != -1 ||
          dialogUrl.indexOf("profile") != -1 ||
          dialogUrl.indexOf("icons") != -1 ||
          dialogUrl.indexOf("addtolinks") != -1 ||
          dialogUrl.indexOf("show_foto") != -1 ||
          dialogUrl.indexOf("feeds") != -1) dialogUrl = completePersonalizedUrl(dialogUrl);
  }

  if (!keepOpen) {
    $(".body_dialog").css({ backgroundImage: "url(/views/shared/images/layout/progress.gif)", height: "50px" });
    $(".body_dialog > *").css({ visibility: "hidden" });
  }

  $(".body_dialog").load(dialogUrl + " .dialog_contents", params, function() {
    if (!keepOpen) {
      $(".body_dialog").css({ backgroundImage: "none", height: "auto" });
      $(".body_dialog > *").css({ visibility: "visible" });
    }
    initInterfaceElts(".body_dialog");
    $(".body_dialog .eval").each(function() {
      eval($(this).text());
    });

    if (init) {
      $("#dialog").animate({ top: 25 + $(document).scrollTop() + 'px' }, 320).css({ height: "auto" });
      try { $("#dialog").draggable({ handle: '.dialog_title' }); } catch (e) {
        $("#dialog .dialog_title").css({ cursor: "default" });
      }
    }
    if (dialogUrl.indexOf("login=true") != -1) {
      checkProfileLogin();
    }

    $(".button_dialog_cancel, .submit .button_close").click(function() {
      closeBox($(this).attr("id"));
      return false;
    });

    $("#add_cms_pageForm").submit(function() {
      hideBox();
      return true;
    });

    if (typeof callback == 'function') callback();

    //veld FbkIdt werd niet gevuld. Pluk hem nu uit de querystring en voeg dynamisch veld toe met de juiste waarde.
    //Deze wordt dan weer toegevoegd in de querystring zodat bij moderatie naar de juiste reactie wordt gescrolled.
    if (queryObj["FbkIdt"] != null && queryObj["FbkIdt"] != '') {
      $('input[name="FbkIdt"]').remove();
      $(this).find("form fieldset").append("<input type='hidden' name='ShwReactions' value='" + queryObj["ShwReactions"] + "' />");
      $(this).find("form fieldset").append("<input type='hidden' name='FbkIdt' value='" + queryObj["FbkIdt"] + "' />");
    }

  });

}

function closeBox(blkId) {
  /* dialoogje sluiten */
  $("#dialog").remove();
  $.dimScreenStop();
}

function hideBox(blkId) {
  /* dialoogje verbergen */
  $("#dialog").hide();
  $.dimScreenStop();
}

function makeBusyBox(obj, light) {
  var busyBoxHtml = light ? '<div class="busyBox busyLight"></div>' : '<div class="busyBox"></div>';
  $(obj).prepend(busyBoxHtml);
}

function removeBusyBox(obj) {
  $(obj).find(".busyBox").remove();
}


function checkStylesheets(sId, sHref) {
  var sheetFound = false;
  for (var sC = 0; sC < document.styleSheets.length; sC++) {
    if (document.styleSheets[sC].id && document.styleSheets[sC].id.indexOf("_sheet") != -1) {
      if (sId && document.styleSheets[sC].id == sId) {
        sheetFound = true;
        break;
      }
      else if (!document.styleSheets[sC].rules || document.styleSheets[sC].rules.length == 0) {
        document.styleSheets[sC].href = document.styleSheets[sC].href + "&retry=" + new Date().getTime();
      }
    }
  }
}

function updateNav(e) {
  /* bezoeker heeft menubalk verlaten: inklappen! */
  // document.title = navOpen +":"+eltsMoving +":"+e.pageY +":"+headerHeight+":"+navHeight;
  if (navOpen && !eltsMoving && e.pageY > headerHeight + navHeight) {
    closeNav();
  }
}

function initOpenNav() {
  /* gebruiker is op 'open menu' */
  if (navOpen) return false;
  else {
    if (navTimer) clearTimeout(navTimer);
    navTimer = setTimeout("openNav()", 128);
  }
}

function cancelOpenNav() {
  /* gebruiker verlaat 'open menu' */
  if (navOpen) return false;
  else {
    $("img#open_menu").attr("src", "/views/shared/images/nav/open_menu.gif");
    if (navTimer) {
      clearTimeout(navTimer);
      navOpen = false;
    }
  }
}

function openNav() {
  if (navTimer) { clearTimeout(navTimer); }
  navOpen = true;
  eltsMoving = true;
  $("#Sitepad")
    .animate({ top: -1 * (sitepadHeight + tabbarHeight + headerHeight) + "px" }, 100, function() {
      $(".mainmenu")
        .animate({ top: (tabbarHeight + headerHeight) + "px" }, 200, function() { eltsMoving = false; });
    });
}

function closeNav() {
  navOpen = false;
  eltsMoving = true;
  $(".mainmenu")
    .animate({ top: -1 * (navHeight + tabbarHeight + headerHeight) + "px" }, 100, function() {
      $("#Sitepad")
        .animate({ top: "0px" }, 200, function() { eltsMoving = false; });
    });
}

var initialMenuSize = 0;

function largestMenuSize() {
  var menuItemsCount = $("ul.main > li:visible").length;
  $("ul.main > li:visible > ul").each(function() {
    var mnu = $(this).attr("id").split("_");
    var mnuSet = mnu[0];
    var mnuElt = mnu[1];
    var mnuIdt = mnu[2] + "_" + mnu[3];

    if (openedMenus[mnuSet] == mnuIdt) {
      var subItemsCount = $(this).find("li").length;
      menuItemsCount = subItemsCount > menuItemsCount ? subItemsCount : menuItemsCount;
    }
  });
  return menuItemsCount;
}

var menuInitialized = false;
var initialMenuSize = 0;

function initMenu(context) {
  var largestItemsCount = largestMenuSize();

  if (!menuInitialized) {
    initialMenuSize = $('#Mainmenu').css('height');
  }

  currentMenuSize = $('#Mainmenu').css('height');
  neededMenuSize = (largestItemsCount * 18) + 36;
  if (neededMenuSize >= parseInt(initialMenuSize, 10) && neededMenuSize != parseInt(currentMenuSize, 10)) {
    $('#Mainmenu').animate({ height: neededMenuSize + 'px' }, 800);
    $('ul.main').animate({ height: neededMenuSize + 'px' }, 800);
    if (initialNavOpen) {
      if ($('#Tabs.tabs_onder').length == 0) {
        $('#Header').animate({ marginBottom: neededMenuSize + 'px' }, 800);
      }
      else {
        $('#Tabs').animate({ marginBottom: neededMenuSize + 'px' }, 800);
      }
    }
  }

  $("ul.main li.more", context).click(function() {
    var href = $(this).find('a').attr('href');
    var args = $(this).parents('ul').find('li.home').length == 0 ? 'menuhome=false' : 'menuhome=true';
    if (href.indexOf('mainmenu=') == -1) {
      args += '&mainmenu=true';
    }
    $(this).load(extendUrl(href, args) + ' ul.main', function() {
      var menuHtml = $(this).find(' ul.main').html();
      $(this).parents('ul.main').html(menuHtml);
      initMenu($('ul.main'));
    });
    return false;
  });

  // mousover gedrag menu > home
  $("li.home", context).each(function() {
    $(this)
      .mouseover(function() {
        $(this).addClass("active");
      })
      .mouseout(function() {
        $(this).removeClass("active");
      });
  });

  // mousover gedrag menu
  $("li.nav", context).each(function() {
    var mnu = $(this).attr("id").split("_");
    var mnuSet = mnu[0];
    var mnuElt = mnu[1];
    var mnuIdt = mnu[2] + "_" + mnu[3];

    if (!menuInitialized && openedMenus[mnuSet] && openedMenus[mnuSet] == mnuIdt) {
      openedMenus[mnuSet] = "init";
      menuInitialized = true;
      openMenu(mnuIdt, mnuSet);
    }

    $(this)
      .mouseover(function() {
        $(this).addClass("active");
        initOpenMenu(mnuIdt, mnuSet);
      })
      .mouseout(function() {
        $(this).removeClass("active");
      });
  });

  // mousover gedrag submenu
  $("li.subnav", context).each(function() {
    var mnu = $(this).parents("li.nav").attr("id").split("_");
    var mnuSet = mnu[0];
    var mnuElt = mnu[1];
    var mnuIdt = mnu[2] + "_" + mnu[3];

    $(this)
      .mouseover(function() {
        keepMenuOpen(mnuIdt, mnuSet);
        $(this).addClass("active");
      })
      .mouseout(function() {
        $(this).removeClass("active");
      });
  });

  // dynamisch functie iconen instellen
  $("ul.functions li .funct_icon", context).each(function() {
    if (!$(this).hasClass('uploaded')) {
      if (!$(this).hasClass('fluency') && $(this).attr("class").indexOf("achtergrond_img") == -1) {
        var curCls = $(this).attr("class").split("function_")[1];
        var curScheme = $(this).parent("li").parent("ul").attr("class").split("_")[1];
        if (curScheme == "self") {
          $(this).css("background-image", "url(" + viewFolder + "images/functions/" + curCls + ".gif)");
        }
        else if (curScheme == "shared") {
          $(this).css("background-image", "url(" + sharedFolder + "images/functions/" + curCls + ".gif)");
        }
        else {
          $(this).css("background-image", "url(" + viewFolder + "images/functions/" + curScheme + "/" + curCls + ".gif)");
        }
      }
    }
  });

  // mousover gedrag functie iconen
  $("ul.functions li", context).each(function() {
    $(this)
      .mouseover(function() {
        $(this).addClass("hoverli");
      })
      .mouseout(function() {
        $(this).removeClass("hoverli");
      });
  });
}

function initOpenMenu(id, mnu) {
  /* in hoofdnavigatie; trigger uitklappen subnavigatie onder niveau-1 item */
  mnu = mnu ? mnu : "mainmenu";
  if (id == openedMenus[mnu]) return false;
  else {
    if (menuTimer) { clearTimeout(menuTimer); }
    menuTimer = window.setTimeout("openMenu('" + id + "','" + mnu + "')", 500);
    return true;
  }
}

function openMenu(id, mnu) {
  mnu = mnu ? mnu : "mainmenu";
  if (menuTimer) { clearTimeout(menuTimer); }

  if (openedMenus[mnu] && openedMenus[mnu] != "" && id != openedMenus[mnu]) {
    $("#" + mnu + "_open_" + openedMenus[mnu]).removeClass("open");
  }

  if (id != openedMenus[mnu]) {
    $("#" + mnu + "_open_" + id).removeClass("active");
    var SttItmIdt = id.split('_')[0];
    var href = $("#" + mnu + "_open_" + id + " > a").attr('href');

    if ($("#" + mnu + "_menu_" + id).length > 0) {
      $("#" + mnu + "_open_" + id).addClass("open");
      openedMenus[mnu] = id;
    }
  }
}

function keepMenuOpen(id, mnu) {
  mnu = mnu ? mnu : "mainmenu";
  if (menuTimer) { clearTimeout(menuTimer); }
  openedMenus[mnu] = id;
}

$(document).ready(function(){
  $(".toggle.donker_open").closest("li").find(".toggle.chapter").first().html("-");
  $(".toggle.licht_open").closest("li").find(".toggle.chapter").first().html("-")
});

function toggleList(obj, id) {
  var is_chapter = false;
  var openAll = false;

  if ($(obj).hasClass("chapter")) {
    if ($(obj).text() == "+" || $(obj).text() == "+(#)") {
      $(obj).text("-");
      $(obj).closest("li").find("ul").removeClass("closed").addClass("open");


      $(obj).closest("li").find(".toggle.licht_normal").css("background-image", "url(/views/shared/images/nav/mapbullet_licht_1.gif)");


      openAll = true;
    }
    else {
      $(obj).text("+");
      $(obj).closest("li").find(".toggle.licht_normal").first().attr("style", "");
    }
    obj = $(obj).parent().parent().parent("li").find(".collapser_link .toggle").first();
    is_chapter = true;
  }

  id = id ? id : $(obj).attr("href");
  if (id.indexOf("#") != -1) {
    id = id.substring(id.indexOf("#") + 1, id.length);
  }
  if ($("#" + id)) {
    var currentOpen = $("#" + id).hasClass("open");
    var swapSrc = $(obj).css("background-image");
    if (currentOpen) {
      if (!openAll) {
        $(obj).css("background-image", swapSrc.replace("_1.gif", "_0.gif"));
        $("#" + id).removeClass("open");
        $("#" + id).addClass("closed");
        $("#" + id).closest("li").find(".toggle.chapter").first().html("+");
      }
      else {
        if ($(obj).attr("style") != "") {
          $(obj).css("background-image", swapSrc.replace("_0.gif", "_1.gif"));
        }

        $("#" + id).closest("li").find(".toggle.chapter").html("-");
        $("#" + id).find(".toggle.licht_normal").css("background-image", "url(/views/shared/images/nav/mapbullet_licht_1.gif)");
      }

    }
    else {
      $(obj).css("background-image", swapSrc.replace("_0.gif", "_1.gif"));

      if ($("#" + id).hasClass("closed")) {
        $("#" + id).removeClass("closed");
        $("#" + id).addClass("open");
        $("#" + id).closest("li").find(".toggle.chapter").first().html("-");
      }
      else {
        if ($("#" + id).hasClass("chapter") == false) {
          if ($(obj).parent("li:not(:has(ul))") && $(obj).attr("class").indexOf("toggle_") != -1) {
            var ItmIdt = id.split("_")[1];
            var href = $(obj).attr("href").split("#")[0];
            href = extendUrl(href, "node=" + $(obj).attr("class").split("toggle_")[1]);
            href = extendUrl(href, "toggle=" + ItmIdt);

            if (is_chapter) {
              href = extendUrl(href, "is_chapter=true");
            }

            $(obj).parent("span").parent("li").find(".container").load(href, function() {
              if ($(this).closest("li").find(".toggle.chapter").html() == "-") {
                $(this).find(".toggle.chapter").html("-");
                $(this).closest("li").find(".toggle.licht_normal").css("background-image", "url(/views/shared/images/nav/mapbullet_licht_1.gif)");
              }

              $(this).find(".toggle").click(function() {
                return toggleList(this);
              });

              if (is_chapter) {
                $(obj).parent().parent().parent("li").find(".container .toggle").css("background-image", swapSrc.replace("_0.gif", "_1.gif"));
              }
            });
          }
        }
      }
      // ajax sitemaps

    }
    return false;
  }
  else return true;
}

var curSpotOpen = "";

function toggleHotspot(id, show) {
  if (curSpotOpen != "" && curSpotOpen != id) {
    $("#" + curSpotOpen).hide();
  }
  if (curSpotOpen != id) {
    var lX = (curMouseX + 250 < contentWidth) ? curMouseX : contentWidth - 250;
    $("#" + id).css("left", lX + "px");
    $("#" + id).css("top", (curMouseY - 50) + "px");
  }
  show ? $("#" + id).show() : $("#" + id).hide();
  if (show) curSpotOpen = id;
  else curSpotOpen = "";
  return false;
}

function showOverlay(spotMapId, src) {
  if (src) {
    $("#" + spotMapId + " img").attr("src", src);
  }
  else {
    $("#" + spotMapId + " img").attr("src", "/views/shared/images/layout/transp.gif");
  }
}

function highlightEditable(obj, id, status) {
  var orgColor = obj.style.backgroundColor ? obj.style.backgroundColor : "transparent";
  if (status) orgColors[id] = orgColor;
  orgColor = orgColors[id] ? orgColors[id] : "transparent";
  obj.style.backgroundColor = status ? "#eeeeee" : orgColor;
}

function reloadWhenLoggedIn(baseUrl, callback) {
  if (!baseUrl) baseUrl = my_Url.substring(0, my_Url.indexOf("?"));
  var loginUrl = extendUrl(baseUrl, "xdl=/views/shared/xdl/json/logincheck&xsl=/views/shared/xsl/json/logincheck"); // &u="+new Date().getTime()
  $.getJSON(loginUrl, function(status) {
    if (status.logged_in != "false") {
      iprox_GebIdt = status.GebIdt;
      setProfile(status.PxfGebIdt);
      if (status.logged_in == "iprox" && pageReloadWhenLoggedIn) {
        reloadLoggedIn(my_Url);
      }
    }
    if (typeof callback == 'function') callback();
  });
}

function reloadLoggedIn(baseUrl) {
  var url = baseUrl ? baseUrl : my_Url.substring(0, my_Url.indexOf("?"));
  document.location = personalizeUrl(url);
}

/* na inlog via dialog, en bij initialisatie subhome */
function checkProfileLogin(baseUrl, callback) {
  if (getCookie('profile_PxfGebIdt') && profile_PxfGebIdt == "") {
    profile_PxfGebIdt = getCookie('profile_PxfGebIdt');
  }

  if (iprox_GebIdt == "00000000") {
    iprox_GebIdt = "";
  }

  if (profile_PxfGebIdt == "" && iprox_GebIdt == "") {
    // geen profielinlog obv. cookie : ophalen
    reloadWhenLoggedIn(extendUrl(baseUrl, "session_reload=true"), callback);
  }
  else if (pageReloadWhenLoggedIn && pageBuilt) {
    // full reload
    reloadLoggedIn(my_Url);
  }
  else {
    // alleen "under" updaten
    updateStatus(baseUrl, callback);
  }
}

function updateStatus(baseUrl, callback, params) {
  // "under" updaten
  if (!baseUrl) baseUrl = my_Url.substring(0, my_Url.indexOf("?"));
  var underUrl = extendUrl(baseUrl, "under=true");
  underUrl = completePersonalizedUrl(underUrl);
  if (params) { // POST
    $(".under .info").load(underUrl + " .under .info > *", params, function() {
      initInterfaceElts(".under");
      if (typeof callback == 'function') callback();
    });
  }
  else {
    $(".under .info").load(underUrl + " .under .info > *", function() {
      initInterfaceElts(".under");
      if (typeof callback == 'function') callback();
    });
  }
}

function invalidCookieLogin(type) {
  if (type == "profile_PxfGebIdt") {
    setProfile("");
  }
}

function checkProfile(elt, callback) {
  var loginStatus = $(".under .info .message").attr("id");

  if (getCookie('profile_PxfGebIdt') && profile_PxfGebIdt == "") {
    // profiel via cookie
    profile_PxfGebIdt = getCookie('profile_PxfGebIdt');
  }
  else if (profile_PxfGebIdt == "" && loginStatus && loginStatus.indexOf("profile_PxfGebIdt") != -1) {
    // profiel via ajax
    profile_PxfGebIdt = $(".under .info .message").attr("id").split("profile_PxfGebIdt_")[1];
  }

  if (profile_PxfGebIdt == "") {
    // anoniem profiel aanmaken
    updateStatus(extendUrl($(".noprofile_form form").attr("action"), "session_reload=true"), callback, $(".noprofile_form form").fastSerialize());
    return false;
  }
  else {
    // ingelogd
    if (typeof callback == 'function') callback();
    return true;
  }
}

function setProfile(id) {
  if (id != "" && id != "0") {
    profile_PxfGebIdt = id;
  }
  else {
    delCookie("profile_PxfGebIdt");
    profile_PxfGebIdt = "";
  }
}

function completePersonalizedUrl(url) {
  return personalizeUrl(url, true);
}


function personalizeUrl(url, donotforce) {
  if (getCookie('profile_PxfGebIdt') && profile_PxfGebIdt == "") {
    profile_PxfGebIdt = getCookie('profile_PxfGebIdt');
  }

  if (iprox_GebIdt == "00000000") {
    iprox_GebIdt = "";
  }

  if (profile_PxfGebIdt != "" && url.indexOf("profile_PxfGebIdt") == -1) {
    url = extendUrl(url, "profile_PxfGebIdt=" + profile_PxfGebIdt);
  }
  else if (iprox_GebIdt != "" && url.indexOf("iprox_GebIdt") == -1) {
    url = extendUrl(url, "iprox_GebIdt=" + iprox_GebIdt);
  }

  if (url.indexOf("GebIdt") == -1 && url.indexOf("u=") == -1 && !donotforce) {
    url = extendUrl(url, "u=" + new Date().getTime());
  }
  return url;
}

function backgroundToSrc(bgImg) {
  bgImg = bgImg.indexOf('url(') == -1 ? bgImg : bgImg.substring(4, bgImg.length - 1);
  bgImg = bgImg.replace('"', '');
  bgImg = bgImg.replace("'", "");
  return bgImg;
}

function initIndexFeatures() {
  if (idxPagIdt) {
    $(".contents").bladerOptie('/aspx/get.aspx?xdl=/views/shared/xdl/ajax/bladeroptie&xsl=/views/shared/xsl/ajax/bladeroptie', idxPagIdt, showSitIdt, showVarIdt, itmIdt);
  }
  if (idxFrmIdt) {
    $("#Margekolom").getIndexForm(my_Url, idxFrmIdt);
  }
}

(function($) {
  $.fn.interfaceElts = function() {
    initInterfaceElts("", $(this));
    return $(this);
  };

  /*
  Create pager element.
  */
  $.fn.bladerOptie = function(url, itmIdt, sitIdt, varIdt, actItmIdt) {
    var container = $(this);

    $.ajax({
      url: url,
      data: {
        "ItmIdt": itmIdt,
        "SitIdt": sitIdt,
        "VarIdt": varIdt,
        "ActItmIdt": actItmIdt
      },
      type: 'GET',
      dataType: 'html',
      success: function(data) {
        container.append(data);
      },
      error: function() {
        alert("error");
      }
    });
    return $(this);
  };

  /*
  Create index form.
  */
  $.fn.getIndexForm = function(url, itmIdt) {
    var container = $(this);

    url = url.indexOf("/@") == -1 ? url : url.substring(0, url.indexOf("/@"));

    $.ajax({
      url: url,
      data: {
        "ActItmIdt": itmIdt,
        "HidResOnStt": "true"
      },
      type: 'GET',
      dataType: 'html',
      success: function(data) {
        container.prepend($(data).find('#Margekolom > *'));
      },
      error: function() {
        alert("error");
      }
    });
    return $(this);
  };
})(jQuery);
