/**
 * (c) InfoProjects bv. - www.infoprojects.nl
 *
 * $Revision: 1.87 $
 * $Date: 2010/04/29 20:41:41 $
 * $Author: Ad $
 */

var menuTimer;
var navTimer;
var navOpen;

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;

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();
  }
}

function initPageLayout() {
  // header_popup vullen (popup)
  $(".header_popup[id=Header]").each(function () {
    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' } );
      });
    }
  });

  $(".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;
  });

  $("area.open_in_iframe").click(function() {
    var href = $(this).attr('href');
    var iFrameHtml = '<iframe allowtransparency="true" frameborder="0" width="'+$('#Contents').width()+'" height="1000" src="'+href+'"></iframe>'
    $('#Contents').html(iFrameHtml);
    return false;
  });
}

function initInterfaceElts(eltId) {
  // eltId kan vanuit een ajax partial call komen (bv. subhome.js)
  jQbase = eltId?eltId+" ":"";

  // linkpointers
  $(jQbase+".symbol_plus").text("[+]");
  $(jQbase+".symbol_minus").text("[-]");
  $(jQbase+".symbol_download").text("[~]");
  $(jQbase+".symbol_extern").text("[>]");
  $(jQbase+".symbol_pagina").text("[<]");
  $(jQbase+".symbol_change").text("[^]");
  $(jQbase+".symbol_folder").text("[/]");

  $(jQbase+".activate_handheld").animate( { opacity:0 }, 10000, null, function() { $(this).hide(); } );

  // printversie voorbereiding
  $(jQbase+".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
  $(jQbase+".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
  $(jQbase+".contents a[href^=http]:not(:has(img))").each( function () {
    var href = $(this).attr('href');
    if (href.length>64) {
      href = href.substring(href.indexOf('://')+3).split('/').join('/&#173;');
    }
    $(this).append('<span class="linkDesc">('+href+')</span>');
  });

  // printversie voorbereiding: email adressen uitschrijven
  $(jQbase+".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
  $(jQbase+".contents .module a .linkDesc, "+jQbase+".contents .linkpointer a .linkDesc, "+jQbase+".contents li a .linkDesc").each( function () {
    $(this).prepend('<br/>');
  });

  // superlinks sizen (subhome)
  $(jQbase+".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)
  $(jQbase+".leadblock[title], "
      +jQbase+".leadblock_breed[title], "
      +jQbase+".leadblock_breed2[title], "
      +jQbase+".leadblock_breed3[title], "
      +jQbase+".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")
  $(jQbase+"h3.linkpointer a").each(function () {
    $(this).prepend('<span class="symbol symbol_plus">[+]</span>');
  });

  // titels van modules met maar 1 link laten linken
  $(jQbase+"h3.linking:not(.linkpointer)").each(function () {
    var titleHtml = $(this).html();
    var titleLinkHref = $(this).parents(".module:first").find("a:not([href*='PagClsRange']):last").attr("href");
    var titleLinkClass = $(this).parents(".module:first").find("a:not([href*='PagClsRange']):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
  $(jQbase+".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
  $(jQbase+".small_calendar").each(function () {
    var calendarDate = $(this).attr("title").split("-");
    $(this).attr("title","");
    buildCalendar(calendarDate[0],calendarDate[1],calendarDate[2],$(this).attr("id"));
  });

  $(jQbase+".toggle").click(function() {
    return toggleList(this);
  });

  var contra_black = "red";
  var contra_grey = "black";
  var contra_red = "black";
  var contra_transp = "black";

  // swapknoppen definieren
  $(jQbase+"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
  $(jQbase+"input.with_image, "+jQbase+"button[class*='with_image'], "+jQbase+"a.button[class*='with_image']").each(function () {
    if ($(this).css("background-image") != 'none') {
      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
  $(jQbase+".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
  $(jQbase+".dialog_foto .button_previous, "+jQbase+".dialog_foto .button_next, ").click( function() {
    $(jQbase+".dialog_foto img").animate( { opacity:0.1 }, 1000 );
  });

  $(jQbase+".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;
  });

  $(jQbase+".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
  $(jQbase+"a.login").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
  $(jQbase+"a.logout").click(function() {
    setProfile("");
  });
}

function initPageFunctions() {
  //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?my_Url:$(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(); });

  // zoeklinks
  $(".zoek_label a, .zoek_label_visual a").click ( function() {
    if ($(this).attr("href") != $(this).attr("title") && $(this).parents("form").find("input[name=Zoe]").attr("value") != $(this).parents("form").find("input[name=Zoe]").attr("title")) {
      $(this).attr("href",$(this).attr("href")+"?PreZoe="+$(this).parents("form").find("input[name=Zoe]").attr("value"));
    }
  });

  $("form[id^=zoek_]").submit( function() {
    if ($(this).find("input[name=Zoe]").val() == $(this).find("input[name=Zoe]").attr("title")) {
      $(this).find("input[name=Zoe]").val("");
    }
  });
}

function initPageBehaviour() {
  // mouseX en mouseY bijhouden
  if (!navOpen) {
    $(document).mousemove(function(e){
      updateXY(e);
      updateNav(e);
    });
  }
  else {
    $(document).mousemove(function(e){ updateXY(e) });
  }

  //zoekboxen vullen met de waarde van hun titel (wordt na focus geleegd)

  $(".zoek input[name=Zoe]").each(function () {
    $(this).val($(this).attr("title"))
      .focus(function() {
        $(this).val("");
      })
      .blur(function() {
        if ($(this).attr("value")=="") {
          $(this).val($(this).attr("title"));
        }
      });
  });

  // 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);

  //myDebug("openConfigSection : "+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;
  $('<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;
    });
    if(typeof callback == 'function') callback();
  });
}

function closeBox(blkId) {
  /* dialoogje sluiten, en met ajax de inhoud ophalen */
  $("#dialog").remove();
  $.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; });
      });
}


function initMenu() {
  // mousover gedrag menu > home
  $("li.home").each(function() {
    $(this)
      .mouseover( function() {
        $(this).addClass("active");
      })
      .mouseout( function() {
        $(this).removeClass("active");
      });
  });

  // mousover gedrag menu
  $("li.nav").each(function() {
    $(this)
      .mouseover( function() {
        var mnu = $(this).attr("id").split("_");
        var mnuSet = mnu[0];
        var mnuElt = mnu[1];
        var mnuIdt = mnu[2]+"_"+mnu[3];
        $(this).addClass("active");
        initOpenMenu(mnuIdt,mnuSet);
      })
      .mouseout( function() {
        var mnu = $(this).attr("id").split("_");
        var mnuSet = mnu[0];
        var mnuElt = mnu[1];
        var mnuIdt = mnu[2]+"_"+mnu[3];
        $(this).removeClass("active");
      });
  });

  // mousover gedrag submenu
  $("li.subnav").each(function() {
    $(this)
      .mouseover( function() {
        var mnu = $(this).parents("li.nav").attr("id").split("_");
        var mnuSet = mnu[0];
        var mnuElt = mnu[1];
        var mnuIdt = mnu[2]+"_"+mnu[3];
        keepMenuOpen(mnuIdt,mnuSet);
        $(this).addClass("active");
      })
      .mouseout( function() {
        $(this).removeClass("active");
      });
  });

  // dynamisch functie iconen instellen
  $("ul.functions li[class]").each(function() {
    if (!$(this).hasClass('fluency')) {
      var curCls = $(this).attr("class").split("_")[1];
      var curScheme = $(this).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").each(function() {
    $(this)
      .mouseover( function() {
        var swapSrc = $(this).css("background-image");
        $(this).css("background-image",swapSrc.replace(".gif","_ro.gif"));
      })
      .mouseout( function() {
        var swapSrc = $(this).css("background-image");
        $(this).css("background-image",swapSrc.replace("_ro.gif",".gif"));
      });
  });
}

function toggleList(obj,id) {
  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) {
      $(obj).css("background-image",swapSrc.replace("_1.gif","_0.gif"));
      $("#"+id).removeClass("open");
      $("#"+id).addClass("closed");
    }
    else {
      $(obj).css("background-image",swapSrc.replace("_0.gif","_1.gif"));
      $("#"+id).removeClass("closed");
      $("#"+id).addClass("open");

      // ajax sitemaps
      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);
        $(obj).parent("li").find(".container").load(href+" ul",function() {
            $(this).find(".toggle").click(function() {
              return toggleList(this);
            });
          });
      }
    }
    return false;
  }
  else return true;
}

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");
    $("#"+mnu+"_open_"+id).addClass("open");
    openedMenus[mnu] = id;
  }
}

function keepMenuOpen(id,mnu) {
  mnu = mnu?mnu:"mainmenu";
  if (menuTimer) { clearTimeout(menuTimer); }
  openedMenus[mnu] = id;
}

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);
  //myDebug("updateStatus : "+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 myDebug(msg) {
  //return;
  if ($("#debug").length == 0) {
    $('<div></div>').attr({
        id: 'debug'
      }).css({
          position: 'absolute',
          backgroundColor: '#dddddd',
          fontSize: '9px',
          zIndex: '1000',
          right: '20px',
          top: '50px',
          width: '200px',
          height: '700px'
      }).appendTo(document.body).html('<ul></ul>');
  }
  $('#debug ul').append('<li>'+msg+'</li>');
  $('#debug').click( function() { $(this).empty().html('<ul></ul>') });
}

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');
    //myDebug("profiel via cookie : "+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];
    //myDebug("profiel via ajax : "+profile_PxfGebIdt);
  }

  if (profile_PxfGebIdt == "") {
    // anoniem profiel aanmaken
    //myDebug("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');
    //myDebug("cookie found : "+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;
}