/**
 *	Javascripts for the Link site.
 *	The scripts below should be included in each page.
 *
 *	@author		Koos van Egmond <koos@7u.nl>
 *	@depends	jQuery
 *	@date		2011-02-02
 */

 
/*********************************************************************
 * FUNCTION TO FIX A MIN-HEIGHT FOR .BGREPEAT
 ********************************************************************/
 
// Set min height for bg repeat (in pixels)
var bgRepeatMinHeight = 270;
 
// Start functioning when DOM is ready
$(function() {

	// Fix height in less than half a second
	setTimeout(function() {
		fixBgRepeat();
	}, 350);
});

/**
 * Function to fix the height of .bgrepeat
 */
function fixBgRepeat() {

	// Get the current height of bgrepeat
	var bgRepeatHeight = $('.bgrepeat').height();
	
	// Fig the height if below the minheight
	if (bgRepeatHeight < bgRepeatMinHeight) $('.bgrepeat').height(bgRepeatMinHeight);
}


/*********************************************************************
 * 'BEDRIJFSLEDEN' BOX ON HOME
 ********************************************************************/
 
// Set ease animation, animation speed and timeoutHandler
var	bedrijfslidAnimation = 'easeOutQuint',
	bedrijfslidAniSpeed = 400,
	bedrijfslidTimeoutHandler,
	bedrijfslidFirstSlide;
 
// Start functioning when DOM is ready
$(function() {

	// Bind previous and next buttons
	$('#bedrijfslid .btn_left, #bedrijfslid .btn_right').click(function() {
	
		// Get the direction
		var dir = ($(this).hasClass('btn_left')) ? 'l' : 'r';
		
		// Slide the image
		slideBedrijfslid(dir, true);
		return false;
	});
	
	// Start the slide show
	startBedrijfslidSlideshow(3000);
});

/**
 * Start slideshow with the logo's
 * @param	Int		Interval	Interval in miliseconds
 */
function startBedrijfslidSlideshow(interval) {

	// Set default interval
	if (typeof interval == 'undefined') interval = 3000;
	
	// Set timeout to slide to the next image
	bedrijfslidTimeoutHandler = setTimeout(function() {
	
		// Slide to the next image
		slideBedrijfslid('r');
		
		// Set timeout for the next slide
		startBedrijfslidSlideshow(3000);
	}, interval);
}

/**
 * Slide left or right in logo
 * @param	String	dir				Direction in which to slide to
 * @param	Bool	pauseSlideShow	Pause slideShow or not
 */
function slideBedrijfslid(dir, pauseSlideShow) {

	// Pause the slideshow if requested
	if (pauseSlideShow) {
	
		// Clear the timeout of the slideshow
		clearTimeout(bedrijfslidTimeoutHandler);
	}
	
	// Set correct direction if not set
	if (typeof dir == 'undefined') dir = 'r';
	
	// Get the width of a slide if not set yet
	if (typeof bedrijfslidWidthSize == 'undefined') {
		bedrijfslidWidthSize = $('#bedrijfslid .logo li:first img').width();
	}
	
	// Set the offset
	var offsetLeft = 0 - bedrijfslidWidthSize;
	
	// Increment or decrement index by direction
	if (dir == 'l') {
		
		// Set the last slide as first and set slide offset
		// to the second
		$('#bedrijfslid .logo li:last').prependTo($('#bedrijfslid .logo'));
		$('#bedrijfslid .logo').css({left:offsetLeft});
		
		// Animate to the requested slide
		$('#bedrijfslid .logo')
			.stop()
			.animate({left:0}, bedrijfslidAniSpeed, bedrijfslidAnimation);
	} else {
		
		// Check if a first item needs to be removed if the 
		// user clicks too fast.
		if ($('#bedrijfslid .logo').queue() && bedrijfslidFirstSlide) {
		
			// Place first item at the end of the slide
			bedrijfslidFirstSlide.remove();
			$('#bedrijfslid .logo').css({left:0});
		}
		
		// Get the first slide
		bedrijfslidFirstSlide = $('#bedrijfslid .logo li:first');
		
		// Set clone of first slide at the end
		bedrijfslidFirstSlide
			.clone()
			.appendTo($('#bedrijfslid .logo'));
		
		// Animate to the requested slide		
		$('#bedrijfslid .logo')
			.stop()
			.animate({left:offsetLeft}, bedrijfslidAniSpeed, bedrijfslidAnimation, function() {
			
				// Place first item at the end of the slide
				bedrijfslidFirstSlide.remove();
				$('#bedrijfslid .logo').css({left:0});
				
				// Unset the firstSlide
				bedrijfslidFirstSlide = false;
			});
	}
	
	// Start slideshow again in 4 seconds
	if (pauseSlideShow) startBedrijfslidSlideshow(4000);
}


