/**
 * Base class, extended by specialised JS objects that may or may not be included
 * 
 * Namespace "BaseTemplate"
 * @class BaseTemplate
 * @desc BaseTemplate class of this project
 */
var BaseTemplate = (function($) {
	var Base = function() {
		// VARIABLES DEFINED HERE ARE PRIVATE
		var arr_init = []; // Array containing all registered init-functions of subclasses
		
		// FUNCTIONS DEFINED HERE ARE PRIVATE
		
		/**
		 * Check and execute registered subclass functions
		 */
		function check_register()
		{
			for (var i = 0; i < arr_init.length; i++)
			{
				arr_init[i]();
			}
		}
		
		return {
			// FUNCTIONS DEFINED HERE ARE PUBLIC
			
			/**
			* Register (initialization) calls from subclasses
			* @param (obj_function) Function to initialize subclass
			*/
			register: function(obj_function) {
				arr_init.push(obj_function);
			},
	
			/**
			* Initialize this class
			*/
			init: function() {
				check_register();
			}
		};
	} ();
	
	$(document).ready(function() {
		Base.init();
	});
	
	return Base;
	
}) (jQuery);

/**
 * Namespace "Common"
 * @class Common
 * @desc Common of BaseTemplate
 */

BaseTemplate.Common = (function($) {
	var Common = function() {
		// Variables & functions defined here are private
		var navOpen = false;

		/**
		 * function slide navigation down
		 */
	  	function slideNav() {
	  		$(document).bind('click.nav', function(e) {
	  			if (!navOpen)
	  			{
	  				return;
	  			}

	  			if (!$(e.target).is('a') &&
	  				($(e.target).is('#nav-sub') || $(e.target).parents('#nav-sub').is('#nav-sub')))
	  			{
	  				return false;
	  			}
	
	  			toggleNav(false);
	  		});
	  		
	  		$('#nav-sub a.close').click(function() {
	  			toggleNav(false);
	  			return false;
	  		});
	  		
	  		// find nav id
	  		$('#nav-main .left a:not(.special, .one)').bind('click', function() {
	  			if (navOpen)
	  			{
	  				toggleNav(false);
	  			}
	  			else
	  			{
	  				toggleNav(true);
	  			}

				return false;
			});
		}
		
		function toggleNav(show)
		{
			if (show)
			{
				$('#nav-sub').slideDown();
				navOpen = true;
			}
			else
			{
				$('#nav-sub').slideUp();
				navOpen = false;
			}
		}
		
		function showNavTwo()
		{
			$('#nav-main a.two').mouseover(
				function() {
					$('#nav-sub ul.two').show();
					$('#nav-sub ul.one').hide();
					$('#nav-sub ul.three').hide();
					$('#nav-sub ul.four').hide();
				}
			);
		}
		function showNavThree()
		{
			$('#nav-main a.three').mouseover(
				function() {
					$('#nav-sub ul.three').show();
					$('#nav-sub ul.one').hide();
					$('#nav-sub ul.two').hide();
					$('#nav-sub ul.four').hide();
				}
			);
		}

		function showNavFour()
		{
			$('#nav-main a.four').mouseover(
				function() {
					$('#nav-sub ul.four').show();
					$('#nav-sub ul.one').hide();
					$('#nav-sub ul.two').hide();
					$('#nav-sub ul.three').hide();
				}
			);
		}

		/** 
		* Functions to create, read and erase cookies
		*/
		function createCookie(name, value, days)
		{
			if (days)
			{
				var date = new Date();
				date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
				var expires = "; expires=" + date.toGMTString();
			}
			else
			{
				var expires = "";
			}
			document.cookie = name + "=" + value + expires + "; path=/";
		}
		
		function readCookie(name)
		{
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for (var i = 0; i < ca.length; i++)
			{
				var c = ca[i];
				while (c.charAt(0) == ' ')
				{
					c = c.substring(1, c.length);
				}
				if (c.indexOf(nameEQ) == 0)
				{
					return c.substring(nameEQ.length, c.length);
				}
			}
			return null;
		}
		
		function eraseCookie(name)
		{
			createCookie(name, "", -1);
		}

		/** 
		* Function to change the font size
		*/
		function fontResizing()
		{
			$('a.enlarge').click(function() {
				$('body').removeClass('largest').addClass('enlarge');
				createCookie('fonts','enlarge',31)
				return false;
			});
			$('a.largest').click(function() {
				$('body').removeClass('enlarge').addClass('largest');
				createCookie('fonts','largest',31)
				return false;
			});
			$('a.standard').click(function() {
				$('body').removeClass('enlarge').removeClass('largest');
				eraseCookie('fonts')
				return false;
			});
			var fonts = readCookie('fonts');
			$('body').addClass(fonts);
		}

/*					   
		$.easing.drop = function (x, t, b, c, d) { 
			return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; 
		}; 
	   
		$.easing.outElastic = function (x, t, b, c, d) {
			var s=1.70158;var p=0;var a=c;
			if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
			if (a < Math.abs(c)) { a=c; var s=p/4; }
			else var s = p/(2*Math.PI) * Math.asin (c/a);
			return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
		};
					   // create custom overlay effect for jQuery Overlay 
		$.tools.overlay.addEffect("drop",   
								 
		// loading animation 
		function(done) {  
			var animateProps = { 
				top: '+=55',  
				opacity: 1,  
				width: '+=20' 
			}; 
			this.getOverlay().animate(animateProps, "medium", 'dopr', done).show(); 
		},  

		// closing animation 
		function(done) { 
			var animateProps = { 
				top: '-=55',  
				opacity: 0,  
				width: '-=20' 
			}; 
			this.getOverlay().animate(animateProps, "fast", 'drop', function()  { 
			   $(this).hide(); 
			   done.call();         
			   }); 
			} 
		);
*/
		// tooltip functionality
		function installLoginToolTip()
		{
			$('#login .tooltip').infoToolTip({
				offsetX: 5,
				offsetY: 15
			});
		}

		/**
		 * Enables the print button on all pages
		 */
		function enablePrintButton(){
			$('#nav .print').click(function(){
				print();
				return false;
			});
		}

		/**
		 * In form adds extra fields for members who need to pay.
		 */
		function toggleMembership()
		{
			$('.age input').click(function() {
				var value = $(this).val();
				if (value == 'adult')
				{
					$('.payment').show();
				}
				if (value == 'child')
				{
					$('.payment').hide();
				}
			});
		}

		function installEvenementReserveerHandler()
		{
			$("#register-event-content button").click(function() {
				var isOK = true;
				var eMailInput = $("#register-event-content input[name=E-mail]");
				var eMail = $.trim(eMailInput.val());
				if (eMail.length == 0 ||
					eMail.indexOf("@") == -1)
				{
					isOK = false;
					eMailInput.next().show();
					eMailInput.get(0).select();
				}
				else
				{
					eMailInput.next().hide();
				}
				var nameInput = $("#register-event-content input[name=Naam]");
				if ($.trim(nameInput.val()).length == 0)
				{
					isOK = false;
					nameInput.next().show();
					nameInput.get(0).select();
				}
				else
				{
					nameInput.next().hide();
				}
				var dateInput = $("#register-event-content input[name=Datum]");
				// In case the <select/> is used, there's no input
				if (dateInput.length > 0)
				{
					if ($.trim(dateInput.val()).length == 0)
					{
						isOK = false;
						dateInput.next().show();
						dateInput.get(0).select();
					}
					else
					{
						dateInput.next().hide();
					}
				}

				if (isOK)
				{
					$.ajax({
						url: "inc/ajax/verwerk_evenement_registreren.php",
						type: "POST", 
						cache: false,
						data: $("#register-event-content select, #register-event-content input"),
						dataType: "html",
						success: function(data, textStatus, XMLHttpRequest) {
//logToConsole("evenement_registreren succes: " + textStatus);
							$("#register-event-content").html(data);
							// TODO: Should use a separate 'infoWindow' handler for this, just for the close button!
//							initInfoWindows();
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							logToConsole("Evenement registreren Ajax - error: " + textStatus + "/" + errorThrown);
						},
						complete: function(XMLHttpRequest, textStatus) {
//logToConsole("widget_favorieten_set_rating complete: " + textStatus);
						}
					});
				}
				return false;
			});
		}

		/**
		 * Central place to init infoWindows.
		 * Put each in separate selector
		 */
		function initInfoWindows()
		{
			$('.register-for-event').bind('click.infoWindow', function() {
				// Retrieve the query string (without the initial '#')
				var getVars = $(this).attr('href').substr(1);
				// IE 7 fix for 'href' dynamically added to DOM
				if (getVars.substr(0, 1) != "?")
				{
					var hashPos = getVars.lastIndexOf("#");
					getVars = getVars.substr(hashPos + 1);
				}

				infoWindow("inc/ajax/evenement_registreren.php" + getVars, {
					contentClass: 'register-event',
					type: 'ajax',
					overlayOpacity: .1,
					overlayClickClose: false,
					afterOpen: function() {
						installEvenementReserveerHandler();
					}
				},
				function() {
					installEvenementReserveerHandler();
				});
				return false;
			});
		}

/*
		function installOverlay(objName)
		{
			// dit is de algemene routine om een overlay (onclick) handler te installeren op bv een <a>
			$(objName).overlay({
				 
				expose: '#ffffff',
				effect: 'apple',
				speed: 10,
							   
				onBeforeLoad: function() {
					var anchor = this.getTrigger();
					var ovl = $("#simple_overlay");
					// grab wrapper element inside content
					var iframe = ovl.find(".contentWrap iframe");
					// set the src specified in the trigger
					//console.log(anchor.attr("href"));
					iframe.attr("src", anchor.attr("href"));
					iframe.attr("width", ovl.css("width"));
					iframe.attr("height", ovl.css("height"));				
				},

				onClose: function() {
					ovl = $("#simple_overlay");
					ovl.hide();
					ovl.find(".contentWrap iframe").attr("src", "");
				}
			});
		}
*/
		function logToConsole(message)
		{
			if (typeof console != "undefined" &&
				typeof console.log != "undefined")
			{
				console.log(message);
			}
		}

/*
		function installLoginCheckLinkHandler()
		{
		}
*/

		function replaceEmptyImageWithPlaceholder(image, nonDOMImage)
		{
			if (image.naturalWidth &&
				image.naturalWidth <= 1 ||
				image.naturalHeight <= 1)
			{
				// Load a 'no cover supplied' image
//console.log("** Replacing image '" + image.src + "' with placeholder");
				image.onload = null;
				image.src = "static/images/icons/noCover.png";
				return;
			}

			if (typeof nonDOMImage == "undefined")
			{
//console.log("Creating test-image for '" + image.src + "'");
				var nonDOMImage = new Image();
				nonDOMImage.onload = function() {
					replaceEmptyImageWithPlaceholder(image, nonDOMImage);
				};
				nonDOMImage.src = image.src;
//				setTimeout(function() {
//					replaceEmptyImageWithPlaceholder(image, nonDOMImage);
//					},
//					300);
				return;
			}
			if (!nonDOMImage.complete)
			{
//console.log("## Waiting for test-image '" + nonDOMImage.src + "' to load");
				setTimeout(function() {
					replaceEmptyImageWithPlaceholder(image, nonDOMImage);
				},
				300);
				return;
			}

			if (nonDOMImage.width == undefined ||
				nonDOMImage.height == undefined ||
				(nonDOMImage.width <= 1 &&
				nonDOMImage.height <= 1))
			{
				// Load a 'no cover supplied' image
				image.onload = null;
				image.src = "static/images/icons/noCover.png";
//console.log("** Replacing image '" + nonDOMImage.src + "' with placeholder");
			}
			nonDOMImage = null;
		}

		return {
			/**
			 * Initialize this Class
			 */
			installOverlay: function(objName) {
				installOverlay(objName);
			},
			replaceEmptyImageWithPlaceholder: function(image, nonDOMImage) {
				replaceEmptyImageWithPlaceholder(image, nonDOMImage);
			},
			initInfoWindows: function() {
				initInfoWindows();
			},
			/**
			 * Returns the value of an URL param
			 * @param {String} name
			 * @param {String} url [optional]
			 */
			urlParam: function(name, url){
				name = name.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
				var regexS = '[\\?&]'+name+'=([^&#]*)';
				var regex = new RegExp(regexS);
				var results = (typeof url == 'undefined') ? regex.exec(window.location.href) : regex.exec(url);

				if (results == null)
				{
					return '';
				}
				else
				{
					return results[1];
				}
			},
			logToConsole: function(message) {
				logToConsole(message);
			},
			init: function() {
				slideNav();
				showNavTwo();
				showNavThree();
				showNavFour();
				fontResizing();
				toggleMembership();
				installLoginToolTip();
				enablePrintButton();
			}
		};
	} ();

	// Register the initializer for this class
	BaseTemplate.register(Common.init);
	
	return Common;

}) (jQuery);
