/* -----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();
		}
	}
}


/* -----COMMON FUNCTIONS---- */
/* --- open a[rel=external] in new window --- */
function openExternal() {
	$('a[rel=external]').live('click', function () {
		window.open($(this).attr('href'));
		return false;
	});
}

/* --- create clientside solution; change class on body on click --- */
function changeFontsize() {
	$('#textsize a').click(function () {
		$('body').removeClass('smalltext mediumtext largetext').addClass($(this).attr('class') + 'text');
		$.ajax({
			url: "/inc/cfc/textsize.cfc?method=SetTextsize",
			type: "POST",
			data: "textsize=" + $(this).attr('class') + 'text'
		});
		return false;
	});
}


/* -----FANCYFORM------ */
/* --- apply $.fn.fancyform() --- */
function applyFancyForm() {
	var elem = $('#sitesearch_keyword, input.mergelabel, #login_email, #login_password');

	applyFunction(
		elem.length,
		function () {
			return $.fn.fancyform;
		},
		['/inc/javascript/jquery.fancyform.js'],
		function () {
			$('label[for=sitesearch_keyword]').text($('#sitesearch legend').text());
			elem.fancyform('mergeLabel');
		}
	);
}


/* -----CAROUSEL------ */
/* --- apply $.fn.carousel() to #banner --- */
function applyCarousel() {
	var elem = $('#banner');

	applyFunction(
		elem.length,
		function () {
			return $.fn.carousel;
		},
		['/inc/javascript/jquery.timers.js', '/inc/javascript/jquery.carousel.js'],
		function () {
			elem.carousel();
		}
	);
}


/* -----POLL------ */
/* --- hide submit button and submit form on radiobutton change --- */
function submitPoll() {
	var poll = $('#poll form');
	poll.find('input.fsubmit').hide();
	poll.find('input[name=poll_answer]').change(function () {
		poll.submit();
	});
}


/* -----GOOGLE MAPS------ */
/* --- show Google Map and load directions form with AJAX  --- */
function applyGMap() {

	var elem = $('#map'),
		gmap,
		gmap_settings = $('#map_settings');
	
	if (elem.length && !$('#health_search_wrp').length) {
		applyFunction(
			elem.length,
			function () {
				return GMaps !== null;
			},
			['/inc/javascript/gmaps.js'],
			function () {
				// set correct dimensions based on setting
				elem
					.width(parseInt(gmap_settings.find('#map_width').text(), 10))
					.height(parseInt(gmap_settings.find('#map_height').text(), 10));
				$.ajax({
					url: '/inc/ajax/gmap_getdirections.html',
					success: function (data) {
						// append directions form
						elem.after(data);
						// setup GMap
						gmap = new GMaps();
						// gmap.mapType = gmap_settings.find('#map_type').text();
						gmap.zoomlevel = parseInt(gmap_settings.find('#map_zoomlevel').text(), 10);
						gmap.GMapLoad(document.getElementById('map'), document.getElementById('directions'));
						gmap.showAddress('Nederland, Haagse Schouwweg 12, 2332KG, Leiden');
						// submit listener on directions form
						elem.next().submit(function () {
							gmap.setDirections(this.address.value, 'Nederland, Haagse Schouwweg 12, 2332 KG, Leiden', 'nl_NL');
							return false;
						});
					}
				});
			}
		);
	}
}


/* -----5 STAPPENPLAN------ */
/* --- divide steps in seperate 'pages', create header- (index) and footernavigation (prev/next) --- */
function applyStappenplan() {
	var stappenplan = $('#stappenplan'),
		stappenplan_li = stappenplan.find('> li'),
		stappenplan_headernav,
		stappenplan_footernav;

	if (stappenplan_li.length) {

		/* FOOTER navigation */
		// append navigation
		stappenplan.after('<div id="stappenplan_prevnext"><a class="prev" href="/"><span>&laquo;</span> Vorige</a><a class="next" href="/">Volgende <span>&raquo;</span></a></div>');
		stappenplan_footernav = stappenplan.next();
		stappenplan_footernav.find('a.prev').hide();

		/* HEADER navigation */				
		// append navigation
		stappenplan.before('<ol id="step_selector" />');
		stappenplan_headernav = stappenplan.prev();
		
		// fill navigation + hide items except first
		$(stappenplan_li).each(function (i) {
			if (i !== 0) {
				stappenplan_headernav.append('<li><a href="/">' + (i + 1) + '</a></li>');
				stappenplan_li.eq(i).hide();
			} else {
				stappenplan_headernav.append('<li class="act"><a href="/">' + (i + 1) + '</a></li>');
			}
		});
		
		// click listener on header navigation
		stappenplan_headernav.find('a').click(function () {
			var index = $(this).parents('li').index();
			
			stappenplan_headernav.find('li.act').removeClass('act');
			stappenplan_headernav.find('li:eq(' + index + ')').addClass('act');
			stappenplan_li.hide();
			stappenplan_li.eq(index).show();
			
			stappenplan_footernav.find('a').show();
			if (index === 0) {
				stappenplan_footernav.find('a.prev').hide();
			} else if (index === (stappenplan_li.length - 1)) {
				stappenplan_footernav.find('a.next').hide();
			}
			
			return false;
		});
		
		// click listener on footer navigation: trigger click on corresponding header navigation link
		stappenplan_footernav.find('a').click(function () {
			var index = stappenplan_headernav.find('li.act').index();
			
			index = ($(this).attr('class') === 'prev') ? index - 1 : index + 1;
			
			if (index < 0) {
				index = 0;
			} else if (index === stappenplan_li.length) {
				index--;
			}
			
			stappenplan_headernav.find('li:eq(' + index + ') a').click();
			
			return false;
		});

	}
}


