﻿menu = new clsMenu();
var overlay;
/* ---------------------------------------------------------------------------------- */
/* ----- Functies: includes --------------------------------------------------------- */
/* ---------------------------------------------------------------------------------- */

// jQuery random-selector definiëren
jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"], {
  random: function(a, i, m, r) {
    if (i == 0) {
      jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
    };
    return i == jQuery.jQueryRandom;
  }
});


/* ---------------------------------------------------------------------------------- */
/* ----- Functies: onLoad ----------------------------------------------------------- */
/* ---------------------------------------------------------------------------------- */

$(document).ready(function () {
  trackEvents();        // Google Analytics events tracken
  initColorbox();       // Colorbox activeren
  initSubnavOverlay();  // Subnavigatie overlay activeren
  initSearch();         // Zoeken activeren
  initFAQ();            // Veelgestelde vragen activeren
  initZorgWizard();     // Activeren van Wizard
  initFormulieren();    // Formulier validatie
  initVideos();         // Videos activeren
  initPostcodeZoeker(); // Postcodezoeker activeren
  initLaunch();         // Lanceringsanimatie activeren
  initAddressList();    // Adressenlijsten activeren
  $('#header .nav li:not(#header .nav li li)').bind("mouseenter", function (e) { menu.MouseEnter($(this)); });
  $('#header .nav li:not(#header .nav li li)').bind("mouseleave", function (e) { menu.MouseLeave($(this)); });
  $("#zorggemeente").bind("click", function () {
    window.location = $("#zorggemeente").attr("href") + "?gemeente=" + $(".keuze-gemeente option:selected").val();
    return false;
  });
  $("#afrekenen").bind("click", function () {
    $(".order-form").show();
    $(this).hide();
  });
  $(".nav .subnav-uitgelicht").each(function () {
    $(this).html($("#extratekst .subnav-uitgelicht:first").html());
    $("#extratekst .subnav-uitgelicht:first").remove();
  });
});


/* ---------------------------------------------------------------------------------- */
/* ----- Functies: Algemeen --------------------------------------------------------- */
/* ---------------------------------------------------------------------------------- */

// Google Analytics events tracken
trackEvent = function (newurl, category, shortversion) {
  if (!shortversion) { shortversion = newurl; }
  _gaq.push(['_trackPageview', newurl]);
  _gaq.push(['_trackEvent', document.location.href, category, shortversion]);
}

trackEvents = function () {
  $("a[target='_blank']:not([href^='/upload/'])").click(function () { trackEvent($(this).attr("href"), "Link"); })
  $("a[href^='mailto:']").click(function () { trackEvent($(this).attr("href"), "Mail"); })
  $("a[target='_blank'][href^='/upload/']:not([rel='lightbox'])").click(function () { trackEvent($(this).attr("href"), "Download"); })
}

// Input-elementen voorzien van blur en focus events om standaard-tekst te tonen/verbergen
function bindInputEvents(inputElement) {
  if ($(inputElement).length > 0) {
    var defaultValue = "Doorzoek de website...";
    $(inputElement).bind("focus", function (e) {
      if (this.value == defaultValue) $(this).val("").addClass("active");
    }).bind("blur", function (e) {
      if (this.value == "") $(this).val(defaultValue).removeClass("active");
    });
  }
}

// Colorbox activeren
function initColorbox() {
  if ($.isFunction($.fn.colorbox)) {
    $("a[rel='lightbox']").colorbox({ maxHeight: "600px" });
    $("a[rel='gallery']").colorbox({ maxHeight: "600px", slideshow: true, slideshowAuto: true, slideshowSpeed: 5000 });
    //$("a[rel*='iframe']").colorbox({ iframe: true, innerWidth: 800, innerHeight: 450 });
    $(".fotoalbum a").colorbox({ maxHeight: "600px", slideshow: true, slideshowAuto: true, slideshowSpeed: 5000 });
    $(".fotoalbum-start").click(function () {
      $(this).next().find('a:first').click();
    });
  }
}

// Subnavigatie overlay activeren

function initSubnavOverlay() {
  $("body").append("<div id=\"subnav-overlay\"></div>");
  overlay = $("#subnav-overlay");
  overlay.css({"opacity":"0.2"});
//  function resizeOverlay() {
//    if ($("body").outerHeight(true) > $(window).height()) { var overlayHeight = $("body").outerHeight(true); }
//    else { var overlayHeight = $(window).height(); }
//    overlay.height(overlayHeight);
//  }
  //resizeOverlay();
  //$("#header .nav").children("li.has-subnav").hover(function () { resizeOverlay(); overlay.show(); }, function () { overlay.hide(); });
}