/*********************************************************************
 * HOVER AND CLICK FUNCTIONALITY FOR LISTS (.jList)
 ********************************************************************/

// Start functioning when DOM is ready
$(function() {

	// Loop through all available list items
	$('.jList li').each(function() {
	
		// Set shortcut to current jquery object
		// !!!! Don't end with semicolon (;) until end of function !!!!
		$(this)
			// ..Set cursor style
			.css('cursor', 'pointer')
			
			// ..Set click functionality
			.click(function() {
			
				// Get the link to go to
				var url = $('a', this).attr('href');
				
				// Go to the link if isset
				if (url) window.location.href = url;
				return false;
			})
		
			// ..Set hover functionality
			.hover(
				function() {
				
					// Add hovered state
					$(this).addClass('hovered');
				},
				function() {
					
					// Remove hovered state
					$(this).removeClass('hovered');
				}
			);
		});
});


/*********************************************************************
 * FUNCTIONS AND STUFF FOR OVERVIEWS WITH PAGINATION
 ********************************************************************/

// Set property for pagecount, active page
var	overviewPageCount = 1,
	overviewActivePage = 1;
 
// Start functioning when DOM is ready
$(function() {

	// Count the number of pages
	overviewPageCount = $('.newsoverview').length;
	
	// Build the pagination if there is more than one page
	if (overviewPageCount > 1) {
	
		// Generate HTML for the pagination
		buildPages();
	
		// Get the active page by an item that is flagged
		// as selected, and open it
		var pageWithSelectedItem = $('.newsoverview li.selected').parent();
		overviewActivePage = $('.newsoverview').index(pageWithSelectedItem) + 1;
		
		// Open the correct page and check the buttons
		openPage();
		checkButtons();
		
		// Set functionalities for the prev and next buttons
		$('.btn_prev, .btn_next').click(function() {
		
			// Increment or decrement page number
			if ($(this).hasClass('btn_prev')) {
				var pageno = overviewActivePage - 1;
			} else {
				var pageno = overviewActivePage + 1;
			}
			
			// Open the page and check the buttons
			openPage(pageno);
			checkButtons();
			
			return false;
		});
		
		// Set function to open correct page on page click
		$('.btn_pageno').click(function() {
			
			// Get the page number that is clicked
			var pageno = parseInt($(this).text());
			
			// Open the correct page and check the buttons
			openPage(pageno);
			checkButtons();
			
			return false;
		});
	}
});

/**
 * Function to generate the HTML for the
 * page navigation
 */
function buildPages() {

	// Add the remaining pages
	for (var i=2; i <= overviewPageCount; i++) {
		
		// Build HTML to add and add it
		var pageHtml = $('<li><a href="javascript:void(0);" title="Pagina '+i+'" class="btn_pageno">'+i+'</a></li>');
		$('.pagination li:last').before(pageHtml);
	}
	
	// Eventually, show the pagination
	$('.pagination').show();
}