/* -----HEALTHCARE COMPARISON------ */
/* --- compare healthcare companies with each other --- */
function compare(id, name) {
	if (!$('#zorgaanbieder' + id).length) {
		if ($('#compare_list li').length > 2) {
			alert("U kunt maximaal 3 zorgaanbieders vergelijken");
			return false;
		}
		$('#compare_message').hide();
		$('#compare_list').append('<li id="zorgaanbieder' + id + '">' + name + '<input type="hidden" name="compare" value="' + id + '" /><a href="#" class="delete">verwijder</a></li>');
	} else {
		alert('Deze zorgaanbieder is al geselecteerd.');
	}
} 

/* --- initialize google map used within healthcare comparison --- */
function healthcareGMap() {
	var map = $('#map_large');
	if (map.length) {
		applyFunction(
			1,
			function () {
				return $.fn.gmap;
			},
			['/inc/javascript/jquery.maps.js'],
			function () {
				map.gmap({
					startLatLng: {
						latitude: '52.200452',
						longitude: '4.534606'
					},
					infowindow: '#message',
					startZoom: 11,
					iconpath: '/inc/img/',
					mapType: "roadmap",
					groups: {
						'default' : 'maps_icon_default.png'
					},
					lang: 'nl'
				});
				
				$('#compare').attr('action', $('#health_compare').attr('action'));
				
				$('#compare_list a.delete').live('click', function () {
					$(this).parent('li').remove();
					$('#compare_message').toggle(!$('#compare_list li').length);
					return false;
				});
	
			}
		);
	}
}

/* --- healthcare comparison: tabbify + initialize google map on 2nd tab --- */
function applyHealthcareCompare() {
	var elem = $('form#health_compare'),
		zorgaanbod = $('#zorgaanbod'),
		html, tab_content, href, map;

	if (elem.length) {
		$('input[name=compare]').live('change', function () {
			if ($('input[name=compare]:checked').length === 3) {
				$('input[name=compare]:not(:checked)').attr('disabled', 'disabled');
			} else {
				$('input[name=compare]:not(:checked)').removeAttr('disabled');
			}
		});
		$.ajax({
			'url': '/inc/ajax/compare_tabbed-content.html',
			'success': function (data) {

				// add tabs + tab_content; move form within 1st tab_content li
				elem.before(data);
				tab_content = $('#tab_content');
				elem.clone().appendTo(tab_content.find('li:eq(0)'));
				elem.remove();
				
				// 2nd tab: google maps
				tab_content.find('li:eq(1)').hide();
				
				// toggle tab content
				$('#tabs a, #tab_content a').click(function () {

					var gmap = $('#map_large');
					if ($(this).parents('li').index() === 1 && !gmap.hasClass('gmap_enabled')) {
						healthcareGMap();
						gmap.addClass('gmap_enabled');
					}

					// activate tab
					$('#tabs li').removeClass('act');
					$(this).parents('li').addClass('act');
					// toggle corresponding 'tab_content li'
					tab_content.find('li').hide();
					tab_content.find('li:eq(' + $(this).parents('li').index() + ')').show();
					return false;

				});
			},
			'error': function (e) {
				debug('ERROR retrieving \'/inc/ajax/compare_tabbed-content.html\'');
			},
			'dataType': 'html'
		});
	} else if (zorgaanbod.length) {
		$.ajax({
			'url': '/inc/ajax/gmap_item-overlay.html',
			'success': function (data) {
				$('body').append(data);
				healthcareGMap();
			},
			'error': function (e) {
				debug('ERROR retrieving \'/inc/ajax/gmap_item-overlay.html\'');
			},
			'dataType': 'html'
		});
	}
}


