// page init
jQuery(function(){

	initNavigation();
	initValidation();


	// Slideshow
	
	jQuery(".slide-nav").tabs("div.slide-box > div", {

		effect: 'fade',
		fadeOutSpeed: "slow",
		rotate: true

	}).slideshow({
	
		autoplay: true,
		autopause: true, 
		interval: 5000
	
	});
	
	
	// Overlay
	
	jQuery("img[rel]").overlay({
	
		mask : {
		color			: '#000',
		loadSpeed		: 200,
		opacity			: 0.5,
		closeOnClick	: true
		},
		top				: 100
	
	});

});

function initValidation() {
	jQuery('#footer .form-box form').each(function(){
		
		var _errormsg = "Forkert e-mail!";

		var _form = jQuery(this);
		var	_errorHolderTarget = jQuery('#newsletter-error-holder');
		var _match = '<!DOCTYPE';
		var _target = _form.attr('action');
		var _errorHolder = jQuery('<p>').hide().prependTo(_errorHolderTarget);

		
		_form.submit(function(){
			
			_errorHolder.hide();
			
			jQuery.ajax({
				type:'POST',
				url:_target,
				data:_form.serialize(),
				success:function(msg){
					if(msg.indexOf(_match)!=-1) window.location = _target;
					else _errorHolder.html(_errormsg).show();

				},
				error:function(){
					alert('AJAX Error!');
				}
			});
			return false;
		});
	});
}


// main navigation init
function initNavigation() {
	var _hoverClass = 'hover';
	var _activeClass = 'active';
	jQuery('#menu').each(function(){
		var _navigation = jQuery(this).find('ul.menu');
		var _items = _navigation.children();
		var _menuOffset = _navigation.offset().left;

		_items.each(function(){
			var _item = jQuery(this);
			var _drop = _item.find('.drop');
			if(_drop.length) {
				_drop.show();
				var _offsetLeft = _item.offset().left - _menuOffset;
				var _itemWidth = _item.outerWidth(true);
				var _dropWidth = 0;
				_drop.children().each(function(){
					_dropWidth+=jQuery(this).outerWidth(true);
				});

				var _offset = _offsetLeft + _itemWidth/2 - _dropWidth/2;

				_drop.removeAttr('style');
				if(_offset > 0) _drop.css('marginLeft',_offset);
			}
		});

		// custom menu behavior
		var _activeIndex = _items.index(_items.filter('.'+_activeClass).eq(0));
		_items.hover(function(){
			jQuery(this).addClass(_hoverClass);
			if(_activeIndex != -1 && jQuery(this).find('.drop').length) _items.eq(_activeIndex).removeClass(_activeClass);
		},function(){
			jQuery(this).removeClass(_hoverClass);
			if(_activeIndex != -1 && jQuery(this).find('.drop').length) _items.eq(_activeIndex).addClass(_activeClass);
		})
	});
}
