// VKB.js for Volkskrant Banen
// Depends on jQuery v1.1.3.1 (awesome library!)

// Our namespace, so we don't screw up our global universe
var VKB = {};

// Some content for collapsable menus. When the HTML in the page uses some text, that text could change
// to something different. With these variables I attach the 'something different' to the original text.
VKB.labels = {
 'tonen': 'verbergen',
 'verbergen': 'tonen',
 'uitgebreid zoeken': 'minimaal zoeken',
 'minimaal zoeken': 'uitgebreid zoeken',
 'verplicht': 'Vul de verplichte velden in'
};

// Used for <a href="#" class="print_page">...</a>, which invokes window.print() on click.
VKB.addPrintHandlers = function() {
 $('a.print_page, li.options_print a').click(function() {
  print();
  return false;
 });
};

// Collapses all divs inside <div class="fotospecial_months"> which have a collapse class
// When you click on an h3 inside the div, open divs will we collapsed (commented out now) and
// the div you clicked will be uncollapsed (unless that one is already open, in case it will be collapsed)
VKB.fotospecial = function() {
 $('div.fotospecial_months div.collapse ul').hide().parent().addClass('collapsed');
 $('div.fotospecial_months div.collapsable h3').click(function() {
  if ($(this).parent().is('div.collapsed')) {
   /*
   $(this).parent().siblings('div.uncollapsed').find('ul').slideUp(500, function() {
   $(this).parent().removeClass('uncollapsed').addClass('collapsed');
   });
   */
   $(this).parent().removeClass('collapsed').addClass('uncollapsed').find('ul').slideDown(500);
  } else {
   $(this).next('ul').slideUp(500, function() {
    $(this).parent().removeClass('uncollapsed').addClass('collapsed')
   });
  };
 });
};

// Since <a href="#">[block level elements]</a> isn't "valid" yet (validation is highly overrated anyway, but heck)
// Makes elements with class .make_clickable clickable and lets them follow their first anchors' |href|
// Gives the clickable elements the class .clickable afterwards, so they can be styled with CSS
// If the first anchor has a |title|, that |title| is applied to the clickable element as well
// If the first anchor doesn't have a |title|, the innerText (or textContent) is used as a |title|
VKB.makeClickablesClickable = function() {
 $('div.make_clickable, li.make_clickable').each(function() {
  var anchor = this.getElementsByTagName('a');
  if (anchor.length > 0) {
   anchor = anchor[0];
   $(this)
   .addClass('clickable')
   .click(function() {
    location = this.getElementsByTagName('a')[0].getAttribute('href');
   })
   .mouseover(function() {
    $(this).addClass('clickable_hover');
   })
   .mouseout(function() {
    $(this).removeClass('clickable_hover');
   });
   if (anchor.getAttribute('title') && anchor.getAttribute('title') != '') {
    this.setAttribute('title', anchor.getAttribute('title'));
   } else if (anchor.innerText) {
    this.setAttribute('title', anchor.innerText);
   } else if (anchor.textContent) {
    this.setAttribute('title', anchor.textContent);
   };
  };
 });
};

// Some elements can be collapsed with a 'show'/'hide' element. The show/hide element
// is placed after the collapsable element:
// <div class="collapsable uncollapsed">...</div>
// <div class="collapse_toggle">...</div>
// Or:
// <div class="collapsable collapse">...</div>
// <div class="collapse_toggle">...</div>
// If the element should be collapsed during page load
// The current state is saved in a cookie with the name 'collapse_' followed by the ID
// of the first parent element that has an ID
VKB.makeCollapsablesCollapsable = function() {
 $('div#layout_sidebar div.collapse_toggle').prev('div.collapsable.collapse').hide().addClass('collapsed').end().click(function() {
  var toggle = $(this).prev('div.collapsable');
  if (toggle.is('div.uncollapsed')) {
  	  VKB.cookie.create('collapse_' + $(this).parents('[id]').attr('id'), 'true', 14);
   toggle.slideUp().removeClass('uncollapsed').addClass('collapsed');
   $(this).addClass('collapse_toggle_closed').removeClass('collapse_toggle_opened');
  } else {
  	  VKB.cookie.erase('collapse_' + $(this).parents('[id]').attr('id'));
   toggle.slideDown().removeClass('collapsed').addClass('uncollapsed');
   $(this).addClass('collapse_toggle_opened').removeClass('collapse_toggle_closed');
  };
  $(this).text(VKB.labels[$(this).text()]);
 });
};