/* -----FORM VALIDATION------ */
/* --- validate forms within site --- */
function applyValidation() {
	var elem = $('form#newsletter_subscribe, form#frm_login, form#tellafriend, form#contact_with-about, form#question, form#order, form#contact, form#subscribe, form#forgotlogin'),
		invalid_fields = [],
		checklist = [],
		not_empty = [],
		valid_email = [],
		thisform = null,
		returnval = false,
		isPopup,
		postUrl;

	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#newsletter_subscribe');
						valid_email = ['input#newsletter_email'];
						invalid_fields = [];
					
						// 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]);
							}
						});

						invalid_fields = $.fn.validation.returnUniqueArray(invalid_fields, 0);

						break;
					case 'frm_login':

						thisform = $('form#frm_login');
						not_empty = ['input#login_password'];
						valid_email = ['input#login_email'];
						invalid_fields = [];
					
						// 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()) {
								if (thisform.find(not_empty[i]).attr('id') === 'login_password') {
									invalid_fields.unshift('input#login_password_fake');
								} else {
									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]);
							}
						});
						
						invalid_fields = $.fn.validation.returnUniqueArray(invalid_fields, 0);

						break;
					case 'tellafriend':

						thisform = $('form#tellafriend');
						not_empty = ['input#tellafriend_name', 'input#tellafriend_friend_name'];
						valid_email = ['input#tellafriend_email', 'input#tellafriend_friend_email'];
						invalid_fields = [];
					
						// 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]);
							}
						});
						
						invalid_fields = $.fn.validation.returnUniqueArray(invalid_fields, 0);

						break;
					case 'contact_with-about':

						thisform = $('form#contact_with-about');
						not_empty = ['select#contactme_about', 'input#contactme_name'];
						valid_email = ['input#contactme_email'];
						invalid_fields = [];
					
						// 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 if e-mailaddress OR phonenumber is filled
						if (thisform.find('input#contactme_email').val() === '' &&  thisform.find('input#contactme_phone').val() === '') {
							invalid_fields.unshift('input#contactme_email', 'input#contactme_phone');
						}
						
						// check ik valid e-mail
						$.each(valid_email, function (i) {
							if (thisform.find(valid_email[i]).val() !== '') {
								if (!$.fn.validation.validEmail(thisform.find(valid_email[i]).val())) {
									invalid_fields.unshift(valid_email[i]);
								}
							}
						});
						
						invalid_fields = $.fn.validation.returnUniqueArray(invalid_fields, 0);

						break;
					case 'question':

						thisform = $('form#question');
						not_empty = ['select#question_about', 'input#question_name', 'textarea#question_question'];
						valid_email = ['input#question_email'];
						invalid_fields = [];
					
						// 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]);
							}
						});
						
						invalid_fields = $.fn.validation.returnUniqueArray(invalid_fields, 0);

						break;
					case 'order':

						thisform = $('form#order');
						not_empty = ['input#order_name', 'input#order_address', 'input#order_zipcode', 'input#order_city', 'select#order_brochure', 'order_brochure_amount'];
						invalid_fields = [];
					
						// 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]);
							}
						});

						invalid_fields = $.fn.validation.returnUniqueArray(invalid_fields, 0);

						break;
					case 'contact':

						thisform = $('form#contact');
						not_empty = ['input#contact_name', 'textarea#contact_question'];
						valid_email = ['input#contact_email'];
						invalid_fields = [];
					
						// 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]);
							}
						});
						
						invalid_fields = $.fn.validation.returnUniqueArray(invalid_fields, 0);

						break;
					case 'subscribe':

						thisform = $('form#subscribe');
						checklist = [
							{
								'input': thisform.find('input[name=subscribe_gender]'),
								'values': ['M', 'F'],
								'name': 'input[name=subscribe_gender]',
								'title': thisform.parents('dd').prev().text()
							}
						];
						not_empty = ['input#subscribe_bsn', 'input#subscribe_password'];
						valid_email = ['input#subscribe_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]);
							}
						});
						
						invalid_fields = $.fn.validation.returnUniqueArray(invalid_fields, 0);

						break;
					case 'forgotlogin':

						thisform = $('form#forgotlogin');
						valid_email = ['input#ru_email'];
						invalid_fields = [];

						// 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]);
							}
						});
						
						invalid_fields = $.fn.validation.returnUniqueArray(invalid_fields, 0);

						break;
					}
					
					// mark invalid fields OR post form
					if (invalid_fields.length > 0) {
						$.fn.validation.markInvalidFields(thisform, invalid_fields);
						return false;
					} else {
						
						isPopup = thisform.attr('id') === 'question' || thisform.attr('id') === 'tellafriend' || thisform.attr('id') === 'contact_with-about';
						postUrl = thisform.attr('action');
						
						debug(isPopup);
						
						// change post URL in case of a popup form
						if (isPopup) {
							if (thisform.attr('id') === 'question') {
								postUrl = '/index.cfm?act=plugin_forms.askaquestion';						
							} else if (thisform.attr('id') === 'tellafriend') {
								postUrl = '/index.cfm?act=plugin_forms.tellafriend';						
							} else if (thisform.attr('id') === 'contact_with-about') {
								postUrl = '/index.cfm?act=plugin_forms.contactme';						
							}
						}

						$.ajax({
							'type': 'POST',
							'url': postUrl,
							'data': thisform.serialize(),
							'success': function(data) {
								thisform.before(data);
							},
							'dataType': 'html'
						});

						// show message within fancybox ...
						if (isPopup) {
							thisform.hide();
							$('.errormsg').hide();
							return false;
						// ... or post the form
						} else {
							return true;
						}

					}
				}
			);
		}
	);
}


