/* Author: Dave O'Brien
*/

(function ($) {
	
	$.helperInitOverlay = $.fn.helperInitOverlay = function (opts) {
				
		var defaults = {
			overlayID: '#overlay',
			maskID: '#expose-mask',
			maskColor: 'transparent',
			speed: 'fast'
		};

		var options = $.extend(defaults, opts);

		apiOverlay = $(options.overlayID).overlay({
			mask: {color: options.maskColor, maskId: options.maskID},
			speed: options.speed
		}).data("overlay");
		
		return apiOverlay;
	};

	$.helperInitTooltips = $.fn.helperInitTooltips = function (opts) {
				
	  var defaults = {
			selectors: 'a[title]',
			position: 'center right',
			offset: [10, 10],
			effect: 'slide',
			opacity: 0.9,
			apiVar: 'default'
	  };

	  var options = $.extend(defaults, opts);

		if (typeof apiTooltips === 'undefined') {
			apiTooltips = {};}

		apiTooltips = $(options.selectors).tooltip({
			position: options.position,
			offset: options.offset,
		  effect: options.effect,
			opacity: options.opacity		
		}).data('tooltip');
		
//		return apiTooltips[options.apiVar];
	};
	
	$.helperInitFormValidation = $.fn.helperInitFormValidation = function (opts) {
				
	  var defaults = {
			selectors: '.form-validate',
			errorMessageDiv: '.error-message',
			effect: 'errorsBelow',
			inputEvent: 'blur',
			apiVar: 'default'
	  };

	  var options = $.extend(defaults, opts);

		// Add novalidate attribute to forms
		$(options.selectors).attr('novalidate', 'novalidate');

		if (typeof apiValidator === 'undefined') {
			apiValidator = {};}
		
		// adds an effect called "errorsBelow" to the validator
		$.tools.validator.addEffect("errorsBelow", function(errors, event) {

			// "show" function
			$.each(errors, function(index, error) {

				var input = error.input,
						errors = error.messages,
						errorDisplayed = false;
						
				if (event.originalEvent.type === 'submit') {
					$('#go-to-form-top').click();
					input.closest('form').find('.error-message').slideDown('fast');
				}

				// Set class on input
				input.addClass('invalid');
				// Check if .message div exists, if not, create it
				if (!input.next('.error-message-below').length) {					
					input.after('<ul class="error-message-below" />');
					if ($(input).is('input[type="text"], input[type="email"], textarea')) {input.next('.error-message-below').hide().width(input.outerWidth());}
					errorDisplayed = true;
				} else {input.next('.error-message-below').empty();}
				// Add messages to the .message div
				$.each(errors, function(index, error) {input.next('.error-message-below').append('<li>'+error+'</li>');});
				if (errorDisplayed) {input.next('.error-message-below').slideDown('fast');}
			});
		}, function(inputs)  {
			
			// "show" function
			$.each(inputs, function(index, input) {

				$(input).removeClass('invalid');
				$(input).next().slideUp('fast', function() {$(this).remove();});
				
			});
		});
		
		// Init validation
		apiValidator[options.apiVar] = $(options.selectors).validator({
			effect: options.effect,
			inputEvent: options.inputEvent
		}).data('validator');
		
		$('.reset').click(function(e) {
			$(this).closest('form').find('label.over-applied').css('text-indent', '0px');
			$('#go-to-form-top').click();
			var form = $(this).closest('form');
			$(':input', form)
			 .not(':button, :submit, :reset, :hidden')
			 .val('')
			 .removeAttr('checked')
			 .removeAttr('selected');
			form.find('.error-message-below').slideUp('fast', function() {
				form.find(':input.invalid').removeClass('invalid');
				$(this).remove();
			});
			form.find('.error-message').slideUp('fast');
		});

		return apiValidator[options.apiVar];
	};

}(jQuery));