/**
 * Function to open a page by its number
 * @param	Int		no		The pagenumber to open
 */
function openPage(pageno) {

	// Set correct page number
	if (typeof pageno == 'undefined' || pageno < 1 || pageno > overviewPageCount) {
		pageno = overviewActivePage;
	}
	
	// Set index by the hand of the pageno
	var pageIndex = pageno - 1;
	
	// Close all pages first
	$('.newsoverview').hide();
	
	// Open the correct page
	$('.newsoverview:eq('+pageIndex+')').fadeIn(250);
	
	// Set correct page number active in the pagination
	$('.pagination .selected').removeClass('selected');
	$('.pagination .btn_pageno[title="Pagina '+pageno+'"]').addClass('selected');
	
	// Set new active page
	overviewActivePage = pageno;
}

/**
 * Function to check if the left or right button needs
 * to be hidden because of reaching the beginning/end
 * of pagination
 */
function checkButtons() {

	// Show both buttons first
	$('.pagination li:first, .pagination li:last').show();
	
	// Hide the prev button if the beginning is reached
	if (overviewActivePage == 1) {
		$('.pagination .btn_prev').parent().hide();
	}

	// Hide the next button if reached the end
	if (overviewActivePage == overviewPageCount) {
		$('.pagination .btn_next').parent().hide();
	}
}


/*********************************************************************
 * COLORBOX RELATED STUFF
 ********************************************************************/

// Only proceed if colorbox has been defined
if (typeof jQuery.fn.colorbox != 'undefined') {

	// Set the options for colorbox
	var colorboxOptions = {};
	
	// Start function when DOM is ready
	$(function() {
		
		// Bind colorbox to anchors where their rel attribute
		// starts with the value 'colorbox'.
		$('a[rel^="colorbox"]').colorbox(colorboxOptions);
	});

}


/*********************************************************************
 * UNIFORM RELATED STUFF
 ********************************************************************/

// Only proceed if uniform has been defined
if (typeof jQuery.fn.uniform != 'undefined') {

	// Start functioning when DOM is ready
	$(function() {

		$("select, input:checkbox, input:radio, input:file").uniform();
	});
}


/*********************************************************************
 * FUNCTIONS AND METHODS FOR THE FORM
 ********************************************************************/

// Set error message placeholder
var formErrorMessage;

// Start functioning when DOM is ready
$(function() {

	// Bind formcheck plugin if defined
	if (typeof jQuery.fn.formcheck != 'undefined') {
	
		$('form').formcheck({
			beforeCheck: function() {
				
				// Empty the error message first
				formErrorMessage = '';
				
				// Show the preloader
				$('.btn_verzenden').hide();
				$('#formPreloader').show();
			},
			onError: function() {
			
				// Show the send button again
				$('#formPreloader').hide();
				$('.btn_verzenden').show();
				
				// Set error message and alert
				formErrorMessage = 'De volgende velden zijn onjuist ingevoerd:\n\n' + formErrorMessage;
				alert(formErrorMessage);
			},
			onFieldError: function(fieldElem) {
			
				// Get the name of the current field and add
				// it to the error message
				var fieldName = fieldElem.attr('name');
				formErrorMessage += '- ' + fieldName + '\n';
			},
			onSuccess: function() {
				
				// Get URL to post to
				var url = $('form').attr('action');
				
				// Get the form's field values
				var data = $('form').serialize();
				
				// Send AJAX request with post data
				$.ajax({
					type: 'POST',
					url: url,
					data: data,
					success: function(html) {
					
						// Clear content, set new one and fade in
						$('.content')
							.hide()
							.empty()
							.append(html)
							.fadeIn(350, function() {
								
								// Fix the height of .bgrepeat
								fixBgRepeat();
							});
					}
				});
				
				return false;
			}
		});
	}

	// Set submit button
	$('.btn_verzenden').click(function() {
	
		// Submit the form
		$('form').submit();
		return false;
	});
});
