// Global variables (sorry)
var oMembersNav;

window.addEvent('domready', function() {
	// Disable the navigational action for any anchor elements without href values
	$$('a[href$=#]').addEvent('click', fNoAnchor);

	// Make sure any anchor elements meant for navigating "back", send the user to the previous page
	$$('a.backLink').addEvent('click', fGoBack);

	// If the user is not logged in yet, make sure default behaviour of the userbox login link
	// is ignored and instead, a miniature login form is displayed in the box after clicking
	if ($$('#userbox a.login')[0]) {
		$$('#userbox a.login').addEvent('click', fDisplayLoginForm);
	}

	// In event of browsers which don't support CSS3 (IE), use JavaScript to achieve the functionalities
	if (Browser.Engine.trident) {
		/*$$('ul#mainnav li:last-child').setStyle('background-image', 'none');
		$$('ul#mainnav li:last-child a').setStyle('border-right', '0 none');*/

		// Specifically for IE6
		if (Browser.Engine.version == 4) {
			// Fix any <img> or .png_bg background-images in IE6
			DD_belatedPNG.fix('img, .png_bg');

			// Add a hover effect to the LI elements of the "Online network" SlideItMoo instance
			if ($('membersnav')) {
				$$('#membersnav li').addEvent('mouseover', function() { this.addClass('active'); });
				$$('#membersnav li').addEvent('mouseout', function() { this.removeClass('active'); });
			}
		}
	}

	// Presentation of the topbar search form
	if ($('txtSearchTop')) {
		$('txtSearchTop').set({
			'alt': '&laquo; Zoeken &raquo;', 
			'styles': {
				'padding': '1px 8px 0', 
				'background-image': 'none', 
				'border': '1px solid #707070'
			}, 
			'events': {
				'blur': function() { this.setStyle('background-image', 'none'); }
			}
		});
		var lblSearch = new OverText($('txtSearchTop')); lblSearch.reposition(); OverText.update();
	}

	// Toggline of the newsletters signup form
	if ($$('#social div.newsletter')[0]) {
		var oNewsletterSlide = new Fx.Slide('mailchimpSubscribe', {
			duration: 500, 
			mode: 'vertical', 
			onComplete: function() {
				if (this.wrapper.getStyle('height') != '0px') {
					this.wrapper.setStyle('height', 'auto');
				}
			}
		}).hide();
		$('mailchimpSubscribe').removeClass('hide');

		$$('#social div.newsletter h4')[0].addEvent('click', function() { oNewsletterSlide.toggle(); });
	}

	/********** Actions to take when the social sharing bar is on the page **********/
		if ($('socialTools')) {
			if ($('Form_sendFriend')) {
				// Manually set alt attributes for input fields as SilverStripe doesn't support this
				$('Form_sendFriend_NameRecipient').set('alt', 'naam ontvanger');
				$('Form_sendFriend_EmailRecipient').set('alt', 'e-mail ontvanger');
				$('Form_sendFriend_NameSender').set('alt', 'naam verstuurder');
				$('Form_sendFriend_EmailSender').set('alt', 'e-mail verstuurder');

				// Create the OverText labels for the "Send-a-friend" e-mail form
				var lblNameReceiver = new OverText($('Form_sendFriend_NameRecipient')); lblNameReceiver.reposition();
				var lblEmailReceiver = new OverText($('Form_sendFriend_EmailRecipient')); lblEmailReceiver.reposition();
				var lblNameSender = new OverText($('Form_sendFriend_NameSender')); lblNameSender.reposition();
				var lblEmailSender = new OverText($('Form_sendFriend_EmailSender')); lblEmailSender.reposition();

				// Enable revealing and disappearing of the form by clicking an anchor element
				$('toggleSendFriend').addEvent('click', fToggleSendForm);

				// Attach an event to validate the form before letting it submit
				$('Form_sendFriend').addEvent('submit', fCheckSendForm);
			} else {
				// If the form is not present on the page, change the link's HREF to reload the page
				// and use MooTools Tips to inform the user why the link action has changed
				$('toggleSendFriend').addClass('lpbTips');
				$('toggleSendFriend').set('title', '<strong>herlaad de pagina</strong><br />om deze pagina nogmaals door te sturen moet u eerst de pagina herladen');
				$('toggleSendFriend').addEvent('click', function() { document.location.reload(); });
			}

			// Bring up the print dialog box when the user clicks the print button
			$('printBut').addEvent('click', function() { window.print(); });
		}
	/********************************************************************************/

	// Submission of the user registration form
	if ($('Form_registerForm')) {
		$('Form_registerForm').addEvent('submit', fCheckSendForm);
	}

	// Submission of the newsletter signup form
	if ($('mailchimpSubscribe')) {
		$('mailchimpSubscribe').addEvent('submit', fCheckSendForm);
	}

	// Add a MooTools Tips instance to any elements containing the corresponding class
	var bTipHovered = false;
	var oTips = new Tips('.lpbTips', {
		text: '', 
		fixed: true, 
		offset: {
			'x': 24, 
			'y': 24
		}, 
		onShow: function(oTip, oElem) {
			oTip.fade('in');

			oTip.addEvent('mouseenter', function() { bTipHovered = true; });

			oTip.addEvent('mouseleave', function() {
				bTipHovered = false;
				oTip.fade('out'); 
			});
		}, 
		onHide: function(oTip, oElem) {
			if (bTipHovered) {
				oTip.show();
			} else {
				oTip.fade('out');
			}
		}
	});

	/********** Online network page (geographically) ********************************/
		if ($('membersnav')) {
			// The number of slides are the total items divided by number of items per slide (rounded upwards)
			var iNumSlides = Math.ceil(parseFloat($$('#membersnav li').length / 10));

			oMembersNav = new noobSlide({
				box: $('membersnav'), 
				items: $$('#membersnav li'), 
				mode: 'vertical', 
				size: 320, 
				addButtons: {
					previous: $('prevMember'), 
					next: $('nextMember')
				}, 
				fxOptions: {
					duration: 200, 
					wait: false, 
					transition: Fx.Transitions.Sine.easeOut
				}, 
				rewind: false, 
				onWalk: function() {
					// When there are no more slides left to slide to (no more items to show), prevent sliding
					if (this.nextIndex == iNumSlides) {
						this.walk(this.previousIndex, true);
					}
				}
			});

			// If there are less than fourteen members, remove the navigational controls
			if ($$('#membersnav li').length < 14) {
				$$('#membersContainer div.left span.control').addClass('hide');
			}

			// Add the click handling to the LI items
			$$('#membersnav li.member a').addEvent('click', fShowMemberOnMap);
			$$('#membersnav li.member').addEvent('click', fShowMemberOnMap);
		}

		if ($('filterForm')) {
			$('filterForm').addEvent('submit', fFilterMemberList);
			$('clearSearch').addEvent('click', fClearMemberSearch);
		}
	/********************************************************************************/

	// Initiliazation of the 'business card' list view of members
	if ($('alphabetnav')) {
		/*var oAlphabetSort = new Fx.Sort($$('#memberslist li.start'), {duration: 1000});
		oAlphabetSort.reverse();*/

		// Add a filter function event to each letter in the alphabet, after hiding letters which don't occur on the page
		$$('#alphabetnav li a').each(function(oElem) {
			if (!$('start-' + oElem.get('text'))) {
				oElem.getParent('li').addClass('hide');
			} else {
				oElem.addEvent('click', fSortMemberList);
			}
		});

		// Set the click event for the "reset filter" hyperlink
		$$('div.alphabet a.reset').addEvent('click', fResetMemberList);
	}

	// Whenever a reCaptcha field is on the screen, replace its buttons with LPB-style buttons
	if ($('recaptcha_widget_div')) {
		var sImgPath = 'themes/lpb/images/but-captcha-';

		$('recaptcha_reload').set('src', sImgPath + 'refresh.gif');
		$('recaptcha_switch_audio').set('src', sImgPath + 'audio.gif');
		$('recaptcha_switch_img').set('src', sImgPath + 'text.gif');
		$('recaptcha_whatsthis').set('src', sImgPath + 'help.gif');
	}
});