/* -----POPUP------ */
/* --- validate forms within site --- */
function applyPopup() {
	
	var elem = $('#options');
	
	// initialize fancybox
	applyFunction(
		elem.length,
		function () {
			return $.fn.fancybox;
		},
		['/inc/javascript/jquery.mousewheel-3.0.4.pack.js', '/inc/javascript/jquery.easing-1.3.pack.js', '/inc/javascript/jquery.fancybox-1.3.4.pack.js'],
		function () {
			
			pageId = elem.find('a.comment').attr('href').split('/id/');
			pageId = (pageId.length > 1) ? pageId[pageId.length - 1] : pageId;
			
			// reset href attribute of #options
			elem.find('a.help').attr('href', '/index.cfm?act=plugin_forms.askaquestion');										// elem.find('a.help').attr('href', '/view/forms/plugin_forms/dsp_askaquestion.cfm');
			elem.find('a.comment').attr('href', '/index.cfm?act=plugin_forms.tellafriend&id=' + pageId);		// elem.find('a.comment').attr('href', '/view/forms/plugin_forms/dsp_tellafriend.cfm');
			elem.find('a.phone').attr('href', '/index.cfm?act=plugin_forms.contactme');											// elem.find('a.phone').attr('href', '/view/forms/plugin_forms/dsp_contact.cfm');

			// initialize popup
			elem.find('a.help, a.comment, a.phone')
				.fancybox(
					{
						'onComplete' : function() {
							
							/* <legend> can be too long (and cannot be displayed inline); change to <h2> instead */
							var fancyboxLegend = $('#fancybox-content legend');
							fancyboxLegend.hide().after('<h2>' + fancyboxLegend.text() + '</h2>');
							
							// apply validation to newly added form
							applyValidation();						
						}
					}
				);
		}
	);
}


/* -----FAQ------ */
function applyFaq() {
	var elem = $('#faq');
	if (elem.length) {
		elem.find('div.moreinfo').each(function() {
			$(this).addClass('jquery_moreinfo');
			$(this).append('<a class="close" href="#">sluiten</a>');
			$(this).hide();
			$(this).find('a.close').click(function () {				
				$(this).parents('div.moreinfo').hide();
				return false;
			});
		});
		elem.find('> ul > li > a').click(function () {
			$(this).parents('li').find('div.moreinfo').show();
			return false;
		});
	}
}

/* -----LOGIN------ */
/* --- hide login link in meta navigation if #login doesn't exist --- */
function toggleLogin() {
	var metanavLink = $('#metanav a');
	var authorized = !$('#login').length;
	
	if (authorized) {
		metanavLink.each(
			function(i) {
				if ($(this).attr('href') === '/nl/inloggen') {
					$(this).parents('li').hide();
				}
			}
		)
	}
}

/* -----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.1/jquery.min.js', alt: '/inc/javascript/jquery-1.5.1.min.js', test: 'jQuery' })
		.wait(
			function () {
				debug('loaded: jquery-1.5.1.min.js');
			}
		)
		.wait( 
			function () {
				$(document).ready(
					function () {
						callFunction(
							[
								openExternal,
								changeFontsize,
								applyFancyForm,
								applyCarousel,
								submitPoll,
								applyGMap,
								applyStappenplan,
								applyValidation,
								applyHealthcareCompare,
								applyPopup,
								applyFaq,
								toggleLogin
							]
						);
					}
				);
			}
		);
/* --- LAB.js unavailable --- */
} else {
	debug('ERROR: LAB.js unavailable');
}
