$(document).ready(function () {
	init();

	//temporary wvhj2011 banner
	$.getScript('http://templates.kennisnet.nl/kennisnet/default/js/wvhj2011.js');

});

function init(){
	topMenu();
	featurette();
	carousel();
	slider();
	skipLinks();
	dossierSearch();
	mainSearch();
	dossierExpert();
}

jQuery.fn.dropdown = function() {

   return this.each(function() {

      var $select = $(this);
      var $dropdown = $('<div class="select closed"></div>');
      var $dropdownInput = $('<input type="text" id="'+$select.attr('id')+'" value="" readonly="readonly" />');
      var $dropdownButton = $('<input type="button" value="&hellip;" />');
      var $dropdownOptionsContainer = $('<ul class="options"></ul>');
      var $dropdownOptions = $([]);

      var populateMenu = function() {
         $select.find('option').each(function(i) {
            var $dropdownOption = $('<li class="option_'+$(this).attr('value').replace(/\s+/g, '_')+'"><a href="#">'+$(this).text()+'</a></li>');
            if ($(this).is(':selected')) $dropdownOption.addClass('selected');
            $dropdownOptionsContainer.append($dropdownOption);
            $dropdownOption.find('a')
               .click(function() {
                  selectMenuOption(i);
                  hideMenuOptions();
                  return false;
               })
               .keydown(handleMenuOption)
               .keypress(function() {
                  return false;
               })
               .mousedown(function() {
                  return false;
               });
            $dropdownOptions = $dropdownOptions.add($dropdownOption);
         });
      }

      var showMenuOptions = function() {
         if ($dropdown.hasClass('closed')) setTimeout(function() {
            $dropdown.removeClass('closed');
            $dropdownOptionsContainer.show();
            $dropdown.addClass('opened').find('.selected a').focus();
         }, 10);
      }

      var hideMenuOptions = function() {
         $dropdownOptionsContainer.hide();
         $dropdown.removeClass('opened').addClass('closed');
         $dropdownInput.focus();
      }

      var selectMenuOption = function(i) {
         $select.val($select.find('option').eq(i).val()).trigger('change');
         $dropdownOptions.removeClass('selected').eq(i).addClass('selected');
         $dropdownInput.val($dropdownOptions.eq(i).text());
      }

      var handleMenuInput = function(e) {
         if (e.keyCode == 37 || e.keyCode == 38) {
            $dropdownOptions.filter('.selected').prev().find('a').click();
            return false;
         } else if (e.keyCode == 39 || e.keyCode == 40) {
            $dropdownOptions.filter('.selected').next().find('a').click();
            return false;
         } else {
            var matches = $dropdownOptions.filter(function() { return $(this).text().match(new RegExp('^'+String.fromCharCode(e.keyCode)+'\.*', 'i')); });
            if (matches.length) matches.eq((matches.index($('.selected'))+1) % (matches.length)).find('a').click();
         }
      }

      var handleMenuOption = function(e) {
         if (e.keyCode == 37 || e.keyCode == 38) {
            $(this).parent().prev().find('a').focus().click();
            return false;
         } else if (e.keyCode == 39 || e.keyCode == 40) {
            $(this).parent().next().find('a').focus().click();
            return false;
         } else if (e.keyCode == 13 || e.keyCode == 27) {
            hideMenuOptions(); return false;
         } else {
            var matches = $dropdownOptions.filter(function() { return $(this).text().match(RegExp('^'+String.fromCharCode(e.keyCode)+'\.*', 'i')); });
            if (matches.length) matches.eq((matches.index($('.selected'))+1) % (matches.length)).find('a').focus().click();
         }

      }

      var initMenu = function() {
         populateMenu();
         $select.hide().removeAttr('id').after($dropdown.append($dropdownInput.mousedown(showMenuOptions).keydown(handleMenuInput)).append($dropdownButton.mousedown(showMenuOptions)).append($dropdownOptionsContainer.hide()));
         selectMenuOption(Math.max($dropdownOptions.index($('.selected', $dropdownOptionsContainer)), 0));
         $(document).mousedown(function() { if ($dropdown.hasClass('opened')) hideMenuOptions(); });
      }

      initMenu();

   });

}

jQuery.fn.placeholder = function(options) {

   options = jQuery.extend({
      className: 'placeholder'
   }, options);

   return this.each(function() {

      var $target = $(this);
      var placeholderValue = options.value || $target.attr('placeholder');

      var showPlaceholder = function() {
         if (!$target.val()) $target.addClass(options.className).val(placeholderValue);
      }

      var hidePlaceholder = function() {
         if ($target.val() == placeholderValue) $target.val('').removeClass(options.className);
      }

      if (!$target.val() || $target.val() == placeholderValue) $target.addClass(options.className);
      if ($target.hasClass(options.className)) $target.val(placeholderValue);

      $target.unbind('focus', this.hidePlaceholder).unbind('blur', this.showPlaceholder).focus(hidePlaceholder).blur(showPlaceholder).closest('form').submit(hidePlaceholder);

   });

}