function fToggleSendForm() {
	$('toggleSendFriend').removeEvent('click', fToggleSendForm);
	$$('#Form_sendFriend label').setStyle('display', 'none');
	var oSendForm = $('Form_sendFriend');

	if (oSendForm.getStyle('display') == 'none') {
		oSendForm.setStyle('display', 'block');
		OverText.update();
	} else {
		oSendForm.setStyle('display', 'none');
		OverText.update();
	}

	$('toggleSendFriend').addEvent('click', fToggleSendForm);
	$$('#Form_sendFriend label').setStyle('display', 'inline');
}


function fCheckSendForm() {
	var iErrorCnt = 0;

	// Store a reference to all mandatory fields to iterate through
	var oFieldsToCheck = $$('#' + this.get('id') + ' input.required');

	$each(oFieldsToCheck, function(oField, iIndex) {
		var bValid = true;

		// Check whether or not the field has a value
		if (oField.get('value') == "") { bValid = false; }

		// Do another check for e-mail fields
		if ($$('#' + oField.get('id') + '[name*=Email]')[0]) {
			if (!emailCheck(oField.get('value'))) { bValid = false; }
		}

		if (bValid) {
			oField.removeClass("invalid");
			oField.addClass("valid");
		} else {
			oField.removeClass("valid");
			oField.addClass("invalid");
			iErrorCnt++;
		}
	});

	if (iErrorCnt > 0) {
		// If a feedback element was hidden, display it now
		if ($$('.fbMessage')[0]) { $$('.fbMessage').removeClass('hide'); }

		return false;
	} else {
		// If a feedback element was displayed, hide it now
		if ($$('.fbMessage')[0]) { $$('.fbMessage').addClass('hide'); }
		return true;
	}
}