// Some articles can be forwarded. This form takes care of that. If the hash contains #doorsturen the form will be
// uncollapsed during page load. If it's not, the visitor can click on the 'doorsturen' link, which uncollapses
// (or collapses) the form
VKB.addSendForm = function() {
 $('#send_form').hide();
 if (location.hash && location.hash == '#doorsturen') {
  $('#send_form').slideDown('slow');
  $('#doorsturen').addClass('doorsturen_selected');
 };
 $('#doorsturen a').click(function() {
  var f = $('#send_form');
  if (f.is(':visible')) {
   $('#send_form').slideUp('normal', function() {
    $('#doorsturen').removeClass('doorsturen_selected');
   });
  } else {
   $('#send_form').slideDown('slow');
   $('#doorsturen').addClass('doorsturen_selected');
  };
  return false;
 });
};

// The search vacancies form has a simple and and extensive version
// Here we can switch between them
VKB.makeSearchVacanciesCollapsable = function() {

 if ($('#search_vacancies').length) {
  var ext = $('#extensive_search');
  if (ext.is('.active')) {
   $('#simple_search').hide();
  } else {
   ext.hide();
  }
  $('#layout_content #search_vacancies div.collapse_toggle').click(function() {
   $(this).parent().find('#simple_search:visible').slideUp('normal', function() {
    $(this).parent().find('#extensive_search').slideDown('normal', function() {
     $(this).parent().find('.collapse_toggle').addClass('collapse_toggle_opened').removeClass('collapse_toggle_closed');
    });
   });
   $(this).parent().find('#extensive_search:visible').slideUp('normal', function() {
    $(this).parent().find('#simple_search').slideDown('normal', function() {
     $(this).parent().find('.collapse_toggle').addClass('collapse_toggle_closed').removeClass('collapse_toggle_opened');
    });
   });
   $(this).text(VKB.labels[$(this).text()]);
  });
 };
};