function initPostcodeZoeker() {
  
var url = location.href;
var url_parts = url.split('?');
var main_url = url_parts[0]; 
  $('.postcodezoeker-postcode').click(function () {
    document.location = main_url + "?postcode=" + $('#postcodecheck-postcode').val();
    return false;
  });
  $('.postcodezoeker-zorg').click(function () {
    document.location = main_url + "?zorg=" + $('#postcodecheck-zorg').val();
    return false;
  });
}

/* ---------------------------------------------------------------------------------- */
/* ----- Functies: Zoeken ----------------------------------------------------------- */
/* ---------------------------------------------------------------------------------- */

// Zoeken activeren
function initSearch() {
  if ($("#search-field").length > 0) {
    // Zoekvenster events binden  
    $("#search-field").attr("autocomplete", "off")
    $("#header .searchbox").append("<div id=\"search-suggestions\"></div>");
    bindInputEvents("#search-field");
    $("#search-field").bind("keydown", function (e) { if ((document.layers ? evt.which : e.keyCode) == 13) { return false; } });
    $("#search-field").bind("keyup", function (e) { if ((document.layers ? evt.which : e.keyCode) == 13) { return search("#search-field", "#search-button", "Doorzoek de website..."); } else { suggest($(this).val()); } });
    $("#search-field").bind("focus", function (e) { suggest($(this).val()) });
    //$("#search-field").bind("blur", function (e) { fill() });
    $("#search-button").bind("click", function () { search("#search-field", "#search-button", "Doorzoek de website..."); });
  }
}

// Zoek-opdracht uitvoeren
function search(fieldSelector, buttonSelector, strIgnore) {
  var strZoek = $(fieldSelector).val();
  if (strZoek.length > 0 && strZoek != strIgnore) {
    var strEncodedZoek = encodeURIComponent(strZoek);
    var strNewUrl = $(buttonSelector).attr("rel") + strEncodedZoek;
    trackEvent(strNewUrl, "Zoeken", strZoek);
    //strZoek = strZoek.replace(/ /g, '+').replace(/\%20/g, '+');
    setTimeout('document.location = "' + strNewUrl + '"', 100);
  }
  return false;
}

var currentTimer = null;

function suggest(inputString) {
  clearTimeout(currentTimer);
  if (inputString.length == 0) { $('#search-suggestions').fadeOut(); }
  else {
    currentTimer = setTimeout(function () {
      $('#searchbox').addClass('load');
      $.get("/pages/ajax/zoekpreview.aspx", { zoek: "" + inputString + "" }, function (data) {
        if (data.length > 0) {
          if ($(data).find(".suggestions-header").text() == "") {
            $('#searchbox').removeClass('load');
            $('#search-suggestions').fadeOut();
          } else {
            $('#search-suggestions').html(data);
            $('#search-suggestions').fadeIn();
          }
        } else {
          $('#search-suggestions').fadeOut();
        }
        $('#searchbox').removeClass('load');
      });
    }
  , 400)
  }
}

function fill(thisValue) {
  $('#search-field').val(thisValue);
  setTimeout("$('#search-suggestions').fadeOut();", 200);
}

/* ---------------------------------------------------------------------------------- */
/* ----- Functies: Formulieren ------------------------------------------------------ */
/* ---------------------------------------------------------------------------------- */

function initFormulieren() {
  if ($(".form .submitbutton a").length > 0) {
    // inladen js.
    formtest = $().formtest($(".form .submitbutton a"), "form");
  }  
}

/* ---------------------------------------------------------------------------------- */
/* ----- Functies: Veelgestelde vragen (FAQ) ---------------------------------------- */
/* ---------------------------------------------------------------------------------- */

// Veelgestelde vragen activeren
function initFAQ() {
  $("#main .faq-questions li:not('.active') .answer").hide();
  $("#main .faq-questions li h3").click(
    function () {
      if (!$(this).parent().hasClass("active")) { $(this).parent().siblings().removeClass("active").find(".answer").slideUp(200); }
      $(this).next(".answer").stop(true, true).slideToggle(200);
      $(this).parent().toggleClass("active");
    }
  );
}

// Ajax-functie, wordt nog nergens gebruikt. Sipke-Jan?
function ajaxafhandeling(xml, fillel, el, slide) {
  if ($(xml).find("respons").length > 0) {
    if (el) {
      fillel.html($(xml).find("respons").text());
      if (slide) { el.slideDown(); }
    }
  }
  if ($(xml).find("eval").length > 0) { eval($(xml).find("eval").text()); }
  if ($(xml).find("melding").length > 0) { alert($(xml).find("melding").text()); }
  if ($(xml).find("redirect").length > 0) { document.location.href = $(xml).find("redirect").text(); }
}