function fNoAnchor() {
	return false;
}

function fGoBack() {
	history.back();
}


// A function which displays a miniature login form in the header's userbox and attaches the AJAX event to it
function fDisplayLoginForm() {
	// If the user is on the login page, just redirect them downwards and delete this form from the DOM to avoid clashes
	if ($$('#content input[name=Remember]')[0]) {
		if ($$('#userbox div.form')[0]) { $$('#userbox div.form').dispose(); }

		// Use the fancy Fx.Scroll class
		var fxScroll = new Fx.Scroll(window).toElement('MemberLoginForm_LoginForm');
		$('MemberLoginForm_LoginForm_Email').focus();
	} else {
		// === Make sure the login form looks perfect before displaying it ==========
			$('MemberLoginForm_LoginForm_Email').removeClass('required');
			$$('#Remember label').set('text', 'onthouden?');
			$$('#ForgotPassword a').set('text', 'wachtwoord vergeten');

			if ($('MemberLoginForm_LoginForm_Email').get('value') == "") { $('MemberLoginForm_LoginForm_Email').set('value', 'e-mail adres'); }
			if ($('MemberLoginForm_LoginForm_Password').get('value') == "") { $('MemberLoginForm_LoginForm_Password').set('value', 'wachtwoord'); }
		// ==========================================================================

		// Reverse the view
		$$('#userbox a.login').dispose();
		$$('#userbox div.form').removeClass('hide');
		$$('#userbox div.form').addClass('clearfix');
	}

	return false;
}


// A function which hides members in the 'business card' list view depending on which
// letter of the alphabet their name starts with
function fSortMemberList() {
	var sLetterID = 'start-' + this.get('text');
	var fxFadeout;

	// Make the menu item active
	$$('#alphabetnav li a').removeClass('current');
	this.addClass('current');

	// The first time a letter is clicked, all letters should fade out; subsequent times, 
	// only the last remaining letters should fade out, while clicked one fades back in
	// Hide all of this letter's siblings in the member list
	$$('#memberslist li').removeClass('current');
	$(sLetterID).getSiblings('li.start').each(function(oItem) {
		fxFadeout = new Fx.Tween(oItem, {duration: 800, property: 'opacity'});
		fxFadeout.start(1, 0).chain(
			function() { this.element.addClass('hide'); }
		);
	});

	if ($(sLetterID).hasClass('hide')) {
		$(sLetterID).removeClass('hide');
		fxFadein = new Fx.Tween($(sLetterID), {duration: 800, property: 'opacity'});
		fxFadein.start(0, 1);
	}

	// After the chain is finished, highlight the remaining 'business cards'
	var fBlinkRemaining = function() { $$('#' + sLetterID + ' div.letter, #' + sLetterID + ' ul li').highlight('#d9e5f1'); };
	fBlinkRemaining.delay(800);
	$(sLetterID).addClass('current');

	return false;
}


