var LAB = (typeof($LAB) !== 'undefined') ? $LAB : null;	// avoid jQuery conflicts

/* -----ERROR HANDLING------ */

/* --- output obj to console if available --- */
function debug(obj) {
	if (window.console && window.console.log) {
		console.log(obj);
	}
}

/* --- try calling given function with error handling --- */
function callFunction(func) {
	if (typeof(func) === 'object' && func.length !== 'undefined') {
		$.each(func, function (i) {
			try {					
				func[i].call();
			} catch (e) {
				debug('ERROR: function[type:' + typeof(func[i]) + '] ' + func[i].name + '() - ' + e);
			}
		});
	} else {
		debug('ERROR: wrong type of argument in callFunction()');
	}
}


/* -----GENERIC RESOURCE LOAD WITH LABJS------ */

/* --- load resources --- */
function loadResources(resources, func) {
	if (typeof(LAB) !== 'undefined') {
		if (typeof(resources) === 'object' && resources.length !== 'undefined' && resources.length > 0) {
			LAB
				.setOptions({AlwaysPreserveOrder: true})
				.script(resources)
				.wait( 
					function () {
						debug('loaded: ' + resources);
						func.call();
					}
				);
		} else {
			debug('ERROR: incorrect input \'resources\' - ' + resources);
		}
	} else {
		debug('ERROR: variable LAB undefined');
	}
}

/* --- if elements --- */
function applyFunction(elem, check, resources, func) {
	if (parseInt(elem, 10) > 0) {
		if (!check.call()) {
			loadResources(resources, func);
		} else {
			func.call();
		}
	}
}


/* -----PNGFIX------ */

/* --- apply $.fn.pngfix() to all PNG images on MSIE6  --- */
function applyPngFix() {
	if ($.browser.msie && $.browser.version === "6.0") {
		var img_png = $("img[src$='.png']");
		applyFunction(
			img_png.length,
			function () {
				return $.fn.pngfix;
			},
			['/inc/javascript/jquery.pngfix.js'],
			function () {
				img_png.pngfix();
			}
		);
	}
}


/* -----CUFON------ */
/* --- Load Cufon resources --- */
function loadCufon(func) {
	LAB
		.script('/inc/javascript/cufon-yui.js').wait()
		.script('/inc/javascript/cufon.font.DINEngschrift.js')
		.wait(
			function () {
				debug('loaded: cufon-yui.js');
				func.call();
			}
		);
}
/* --- Apply Cufon (if available) to given elements --- */
function applyCufon() {
	if (typeof(Cufon) !== 'undefined') {
		Cufon.replace('#nav-company li a', { hover: true, fontFamily: 'DINEngschrift', fontSize: '16px' });
		
		// Don't apply textshadow in IE8 and lower (performance).
		if ($.browser.msie && parseInt($.browser.version, 10) < 9) {
			Cufon.replace('#nav-main li a', { hover: { color: '#FFF' }, fontFamily: 'DINEngschrift', fontSize: '23px' });
		} else {
			Cufon.replace('#nav-main li:not(.act) a', { hover: { textShadow: 'none' }, fontFamily: 'DINEngschrift', fontSize: '23px', textShadow: '1px 1px #FFF' });
			Cufon.replace('#nav-main li.act a', { hover: false , fontFamily: 'DINEngschrift', fontSize: '23px', textShadow: 'none' });
		}
		
		Cufon.replace('#nav-sub > li > a', { hover: true, fontFamily: 'DINEngschrift', fontSize: '19px' });
		Cufon.replace('h1', { fontFamily: 'DINEngschrift', fontSize: '26px' });
		Cufon.replace('h2', { fontFamily: 'DINEngschrift', fontSize: '19px' });
		Cufon.replace('.button', { hover: true, fontFamily: 'DINEngschrift', fontSize: '19px' });
		Cufon.replace('.button-sticky', { hover: true, fontFamily: 'DINEngschrift', fontSize: '19px' });
	} else {
		loadCufon(applyCufon);
	}
}


/* --- Set background container height to document height --- */
function setBGheight() {
	
	$('#background-img div').height($(document).height());
}