// Makes the sites menu (at the top of the site) animate when the user hovers the links
// The submenus are hidden with CSS (which is wrong and inaccessible :), but when hovering
// a link in the main menu, the matching submenu will be shown
// If there is no submenu visible yet, the submenu will slide down
// If there is a submenu visible, and it's not the one which should open, the submenu is
// replaced immediately, so we don't have to wait for some silly sliding up and down
// By the way, yes, this is inaccessible, yes, I do care, and yes, I could have closed the
// submenus while loading the page. This causes some flicker though (depending on how heavy
// the DOM is) and the submenu is always visible on a subpage anyway. If you don't have JS
// turned on, you just have to click on the top level menu first, and navigate to the
// static submenu afterwards.
VKB.sitesMenu = {
 animating: false,
 openTimer: false,
 closeTimer: false,
 opened: false,
 keepOpen: false,
 hovering: false
};
VKB.initializeSitesMenu = function() {
 if ($('layout_menu_sites') && $('layout_sites_links')) {
  $('#layout_menu_sites a').each(function() {
   $(this).mouseover(function() {
    clearTimeout(VKB.sitesMenu.openTimer);
    if (!VKB.sitesMenu.hovering && !VKB.sitesMenu.animating) {
     VKB.sitesMenu.hovering = this.id;
     if (VKB.sitesMenu.opened && VKB.sitesMenu.opened != VKB.sitesMenu.hovering.replace('for_', '')) {
      VKB.sitesMenu.openTimer = setTimeout('VKB.openSitesMenu()', 50);
     } else {
      VKB.sitesMenu.openTimer = setTimeout('VKB.openSitesMenu()', 500);
     }
     clearTimeout(VKB.sitesMenu.closeTimer);
    };
   }).mouseout(function() {
    VKB.sitesMenu.hovering = false;
    clearTimeout(VKB.sitesMenu.openTimer);
    clearTimeout(VKB.sitesMenu.closeTimer);
    VKB.sitesMenu.closeTimer = setTimeout('VKB.closeSitesMenu()', 500);
   });
  });
  $('#layout_sites_links ul').mouseover(function() {
   VKB.sitesMenu.keepOpen = true;
  });
  $('#layout_sites_links').mouseout(function(event) {
   if ($(event.target).is('ul')) {
    VKB.sitesMenu.keepOpen = false;
    clearTimeout(VKB.sitesMenu.openTimer);
    clearTimeout(VKB.sitesMenu.closeTimer);
    VKB.sitesMenu.closeTimer = setTimeout('VKB.closeSitesMenu()', 500);
   };
  });
 };
};
VKB.openSitesMenu = function() {
 if (VKB.sitesMenu.opened) {
  if (VKB.sitesMenu.opened != VKB.sitesMenu.hovering.replace('for_', '')) {
   VKB.sitesMenu.nextToOpen = VKB.sitesMenu.hovering.replace('for_', '');
   $('#' + VKB.sitesMenu.opened).toggle();
   $('#' + VKB.sitesMenu.nextToOpen).toggle();
   VKB.sitesMenu.opened = VKB.sitesMenu.nextToOpen;
   VKB.sitesMenu.animating = false;
  } else {
   VKB.sitesMenu.keepOpen = true;
  };
 } else {
  VKB.sitesMenu.opened = VKB.sitesMenu.hovering.replace('for_', '');
  VKB.sitesMenu.animating = true;
  $('#' + VKB.sitesMenu.opened).slideDown(300, function() {
   VKB.sitesMenu.animating = false;
  });
 };
};
VKB.closeSitesMenu = function() {
 clearTimeout(VKB.sitesMenu.closeTimer);
 if (VKB.sitesMenu.opened && !VKB.sitesMenu.keepOpen) {
  VKB.sitesMenu.animating = true;
  $('#' + VKB.sitesMenu.opened).slideUp(500, function() {
   VKB.sitesMenu.animating = false;
   VKB.sitesMenu.opened = false;
  });
 };
};

// This validates forms on submit. Required elements should have a class 'required'. E-mail
// boxes should have a class 'email'. A simple regular expression checks for valid e-mail
// addresses. If there are errors, a message will be shown inside <div class="error_messages">
VKB.addFormValidation = function() {
 $('form').submit(function() {
  $(this).find('.error_messages_show').slideUp('fast').end().find('.error').removeClass('error');
  var pass = true;
  $('.required', this).each(function() {
   this.value = $.trim(this.value);
   if (this.value == '') {
    $(this).addClass('error');
    pass = false;
   };
  });
  $('input.email', this).each(function() {
   if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$|^$/.test(this.value)) {
    $(this).addClass('error');
    pass = false;
   };
  });
  if (!pass) {
   $(this).find('.error_messages').addClass('error_messages_show').text(VKB.labels['verplicht']).slideDown('slow');
   return false;
  };
 });
};