$(document).ready(function() {

	// Dropdown navigation
	$("#navigation").removeClass("css-dropdown"); // This removes the CSS 'falback' for dropdown navigation

	$("#navigation li").has("ul").hoverIntent({
		over: function(){
			$(this).addClass("hovered").children("ul").slideDown({
			    duration: 500, 
			    easing: 'easeOutQuint'
			});
		},
		timeout: 750,
		out: function() {
			$(this).removeClass("hovered").children("ul").stop(true, true).fadeOut('fast', function() {
				$(this).css("display", "none");
			});
		}
	});
	
	// Label over init
	$('#search-inline label, #vacancy-search label, #block-search-results label, #contact-form label, #block-form-cv label.lo-init, #search-inline-404 label').labelOver('over-applied');	
	
	// jQuery Tools Helper init
	$.helperInitOverlay();
	
	$.helperInitTooltips({
		selectors: 'a[title], .telephone-numbers li[title]',
		apiVar: 'links'
	});
	
	$.helperInitTooltips({
		selectors: 'input[title], textarea[title]',
		apiVar: 'inputs',
		position: 'top right',
		offset: [38, 10]
	});
	
	$.helperInitFormValidation();
	
	// jQuery Tools init
	$(".block-accordion-simple .accordion").tabs(".accordion-pane", {
		tabs: 'h3',
		effect: 'slide'
	});
	
	$(".block-accordion-simple .accordion-nested").tabs(".accordion-pane-nested", {
		tabs: 'h4',
		effect: 'slide'
	});
	// jQuery Tools init
	$(".block-accordion-small .accordion").tabs(".accordion-pane", {
		tabs: 'h4',
		effect: 'slide'
	});
	
	// Contact map
	//  - generate tooltips, copy to under each link
	$('#block-map .vcard').each(function(i, vcard) {
		var title = $(vcard).parent().prev();
		var id = $(vcard).parent().prev().attr('id');
		var matchingTrigger = $('#block-map .map a[href=#' + id + ']');

		if (matchingTrigger.length) {
			var tooltip = $(vcard).clone().insertAfter(matchingTrigger).removeClass('vcard').addClass('tooltip').addClass('tooltip-offices');
			var text = title.text();
			tooltip.prepend("<h6>" + text + "</h6>");
		}
	});
	
	// Init map tooltips
	$('#block-map .map a').tooltip({
		position: 'center left',
		offset: [0, -10],
	  effect: 'slide',
		opacity: 0.9,
		relative: true		
	}).data('tooltip');
	
	// Map - Open up the correct tab when buttons are clicked on
	if ($('#block-map .accordion').length) {
		var mapAccordionAPI = $('#block-map .accordion').data('tabs');
		var tabs = mapAccordionAPI.getTabs();

		$('.map a').click(function(e) {
			var link = this;

			tabs.each(function(i, tab) {

				if ($(tab).attr('id') === link.hash.substring(1)) {
					var index = $(tab).index('.accordion h4');

					$(link).parent().addClass('active');
					mapAccordionAPI.click(index);
				}
			});
		});
	}
	
	// Help - Open up the correct tab when menu is clicked on
	if ($('#block-help-accordian .accordion').length) {
		blockHelpTabsAPI = $('#block-help-accordian .accordion').data('tabs');

		$('#block-help-links li:first').addClass('active');

		blockHelpTabsAPI.onClick(function(e){
			var $currentTab = blockHelpTabsAPI.getCurrentTab();

			$('#block-help-links li').removeClass('active');
			$('#block-help-links li a[href=#' + $currentTab.attr('id') + ']').parent().addClass('active');

		});

		$('#block-help-links li a').click(function(e) {

			$('#block-help-links li').removeClass('active');
			var tabs = blockHelpTabsAPI.getTabs();
			var link = this;

			tabs.each(function(i, tab) {

				if ($(tab).attr('id') === link.hash.substring(1)) {
					var index = $(tab).index('.accordion h3');
					$(link).parent().addClass('active');
					blockHelpTabsAPI.click(index);
				}
			});
		});
	}
	
	$('.vcard-highlight').click(function(event) {
		if ($(this).hasClass('active')) {$(this).removeClass('active');} else {
			$(this).siblings().removeClass('active');
			$(this).addClass('active');				
		};
	});
	
	
	// Enable whole row to be clicked
	$('.table-clickable tr').not('.no-click').click(function(e) {	
		if ($(this).find('a')) {
			window.location = $(this).find('a').attr('href');
		}
	});
	
	if ($('.block-message-remove').length) {$('.block-message-remove').delay(4000).slideUp('fast');};

	// HomeHori Accordion
	if ($('#block-horizontal-accordion').length) {

		var lastBlock = $("#acc-ghx");
		var maxWidth = 600;
		var minWidth = 170;

		$("#block-horizontal-accordion ul li").hoverIntent({
			over: function(){
				if ($(lastBlock).id === undefined) {
					lastBlockID = $(lastBlock).attr('id');
				}

				if (this.id !== $(lastBlock).attr('id')) {
					$(lastBlock).find('img.back, img.front, .text').fadeOut( { queue:false, duration:200, easing: 'easeInQuint' });
					$(lastBlock).find('.shop-link').animate({paddingLeft:"15"+"px"}, { queue:false, duration:400 });
					$(lastBlock).animate({width: minWidth}, { queue:false, duration:400 });

					$(this).animate({width: maxWidth}, { queue:false, duration:400, complete: function (e) {$(lastBlock).find('.shop-link').animate({paddingLeft:"360"+"px"}, { queue:false, duration:400, easing: 'easeInQuint', complete: function (e) {
							$(lastBlock).find('.back, img.front, .text').fadeIn( { queue:false, duration:400, easing: 'easeInQuint' });	
						}
					});
					}});
					lastBlock = this;
				} else {
					$(lastBlock).find('.back, img.front, .text').fadeIn( { queue:false, duration:400, easing: 'easeInQuint' });	
				}
			},
			timeout: 250,
			out: function(){}});
	}

	
	$(".block-tabs-simple .tabs").tabs(".tab-pane", {
		circular: true,
		current: 'active',
		effect: 'fade',
		fadeInSpeed: 'fast'
	});
	
	$(".block-tabs-help .tabs, .block-tabs-jobs .tabs").tabs(".tab-pane", {
		circular: true,
		current: 'active',
		effect: 'fade',
		fadeInSpeed: 'fast'
	});
	
	$(".block-tabs-slideshow-large .tabs").tabs(".tab-panes > .tab-pane", {
		effect: 'fade',
		rotate: true,
		current: 'active'
	}).slideshow({
		autoplay: true,
		interval: 5000,
		clickable: false,
		prev: '.prev',
		next: '.next'
	});
	
	// Local Scroll init	
  $.localScroll(); 

});