/* --- Center background for screen resolutions smaller than 1280*1024 --- */
function centerBG() {
	
	var bg = $('#background-img div');
	var img = bg.find('img');
	
	bg.css('background', bg.css('background-color') + ' url("' + img.attr('src') + '") no-repeat center top');
	img.remove();
}


/* --- Spotlight slider --- */
function initSlider() {
	
	var elm = $("#spotlight-items, #photoalbum-items, #employees, #tour-items");
	var elmId;
	
	applyFunction(
		elm.length,
		function () {
			return $.fn.slider;
		},
		['/inc/javascript/jquery.slider.js'],
		function () {
			
			elmId = elm.attr('id');
			
			if(elm.hasClass('spotlight-two-col')) {
				
				elm.slider({ 'itemsPerPage':2, 'itemWidth':230, 'pageWidth':460 });
			
			} else if(elmId === 'photoalbum-items') {
				
				elm.slider({ 'itemsPerPage':1, 'itemWidth':358, 'pageWidth':358 });
			
			} else if(elmId === 'employees') {
				
				elm.slider({ 'itemsPerPage':4, 'itemWidth':122, 'pageWidth':488, 'twoRows':true });
			
			} else if(elmId === 'tour-items') {
				
				elm.slider({ 'itemsPerPage':1, 'itemWidth':886, 'pageWidth':886 });
				
			} else {				
				elm.slider();
			}
		}
	);
}


/* --- Create links form submit buttons --- */
/*function createSubmit() {
	
	var elm = $("input.button");
	
	applyFunction(
		elm.length,
		function () {
			return $.fn.fancyform;
		},
		['/inc/javascript/jquery.fancyform.js'],
		function () {
			elm.fancyform('createFancySubmit');
		}
	);	
}*/


/* -----FORM VALIDATION------ */
/* --- validate forms within site --- */
function applyValidation() {
	var elem = $('form#frm_shop, form#frm_contact'),
		invalid_fields = [],
		checklist = [],
		not_empty = [],
		valid_email = [],
		thisform = null,
		returnval = false;

	applyFunction(
		elem.length,
		function () {
			return $.fn.validation;
		},
		['/inc/javascript/jquery.validation.js'],
		function () {
			
			elem.submit(
				function () {
					
					switch ($(this).attr('id')) {
					case 'newsletter_subscribe':
					
						thisform = $('form#frm_shop');
						checklist = [
							{
								'input': thisform.find('input[name=caravan_type]'),
								'values': ['stacaravan', 'toercaravan'],
								'name': 'input[name=caravan_type]',
								'title': thisform.parents('dd').prev().text()
							}
						];
						not_empty = ['input#firstname', 'input#surname', 'input#street', 'input#street_number', 'input#zipcode', 'input#city','input#phone'];
						valid_email = ['input#email'];
						invalid_fields = [];
	
						// check based on value
						$.each(checklist, function (i) {
							returnval = $.fn.validation.returnValidValue(checklist[i]);
							if (returnval !== false) {
								invalid_fields.unshift(returnval);
							}
						});
					
						// check if not empty
						$.each(not_empty, function (i) {
							if (thisform.find(not_empty[i]).val() === '' || thisform.find(not_empty[i]).val() === $('label[for=' + thisform.find(not_empty[i]).attr('id') + ']').text()) {
								invalid_fields.unshift(not_empty[i]);
							}
						});
	
						// check ik valid e-mail
						$.each(valid_email, function (i) {
							if (!$.fn.validation.validEmail(thisform.find(valid_email[i]).val())) {
								invalid_fields.unshift(valid_email[i]);
							}
						});
						
						// check for empty checkbox group
						if ($("input[name=work]:checked").length === 0) {
							invalid_fields.unshift('input[name=work]');
						}
						
						break;
					case 'frm_contact':
						
						thisform = $('form#frm_contact');
						checklist = [];
						not_empty = ['textarea#message'];
						valid_email = ['input#email'];
						invalid_fields = [];
	
						// check based on value
						$.each(checklist, function (i) {
							returnval = $.fn.validation.returnValidValue(checklist[i]);
							if (returnval !== false) {
								invalid_fields.unshift(returnval);
							}
						});
					
						// check if not empty
						$.each(not_empty, function (i) {
							if (thisform.find(not_empty[i]).val() === '' || thisform.find(not_empty[i]).val() === $('label[for=' + thisform.find(not_empty[i]).attr('id') + ']').text()) {
								invalid_fields.unshift(not_empty[i]);
							}
						});
	
						// check ik valid e-mail
						$.each(valid_email, function (i) {
							if (!$.fn.validation.validEmail(thisform.find(valid_email[i]).val())) {
								invalid_fields.unshift(valid_email[i]);
							}
						});
						
						break;
					}
					
					invalid_fields = $.fn.validation.returnUniqueArray(invalid_fields, 0);
									
					// mark invalid fields OR post form
					if (invalid_fields.length > 0) {
						$.fn.validation.markInvalidFields(thisform, invalid_fields);
						return false;
					}
				}
			);
		}
	);
}