// A function which displays all of the 'business cards' which were hidden
function fResetMemberList() {
	if ($$('#alphabetnav li a.current')[0]) {
		// No menu items should be active as all letters are displayed
		$$('#alphabetnav li a').removeClass('current');

		// No letter should be active in the list view as the filter has been removed
		$$('#memberslist li.current').removeClass('current');

		// Fade all of the letters back in and remove the active class from the previously lone-displayed letter
		$$('#memberslist li[class*="hide"]').each(function(oItem) {
			oItem.removeClass('hide');
			var fxFadein = new Fx.Tween(oItem, {duration: 800, property: 'opacity'});
			fxFadein.start(0, 1);
		});
	} else {
		// No menu item was active, therefore there is nothing to reset
	}

	return false;
}


// A function which uses search criteria to display only matching members (geographic member page)
function fFilterMemberList() {
	var sCriteria = this.getElement('input.textbox').get('value');
	var oItems = $$('#membersnav li');

	if (sCriteria !== "") {
		// Hide all of the items before displaying the results and display the clear search button
		oItems.addClass('hide');
		this.getElement('#clearSearch').removeClass('hide');

		// Iterate through each item and check whether it contains the search criteria
		oItems.each(function(oItem) {
				oItem.erase('rel');

				var sContent = oItem.get('html');

				// Make sure both the criteria as the contents are all lowercase to void case-sensitiveness
				if ((sContent.toLowerCase()).contains(sCriteria.toLowerCase())) {
					oItem.removeClass('hide');
					oItem.set('rel', 'result');
				}
		});

		if ($$('#membersnav li[rel]').length == 0) {
			// If no results were found, display feedback in the slider list
			var liNoResults = new Element('li', {id: 'noResults', html:'<em>Geen resultaten&nbsp;</em>'});
			var aResetSearch = new Element('a', {
				href: '#', 
				title: 'Ga terug', 
				html: 'terug &raquo;', 
				events: {
					click: function() {
						// Display all the items and delete the feedback message
						$('noResults').dispose();
						oItems.each(function(oItem) { oItem.erase('rel'); });
						oItems.removeClass('hide');
						$('slideContainer').highlight('#d9e5f1');

						// If the clear search button is being shown from a previous search, hide it
						if (!$('clearSearch').hasClass('hide')) { $('clearSearch').addClass('hide'); }

						// Clear the search bar and focus on it
						var oSearchBox = $$('#filterForm input.textbox')[0];
						oSearchBox.set('value', '');
						oSearchBox.focus();

						return false;
					}
				}
			});

			aResetSearch.inject(liNoResults);
			liNoResults.inject($('membersnav'));
		} else {
			// If a previous result returned no results, make sure the current search removes that message
			if ($('noResults')) {
				$('noResults').dispose();
			}
		}
	} else {
		// If nothing was searched for, display all of the list items
		oItems.each(function(oItem) { oItem.erase('rel'); });
		oItems.removeClass('hide');

		// If the previous search did have results, make sure to hide the clear search button
		if (!$('clearSearch').hasClass('hide')) { $('clearSearch').addClass('hide'); }
	}

	// Make sure the slider moves back to the top of the list as that's where the remaning visible items will be
	oMembersNav.walk(0, true);

	// Highlight the search results to indicate to the user something has happened
	$('slideContainer').highlight('#d9e5f1');

	// Make sure the search field maintains focus (stupid IE)
	this.getElement('input.textbox').focus();

	return false;
}


// A function which returns the geographic search form to its natural state
function fClearMemberSearch() {
	// Reset the search results area
	if ($('noResults')) { $('noResults').dispose(); }
	var oItems = $$('#membersnav li');
	oItems.each(function(oItem) { oItem.erase('rel'); });
	oItems.removeClass('hide');
	$('slideContainer').highlight('#d9e5f1');

	// Reset the search form area
	var oSearchBox = this.getSiblings('input.textbox')[0];
	oSearchBox.set('value', '');
	oSearchBox.focus();
	this.addClass('hide');
}