function mainSearch() {
	$('#search_query').val('').placeholder({value: $('#search_domain :selected').text()});
	$('#search_domain').dropdown().change(function() { $('#search_query').placeholder({value: $(this).find(':selected').text()}).focus(); });
}

function topMenu(){
	$('#headerTrigger').removeClass('open').toggle(function(){
		$(this).css('outline','none');
		$('#logo, #contentContainer, #mainMenu, #search, #footer, #headerMenu').animate({'top':'+=20em'},400);
		$('#wrapper').animate({'height':'+=20em'},400);
		$(this).addClass('open');
		return false;
	}, function(){
		$('#logo, #contentContainer, #mainMenu, #search, #footer, #headerMenu').animate({'top':'-=20em'},300);
		$('#wrapper').animate({'height':'-=20em'},400);
		$(this).removeClass('open');
		return false;
	});
}

function featurette(){
	$('#breadcrumbs').append('<span class="breadcrumbLeft"></span><span class="breadcrumbRight"></span>');
	$('#relatedContent h2').append('<span class="h2Left"></span><span class="h2Right"></span>');
	$('#q-and-a img').hover(function(){ $(this).parent().parent().find('h3').css({'background': 'rgba(46,49,146,0.9)'});},function(){ $(this).parent().parent().find('h3').css({'background': 'rgba(46,49,146,0.7)'});});
}

function carousel(){
	if($('#carousel').is('*')){
		var identifier = 1;
		$('#carousel li a').css({'outline': '0'});
		$('#carousel li').each(function(identifier){
			identifier++;
			var image = $(this).find('.img img').attr('src');
			var title = $(this).find('.img').attr('title');
			var href = $(this).find('.img').attr('href');
			$(this).attr("id", 'li' + identifier);
			$(this).parent().parent().append('<a href="'+ href +'" class="largeImg image' + identifier +'"><img src="' + image + '" alt="' + title + '" /></a>\r');
			$(this).parent().parent().append('<a href="'+ href +'" class="imgLink imgLink' + identifier +'">' + title + '</a>\r');
		});
		
		$('.image1').fadeIn(400);
		$('.imgLink1').fadeIn(400);
		$('#carousel #li1 a.trigger').addClass('triggerActive');
		$('#carousel li .img').hover(function(i){ $(this).parent().find('a.trigger').addClass('triggerHover'); }, function(){ $(this).parent().find('a.trigger').removeClass('triggerHover'); });
		$('.largeImg').hover(function(){ $(this).parent().find('.imgLink').addClass('imgLinkHover'); }, function(){ $(this).parent().find('.imgLink').removeClass('imgLinkHover'); });
		
		$('#carousel li a').click(function(){
			$('#carousel li a.trigger').removeClass('triggerActive');
			$('.largeImg').hide();
			$('.imgLink').hide();
			$(this).closest('li').find('a.trigger').addClass('triggerActive');
			var currentId = $(this).parent().attr('id').split('li')[1];
			$('.image' + currentId).fadeIn(200);
			$('.imgLink' + currentId).fadeIn(200);
			return false;
		});
	}
}

function slider(){
	if($('#q-and-a').is('*')){
		$('#q-and-a #dossierContainer').addClass('activated');
		var l = $('#q-and-a ul li').size() * 24 + 'em';
		$('#q-and-a ul').css({'width': l });
		$('#q-and-a #dossierContainer').jScrollPane({
			maintainPosition: false, 
			horizontalDragMinWidth: 89, 
			horizontalDragMaxWidth: 89,
			animateScroll: true
		});
	}
}

function skipLinks(){
	$('.skipLink').focus(function(){ $(this).css({'left': '14em'}); });
	$('.skipLink').blur(function(){ $('.skipLink').css({'left': '-999em'}); });
}

function dossierSearch(){
	if($('#dossierSearch').is('*')){
		$('#dossierSearch form, #dossierSearchInput').attr('autocomplete', 'off');
		var placeholder = 'Zoek in dit dossier';
		$('#dossierSearchInput').val(placeholder).addClass('placeholder').focus(function(){
			if ($(this).val() == placeholder) $(this).val('').removeClass('placeholder');
			if ($(this).val())$('#dossierSearchResults').show();
		}).blur(function(){
			if (!$(this).val()) $(this).val(placeholder).addClass('placeholder');
		}).keyup(function(event){
			if ($(this).val()){
				$('#dossierSearchResults').fadeIn(200);
			 	Dresolr.querySolr();
			} else {
				$('#dossierSearchResults').hide();
			}
		})
		$('#dossierSearch').hover(
			function() { $.data(this, 'hover', true); },
			function() { $.data(this, 'hover', false); }
		);
		$('body').mousedown(function(){
			if (!$('#dossierSearch').data('hover')) $('#dossierSearchResults').hide();
		});
	}
}

function dossierExpert(){
	$('#dossierExpert .form').hide();
	$('#dossierExpert a').click(function(){
		$('#dossierExpert .intro').hide();
		$('#dossierExpert .form').show();
		return false;
	});
}