function initZorgWizard(blnfirst) {
  if (!blnfirst) {
    $(".wizard .wizard-answers li a[rel*='iframe']").colorbox({ iframe: true, innerWidth: 800, innerHeight: 450, titletext: "test" });
  }
  $(".wizard .wizard-answers li").click(function () {
    ajaxZorgWizard("/pages/ajax/ajaxwizard.aspx?id=" + $(this).attr("data-show-next"));
  });
  if ($(".wizard .wizard-back").attr("data-show-parent") != null) {
    $(".wizard .wizard-back").click(function () {
      ajaxZorgWizard("/pages/ajax/ajaxwizard.aspx?id=" + $(this).attr("data-show-parent"));
    });
  }
  
}

function ajaxZorgWizard(strUrl) {
  
  if (!strUrl.match(/undefined$/)) {
    $.ajax({
      type: "GET",
      url: strUrl,
      dataType: "xml",
      success: function (xml) {
        //Als er antwoorden zijn gevonden dan deze antwoorden tonen
        if ($(xml).find("antwoorden antwoord").length > 0) {
          //$(".sidebar .wizard .wizard-question").html($(xml).find("vraag").text().trim());
          $(".sidebar .wizard .wizard-question").html($.trim($(xml).find("vraag").text()));
          $(".content .wizard .wizard-intro h3").html($.trim($(xml).find("vraag").text()));
          $(".wizard .wizard-answers").html("");
          $(xml).find("antwoord").each(function () {
            switch ($.trim($(this).find("type").text())) {
              case '1':
                //Vervolgvraag
                $(".wizard .wizard-answers").html($(".wizard .wizard-answers").html() + "<li data-show-next='" + $.trim($(this).find("id").text()) + "'><span onclick=\"" + $.trim($(this).find("ga").text()) + "\">" + $.trim($(this).find("omschrijving").text()) + "</span></li>");
                break;
              case '2':
                //Eindantwoord
                $(".wizard .wizard-answers").html($(".wizard .wizard-answers").html() + "<li><a onclick=\"" + $.trim($(this).find("ga").text()) + "\" rel='iframe" + $(this).index() + "' href='/pages/iframe/wizard.aspx?id=" + $.trim($(this).find("id").text()) + "' data-album-title='Informatie over: " + $.trim($(xml).find("vraag").text()) + "'>" + $.trim($(this).find("omschrijving").text()) + "</a></li>");
                break;
              case '3':
                //Link
                $(".wizard .wizard-answers").html($(".wizard .wizard-answers").html() + "<li><a onclick=\"" + $.trim($(this).find("ga").text()) + "\" href='" + $.trim($(this).find("link").text()) + "' >" + $.trim($(this).find("omschrijving").text()) + "</a></li>");
                break;
              case '4':
                //Formulier
                $(".wizard .wizard-answers").html($(".wizard .wizard-answers").html() + "<li><a onclick=\"" + $.trim($(this).find("ga").text()) + "\" rel='iframe" + $(this).index() + "' href='/pages/iframe/wizard.aspx?id=" + $.trim($(this).find("id").text()) + "' data-album-title='Informatie over: " + $.trim($(xml).find("vraag").text()) + "'>" + $.trim($(this).find("omschrijving").text()) + "</a></li>");
                break;
              default:

            }

          });
        }
        //Als er een link is gevonden dan doorlinken naar een externe pagina
        else if ($(xml).find("link").length > 0) {
          document.location = $(xml).find("link").text();
        }
        var vorigeGA = $.trim($(xml).find("parentga").text());
        if ($(xml).find("parent").length > 0) {
          $(".wizard .wizard-back").replaceWith("<div onclick=\"" + vorigeGA + "\" class='wizard-back' data-show-parent='" + $(xml).find("parent").text() + "'>Vorige</div>");
        }
        else {
          $(".wizard .wizard-back").replaceWith("<div onclick=\"" + vorigeGA + "\" class='wizard-back hidden'>Vorige</div>");
        }
        initZorgWizard();
      }
    });
  }
}

/* ---------------------------------------------------------------------------------- */
/* ----- Functies: Sidebar-video's -------------------------------------------------- */
/* ---------------------------------------------------------------------------------- */

function initVideos() {
  initContentVideos();
}

function initContentVideos() {
  $(".content li.media-video").each(function () {
    $(this).find('.video-container').flash(null, { version: 9 }, function (htmlOptions) {
      var $this = $(this);
      htmlOptions.src = '/interface/flash/kpnplayerup.swf';
      htmlOptions.flashvars.url = $(this).find(".videosource").html();
      htmlOptions.flashvars.image = $(this).find("img").attr("src");
      htmlOptions.flashvars.keepImage = false;
      htmlOptions.flashvars.streamType = 'video';
      htmlOptions.width = 418;
      htmlOptions.height = 313;
      htmlOptions.flashvars.autoplay = 'false';
      htmlOptions.wmode = 'transparent';
      htmlOptions.allowFullscreen = 'true';
      $this.html('');
      $this.addClass('flash-replaced').prepend($.fn.flash.transform(htmlOptions));
    });
  });
}