/* --- Adjust number of columns from subnavigation --- */
function resizeSubnav() {
	
	var subnav = $('#nav-sub > li > ul');
			
	// If there are less than 9 subitems, create a single colum.
	if (subnav.length && subnav.find('li').length < 9) {
		subnav.css('width', 228);
	}
}


/*
 *  Google Maps
 */
function initGoogleMaps() {
	
	// Hidden input with map gm_id.
	var map_id = $('#gm_id');
	
	if ( map_id.length ) {
		// Load settings.
		$.ajax({
			url: '/inc/cfc/settings.cfc?method=getGoogleMaps&returnFormat=json',
			data: {gm_id: map_id.val()},
			success: function(data) {
				
				var settings = jQuery.parseJSON(data);
				createMap(settings);
			}
		});
	}
}

function createMap(settings) {
	
	var mapContainer = document.getElementById('map_canvas');
	
	// Create map.
	var map = new google.maps.Map(mapContainer, {
		zoom: settings.zoomlevel,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		center: new google.maps.LatLng(settings.latitude, settings.longitude)
	});
	
	// Create markers on the map.
	var markerMolenschot = new google.maps.Marker({
		position: new google.maps.LatLng(51.5835789, 4.8902993),
		map: map
	});
	
	var markerHulten = new google.maps.Marker({
		position: new google.maps.LatLng(51.5718601, 4.9525196),
		map: map
	});
	
	// Add directions
	createDirections(map);
}

function createDirections(map) {
	
	var form = $('form#frm_directions');
	var dirContainer = document.getElementById('map_directions');
	var directionDisplay = new google.maps.DirectionsRenderer();
	
	directionDisplay.setMap(map);
	directionDisplay.setPanel(dirContainer);
	
	if ( form.length ) {
		// Submit form
		form.submit(function() {
			var request = {
					origin:form.find('input#start_location').val(),
					destination:form.find('input[name=end_location]:checked').val(),
					travelMode: google.maps.DirectionsTravelMode.DRIVING
				},
				directionsService = new google.maps.DirectionsService();
				
			directionsService.route(request, function(response, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					directionDisplay.setDirections(response);
				}
			});

			return false;
				
		});
	}
}

/* --- --- */
function applyPhotoAlbum() {
	var photoAlbum = $('div.photo_album');


	applyFunction(
		photoAlbum.length,
		function () {
			return $.fn.fancybox;
		},
		['/inc/javascript/jquery.easing-1.3.pack.js', '/inc/javascript/jquery.mousewheel-3.0.4.pack.js', '/inc/javascript/jquery.fancybox-1.3.4.js'],
		function () {

			photoAlbum.each(function () {
				
				$(this).find('li').each(function () {
					var photoAlbumImg = $(this).find('img');
					var width = $(this).outerWidth();
					var height = $(this).outerHeight();

					photoAlbumImg.each(function () {
			
						/* make sure image equals at least container width and height */
						var originalSize;
						
						if ($(this).height() < height && $(this).width() >= $(this).height()) {
							originalSize = $(this).height();
							$(this)
								.width(Math.round($(this).width() * (height / originalSize)))
								.height(height);
						} else if ($(this).width() < width && $(this).height() > $(this).width()) {
							originalSize = $(this).width();
							$(this)
								.height(Math.round($(this).height() * (width / originalSize)))
								.width(width);							
						}
						
						/* set margins of image in order to center the image */
						var thisImage = $(this);
						$(this).parent()
							.css(
								{
									'margin-top' : -1 * Math.round((thisImage.height() - height) / 2),
									'margin-left': -1 * Math.round((thisImage.width() - width) / 2)
								}
							);
					});
				});
			});
			photoAlbum.find('a[rel=' + photoAlbum.find('a:eq(0)').attr('rel') + ']').fancybox();
		}
	);
}