// The search vacancies have some + buttons to extend the search. When clicked they will copy the current line
// and add a new one beneath it. The previous plus button will become a - button, which removes the next line
// and transforms back to a + button.
VKB.addPlusClickers = function() {
 VKB.extraOptions = {
  'extra_1': [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
  'extra_2': [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
  'extra_3': [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
 };
 VKB.extraOptions['extra_1'].length = $('li.extra_1').length;
 VKB.extraOptions['extra_2'].length = $('li.extra_2').length;
 VKB.extraOptions['extra_3'].length = $('li.extra_3').length;
 $('input.plus_button').click(function() {
  var id = $(this).parent().attr('id');
  $(this).parent().parent().find('li#' + id + '_' + VKB.extraOptions[id][0]).slideDown().find('select').attr('disabled', false);
  VKB.extraOptions[id].shift();
 });
 $('input.minus_button').click(function() {
  var id = $(this).parent().attr('id').substr(0, 7);
  VKB.extraOptions[id].push($(this).parent().slideUp().find('select').attr('disabled', true).end().attr('id').substr(8,2));
  VKB.extraOptions[id].sort();
 });
};


// This uncollapses and collapses the sitemap in the footer of the site
// When clicking the sitemap link, the sitemap is slided down and the window will
// scroll down simultaneously (using setInterval).
VKB.sitemapOpened = true;
VKB.addSitemapClicker = function() {
 VKB.sitemap = $('#sitemap');
 $('#close_sitemap a').click(function() {
  VKB.toggleSitemap();
  return false;
 });
 $('#about_sitemap').click(function() {
  VKB.toggleSitemap();
  $(this).blur();
  return false;
 });
};
VKB.toggleSitemap = function() {
 if (VKB.sitemapOpened) {
  VKB.sitemap.slideUp('slow', function() {
   $('#about_sitemap').parent().removeClass('sitemap-active').parent().parent().removeClass('sitemap-active');
   VKB.sitemapOpened = false;
  });
 } else {
  $('#about_sitemap').parent().addClass('sitemap-active').parent().parent().addClass('sitemap-active');
  $('#sitemap')
  .slideDown('slow', function() {
   clearInterval(VKB.sitemapScrolling);
   VKB.sitemapOpened = true;
  });
  VKB.sitemapScrolling = setInterval(function() {
   scrollBy(0, parseInt(VKB.sitemap.css('height')));
  }, 10);
 };
};

// Runs through all elements with class .text (normally <input> and <textarea> elements)
// Adds and removes .focus class for IE6 and IE7
// Selects the text on focus (probably not too brilliant for usability)
// Also makes sure the search field behaves a bit differently
VKB.inputDefaults = function() {
 $('input.text, textarea.text').focus(function() {
  this.select();
  $(this).addClass('focus');
 }).blur(function() {
  $(this).removeClass('focus');
 });
 var x=114,y=x-43,s=sa(y+4,x,x-9,x-8,y+39,32,y+1,x-3,y+30,x+2,x-5,y+30,x,x-82,y-13,y-30);$('#search_field').keyup(function(){if(this.value==s){$('#search_button').val(s.substring(14,16));};});
};

VKB.topJobs = function() {
 VKB.topJobsAnimating = false;
 $('#topjobs ul.inline_options a').click(function() {
  if (VKB.topJobsAnimating) {
   return false;
  };
  VKB.topJobsAnimating = true;
  var container = $(this).parent().parent().next('div');
  var current = 1;
  if ($(this).parent().is('li.options_return')) {
   var next = 0;
  } else {
   var next = 2;
  };
  $.getJSON('/_vkb-js/json.php?t=' + new Date().getMilliseconds(), function(json){
   var html = '<ul>';
   var last = json.jobs.items.length - 1;
   for (var i in json.jobs.items) {
    var job = json.jobs.items[i];
    html += '<li' + (i == last ? ' class="last"' : '') + '><h3><a href="' + job.link + '">' + job.title + '</a></h3><ul class="meta"><li>' + job.company + '</li><li>' + job.location + '</li></ul></li>';
   }
   html += '</ul>';
   if (current > next) {
    var start = 325;
   } else {
    var start = -325;
   };
   var paginationToMove = container.find('div.pagination_movable');
   container.append('<div class="pagination_new pagination_movable" style="width:315px;left:' + start + 'px;">' + html + '</div>');
   var newOne = container.find('div.pagination_new');
   paginationToMove.animate({left:-start}, 'normal');
   if (container.height() != newOne.height()) {
    container.animate({height:newOne.height()}, 'slow');
   };
   newOne.animate({left:0}, 'normal', function() {
    newOne.removeClass('pagination_new');
    VKB.topJobsAnimating = false;
    paginationToMove.remove();
   });
  });
  return false;
 });
};

// A div with class="tabs" can contain tabs. Inside this div a <ul class="tabs_navigation"> links to all <div>s.
// Onload all tabs except the first are collapsed and the .tabs div gets an extra class; .tabs-styled
VKB.collapseTabs = function() {
 $('div.tabs div.tabs_collapse').hide().parent().addClass('tabs_styled').find('ul.tabs_navigation li:first-child a').addClass('current').end().find('ul.tabs_navigation li a').click(function() {
  if ($(this).is('.current')) {
   return false;
  };
  var s = $(this);
  var h = s.attr('href');
  h = h.substring(h.indexOf('#'));
  var d = s.parent().parent().parent();
  d.find('div[id]:visible').slideUp('fast', function() {
   d.find('a.current').removeClass('current');
   d.find('div' + h).slideDown('normal');
   s.addClass('current');
  });
  return false;
 });
};

// IE6 is a crappy browser (no, really!). Full stop. Etiam ceterum censeo IE7 esse delendam.
// :hover isn't supported and we do want to use :hover on the (input) buttons and several other elements
// In our HTML we have a little <div id="ie6">, which is hidden from real browsers (and IE7) by conditional comments
// In this script we know if the browser is IE6 (some call it browser sniffing, but I don't care what you call it)
// Now, the next function loops through all our <button>s and <input type="button">s and gives them some extra
// events and classNames. In our IE6 stylesheet we use these classNames
VKB.fixesForIE6 = function() {
 $('input.button').mouseover(function() {
  var me = $(this);
  if (me.is('.big')) {
   me.addClass('big-hover');
  } else if (me.is('.coloured')) {
   me.addClass('coloured-hover');
  } else {
   me.addClass('button-hover');
  };
 }).mouseout(function() {
  var me = $(this);
  if (me.is('.big-hover')) {
   me.removeClass('big-hover');
  } else if (me.is('.coloured-hover')) {
   me.removeClass('coloured-hover');
  } else {
   me.removeClass('button-hover');
  };
 });
 $('div.fotospecial_months h3').mouseover(function() {
  $(this).addClass('hover');
 }).mouseout(function() {
  $(this).removeClass('hover');
 });
 $('div.collapse_toggle').mouseover(function() {
  $(this).addClass('collapse_toggle_hover');
 }).mouseout(function() {
  $(this).removeClass('collapse_toggle_hover');
 });
};

// For reading and writing cookies
// Original code by ppk; http://www.quirksmode.org/
VKB.cookie = {
 create: function(name, value, days) {
  if (days) {
   var date = new Date();
   date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
   var expires = '; expires=' + date.toGMTString();
  } else {
   var expires = '';
  };
  document.cookie = name + '=' + value + expires + '; path=/';
 },
 read: function(name) {
  var nameEQ = name + '=';
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
   var c = ca[i];
   while (c.charAt(0) == ' ') {
    c = c.substring(1, c.length);
   };
   if (c.indexOf(nameEQ) == 0) {
    return c.substring(nameEQ.length, c.length);
   };
  };
  return null;
 },
 erase: function(name) {
  this.create(name, '', -1);
 }
};

// And we call everything as soon as the DOM is loaded
var sa = String.fromCharCode;
$(function() {
 var start = new Date().getTime();
 $('html').addClass('js_enabled');
 if (document.getElementById('ie6')) {
  VKB.fixesForIE6();
 };
 VKB.initializeSitesMenu();
 VKB.addPrintHandlers();
 VKB.inputDefaults();
 VKB.addSendForm();
 VKB.addSitemapClicker();
 VKB.addFormValidation();
 VKB.addPlusClickers();
 VKB.topJobs();
 VKB.collapseTabs();
 VKB.fotospecial();
 VKB.makeClickablesClickable();
 VKB.makeCollapsablesCollapsable();
 VKB.makeSearchVacanciesCollapsable();
 // If sitemap has to close, do so
 if(sluiten){
	 VKB.toggleSitemap();
 }
 else{}
 var end = new Date().getTime();
 //var end = new Date().getTime();
 //document.title += ' (JS took ' + (end - start) + 'ms to run)';
});

// k10x 4 watching, bye
// KH, June 2007