/* ---------------------------------------------------------------------------------- */
/* ----- Functies: Adressenlijsten -------------------------------------------------- */
/* ---------------------------------------------------------------------------------- */

function initAddressList() {
  $("#main .address-box:not('.active') ul").hide();
  $("#main .address-box h2").click(
    function () {
      if (!$(this).parent().hasClass("active")) { $(this).parent().siblings().removeClass("active").find("ul").slideUp(200); }
      $(this).next("ul").stop(true, true).slideToggle(200);
      $(this).parent().toggleClass("active");
    }
  );
}


/* ---------------------------------------------------------------------------------- */
/* ----- Functies: Lanceringsanimatie ----------------------------------------------- */
/* ---------------------------------------------------------------------------------- */

function initLaunch() {
  //De hoogte goed instellen
    $("#new-website-notification").css("height", $("body").css("height"));
    if ($("#launch-anim-wrapper").length > 0) {
      $("body").css({ "overflow-y": "scroll" });

      var breedte = 142;
      var hoogte = 142;
      var extrahoogte = 0;

      var blok = $(".launch-anim");

      // Blokken plaatsen met juiste positie en achtergrondpositie
      for (x = 0; x <= 6; x++) {
        for (y = 0; y <= 10; y++) {
          extrahoogte = 0;
          if (y >= 1) { extrahoogte = 13; }
          blok.append("<div class=\"x" + x + " y" + y + "\" style=\"background-position:-" + (x * breedte) + "px -" + ((y * hoogte) + extrahoogte) + "px; left: " + (x * breedte) + "px; top: " + ((y * hoogte) + extrahoogte) + "px;" + ((y == 0) ? "height:155px;" : ((y == 10) ? "height:47px;" : "")) + "\"></div>");
        }
      }
      // Blokken laten vallen, vervolgens de melding tonen en weer weghalen.
      setTimeout(function () {
        setInterval(function () { fadeBox(); }, 50);
        setTimeout(function () {
          $("#launch-anim-wrapper").fadeOut(700, function () {
            setTimeout(function () {
              $("#new-website-notification").fadeOut(2000, function () {
                $("#launch-anim-wrapper, #new-website-notification").remove();
              });
            }, 3000);
          });
        }, 5000);
        $("#new-website-notification").addClass("active");
      }, 1500);
    }
}

function fadeBox() {
  $(".launch-anim div:random:eq(0)").css({"z-index": 10}).animate({ "top": "+=200px", "opacity": 0 }, 500, function () { $(this).remove(); });
}

function __doPostBack(eventTarget, eventArgument) {
  var theForm = document.forms['aspnetForm'];
  if (!theForm) {
    theForm = document.aspnetForm;
  }
  if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
    if (theForm.__EVENTTARGET) {
      theForm.__EVENTTARGET.value = eventTarget;
      theForm.__EVENTARGUMENT.value = eventArgument;
    }
    else {
      theForm.EVENTTARGET.value = eventTarget;
      theForm.EVENTARGUMENT.value = eventArgument;
    }
    theForm.submit();
  }
}

function clsMenu() {
  var mouseLeaveTimeout;
  var itemActiveTimeout
  var lastEnterElement;
  var lastActiveElement;
  var blnInstantActive = false;

  this.MouseEnter = function (el) {
    clearTimeout(mouseLeaveTimeout);
    $(lastEnterElement).removeClass("hover");
    lastEnterElement = el;
    $(el).addClass("disabled");
    $(el).addClass("hover");
    if (blnInstantActive) {
      menu.ItemActive(el);
    }
    else {
      itemActiveTimeout = setTimeout(function () { menu.ItemActive(el); }, 350);
    }
  }

  this.ItemActive = function (el) {
    blnInstantActive = true;
    $(el).removeClass("disabled");
    lastActiveElement = el;
    this.showOverlay(el); 
  }

  this.MouseLeave = function (el) {
    mouseLeaveTimeout = setTimeout(function () { $(el).removeClass("hover"); $(el).removeClass("disabled"); blnInstantActive = false; overlay.hide(); }, 250);
    clearTimeout(itemActiveTimeout);
  }

  this.showOverlay = function (el) {
    if ($(el).hasClass("has-subnav")) {
      if ($("body").outerHeight(true) > $(window).height()) { var overlayHeight = $("body").outerHeight(true); }
      else { var overlayHeight = $(window).height(); }
      overlay.height(overlayHeight);
      overlay.show();
    }
    else {
      overlay.hide();
    }
  }
}