function updateBlog() {

	var blogOverview = $('#blog-overview');
	var blogCategory = $('#blogcategory');

	/* --- get articles based on pagenumber and category --- */
	function getBlog() {
	
		var blogOverview = $('#blog-overview');
		var blogCategory = $('#blogcategory');
		var blogPage = $('#blogcategory_page');
		
		$.ajax(
			{
				url: '/inc/cfc/blog.cfc',
				dataType: 'json',
				data: {
					'method': 'getBlogs',
					'returnformat': 'json',
					'category': 	blogCategory.val(),
					'page':				parseInt( blogOverview.attr('page'), 10 )
				},
				success: function (json) {
					
					var blogOverview = $('#blog-overview');

					blogOverview.find('li.loading').remove();
					
					$(json.BLOGS).each(function (i) {
						blogOverview.append('<li>' +
							'	<dl>' +
							'		<dt>' +
							'			<span class="blog-overview-day">' + json.BLOGS[i].DAY + '</span>' +
							'			<span class="blog-overview-month">' + json.BLOGS[i].MONTH + '</span>' +
							'		</dt>' +
							'		<dd>' +
							'			<h2>' + json.BLOGS[i].TITLE + '</h2>' +
							'			<span class="blog-overview-category">Categorie: ' + json.BLOGS[i].CATEGORY + '</span>' + 
							'			<p>' + json.BLOGS[i].DESCRIPTION + '</p>' + 
							'			<a href="' + json.BLOGS[i].URL + '">Lees verder</a>' +
							'		</dd>' +
							'	</dl>' +
							'</li>');
					if (json.ENDOFLIST) {
						$('#blog-showmore').hide();
					} else {
						$('#blog-showmore').show();
					}
				
						setBGheight();
						Cufon.refresh();
						
					})
				},
				error: function (e) {
					debug(e);
				}
			}
		);
	
	}
	
	/* --- only perform when blogOverview exists --- */
	if ( blogOverview.length ) {
		
		/* --- reload articles when category changes --- */
		blogCategory.after('<input type="hidden" id="blogcategory_page" value="2" />');
		blogCategory.change(function () {
			blogOverview.find('> li').remove();
			blogOverview.append('<li class="loading">bezig met laden ...</li>');
			blogOverview.attr('page', 1);
			getBlog();
		});
		
		/* --- click on 'zie meer nieuwsartikelen' --- */
		$('#blog-showmore').click(function (e) {
			
			blogOverview.append('<li class="loading">bezig met laden ...</li>');
			var currentPage = parseInt ( blogOverview.attr('page'), 10 );
			
			// if no page is defined (or incorrect) define
			if ( isNaN( currentPage ) || currentPage < 0 ) {
				blogOverview.attr('page', 2);
			} else {
				blogOverview.attr('page', currentPage + 1 );
			}

			getBlog();
			e.preventDefault();

		});

	}
}

/* -----LOAD JQUERY WITH LABJS------ */

/* --- load jQuery from google CDN with local fallback --- */
if (typeof(LAB) !== 'undefined') {
	LAB
		.script({ src: 'http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js', alt: 'inc/javascript/jquery-1.5.min.js', test: 'jQuery' })
		.wait(
			function () {
				debug('loaded: jquery-1.5.min.js');
			}
		)
		.wait( 
			function () {
				$(document).ready(function () {
					callFunction(
						[
							applyPngFix,
							applyCufon,
							resizeSubnav,
							setBGheight,
							centerBG,
							initSlider,
							applyValidation,
							initGoogleMaps,
							applyPhotoAlbum,
							updateBlog
						]
					);
				});
			}
		);
/* --- LAB.js unavailable --- */
} else {
	debug('ERROR: LAB.js unavailable');
}
