// JavaScript Document
	var domain = null;
	$(function() {
		try {
			domain = 'http://'+top.location.host;	
		}
		catch(err) {
			domain = 'http://'+document.location.host;
		}
				
		// Keep session alive
		keepSessionAlive();

		// Reposition popupcontainer on load
		repositionPopup();
		// Reposition popupcontainer on resize
		$(window).bind('resize', function(){repositionPopup()});
		// Reposition popupcontainer on scroll
		$(window).bind('scroll', function(){repositionPopup()});		
			
		// Insert and position loading div
		var loadingDiv = $('<div id="ajax-loader" class="ajax-loader"></div>');
		loadingDiv.css('position', 'absolute');
		loadingDiv.css('display', 'none');
		$('body').prepend(loadingDiv);	
		$(document).mousemove( function(e) {
		   mouseX = e.pageX + 10; 
		   mouseY = e.pageY - 50;
		   $('#ajax-loader').css('top', mouseY+'px');
		   $('#ajax-loader').css('left', mouseX+'px');		   		   
		 });	

		// if the card card popup is requested, show popup
		if (window.location.href.indexOf("#popup=") > -1) { 
			var url = domain + window.location.href.substr(window.location.href.indexOf("#popup=")+7);		
			showCardInfoWindow(url); 
		}		
		
		// focus on first input field, not on homepage or search page
		if ($('#column-main form:visible:has(:input:not([type=submit]):not([readonly=readonly]):visible)').length > 0) {
			$('#column-main form:visible:first:has(:input:visible) :input:not([type=submit]):not([readonly=readonly]):visible:first').focus();			
		}		
		
		//preview in fancybox
		 $("a.preview").fancybox({
		  'type':			'image',
		  'zoomSpeedIn'		: 300, 
		  'zoomSpeedOut'	: 300, 
		  'overlayShow'		: false,
		  'titlePosition'	: 'inside',
		  'titleFormat'		: formatTitle		  
		 });			
		 
		//popup content in fancybox
		fancyLinks();	
		
		initTabs();
	});
	
function fancyLinks() {	
		//popup content in fancybox
		 $("a.fancy").fancybox({
		  'zoomSpeedIn'		: 300, 
		  'zoomSpeedOut'	: 300, 
		  'overlayShow'		: false,
		  'ajax'			: {'data': 'fancy=1'},
		  'onClosed'		: function(){fancyLinks()}
		 });			
}
	
function formatTitle(title, currentArray, currentIndex, currentOpts) {
	var output = '';
	var otherSide = '';
	// Nederlands
	if (title.indexOf('kaart') != -1) {
		titleInsideFolded	= 'Binnenzijde wenskaart';
		titleBacksideSingle	= 'Achterzijde ansichtkaart';
		titleFrontSingle	= 'Voorzijde ansichtkaart';
		front				= 'voorzijde';
		backside			= 'achterzijde';
		inside				= 'binnenzijde';
		See					= 'Bekijk';
	}
	// English
	else {
		titleInsideFolded	= 'Inside Greeting card';
		titleBacksideSingle	= 'Back Postcard';
		titleFrontSingle	= 'Front Postcard';
		front				= 'frontside';
		backside			= 'backside';
		inside				= 'inside';
		See					= 'See';		
	}
	
	if (title == titleInsideFolded || title == titleBacksideSingle) {
		otherSide = front;
		output = '<a href="javascript:;" onclick="$.fancybox.prev();" style="display:block;float:right">'+ See +' '+ otherSide + ' &raquo;</a>';
	}
	else {
		otherSide = title == titleFrontSingle? backside : inside;
		output = '<a href="javascript:;" onclick="$.fancybox.next();" style="display:block;float:right">'+ See +' '+ otherSide + ' &raquo;</a>';		
	}
	
	output += '<strong style="display:block;text-align:left;">' + title + '</strong>';	
	return output;
}
		
	// Keep session alive	
	function keepSessionAlive() {
		var timeout = (15 * 60 * 1000) // every 15 minutes 
		setTimeout("savesession()", timeout);
	}
	function savesession() {
		var url = '/sessionsaver.php';
		$.post(url, null, function(data) {
			//alert(data);
			keepSessionAlive();
		});	
	}
	
	var windowHeight = $(window).height(); // height of the viewport
	var globalRepositionCounter = 0;
	// Function to start the reposition process for the popup-container div to middle of screen
	function repositionPopup() {	
		globalRepositionCounter++;
		var localRepositionCounter = globalRepositionCounter;
		setTimeout("doRepositionPopup("+localRepositionCounter+")", 200);
	}
	// Function to actually reposition the popup-container div to middle of screen
	function doRepositionPopup(localRepositionCounter) {
		// Don't reposition if a new reposition request was fired
		if (localRepositionCounter != globalRepositionCounter) {
			return;
		}


		var headerHeight = 150; // distance in pixels from top of screen to default start popupContainer
		if ($('#beta-message').length > 0) {
			headerHeight += 50;
		}
		var headerHeightSite = $("#header").css('height').substr(0,3);
		if ( $("#header").css('height').length == 4){
			var headerHeightSite = $("#header").css('height').substr(0,2);
		}
		headerHeight += (headerHeightSite - 129);
		

		
		var bodyHeight = $('body').height(); // height of the whole page
		var newWindowHeight = $(window).height(); // (new) height of the viewport
		var scrollTop = $(window).scrollTop(); // vertical scroll distance

		var resizeMask = false;
		// If the mask is invisble now or the windowheight has changed, resize the mask
		if ($('#mask:visible').length == 0 || newWindowHeight != windowHeight) {
			resizeMask = true;
		}
		windowHeight = newWindowHeight;
		
		var popupContainers = $('.popup-container');

		if (popupContainers.length > 0) {
			var popupContainer = $(popupContainers[0]);		
			var popups = popupContainer.find('.popup');
			var popup = $(popups[0]);
			var popupHeight = popup.height(); // height of the popup
			
			// Try to position the popup in the middle of the screen
			var newTop = (windowHeight/2) - (popupHeight/2);
			newTop = newTop - headerHeight;				
			// Don't let the top of the popupContainer get out of the window top
			if (newTop <= ((headerHeight*-1) + 5)) {
				newTop = (headerHeight*-1) + 5;
			}
			
			newTop += scrollTop;

			var fullHeight = bodyHeight > windowHeight? bodyHeight : windowHeight;	
			
			if (resizeMask) {
				// Stretch and show mask
				if (popupHeight+headerHeight+newTop > fullHeight) {
					fullHeight = popupHeight+headerHeight+newTop;
				}			
				$('#mask').css('height', fullHeight);
				$('#mask').show();				
			}
			// Don't reposition if the popupHeight is larger than the windowHeight
			// Don't reposition if the popupHeight + the top is larger than the fullHeight
			// Always reposition if it is the first request (mask is invisible)
			if ((popupHeight < windowHeight && (popupHeight+headerHeight+newTop) < fullHeight) || resizeMask) {
				popupContainer.css('top', newTop+'px');
				setTimeout(function(){popupContainer.css('visibility', 'visible');}, 250);
			}
		}
	}

	// bind switchTab function to all tabs
	function initTabs() {
		// get all links with attribute rel beginning with "tab" and bind the switchtab function
		$('a[rel^="tab"]').bind('click', function() {
			var pageId = null;
			var pageType = null;
			var rel = $(this).attr('rel');
			
			// determine which elements to switch
			var relParts = rel.split('[');
			if (typeof relParts[1] != 'undefined') {
				var pageData = relParts[1].split(',');
				if (typeof pageData[1] == 'undefined') {
					pageId = relParts[1].substr(0, relParts[1].length-1);					
				}
				else {
					pageId = pageData[0];
					pageType = pageData[1].substr(0,pageData[1].length-1);
				}
			}
			
			return switchTab(this, pageId, pageType);
		});			
	}

	// function to switch elements for tabs
	function switchTab(clickedEl, pageId, pageType) {
		var a = $(clickedEl);
		var li = a.parent();
		var ul = li.parent();
		
		if (typeof pageId == 'undefined' || pageId == null) {
			pageId = a.attr('id').substr(4);
		}
		if (typeof pageType == 'undefined' || pageType == null) {
			pageType = ul.attr('id').substr(4);
		}		

		ul.find('li').removeClass('active');
		$('#'+pageType).children().hide();
		$('#'+pageId).show();
		li.addClass('active');
		
		return false;		
	}

	// function for card popup
	function switchCardType(element, cardType) {
		if (element.tagName == 'a') {
			switchTab(element, cardType);
			
		}
		else {
			switchTab($('#tab-'+cardType), cardType);
		}
		switchTab(element, 'form-'+cardType, 'forms-card-preview');		
		
		var oppositeCardType = cardType == 'ansicht'? 'folded' : 'ansicht';
		$('#radio-'+oppositeCardType+'-2').attr('checked',true);
		
		return false;
	}	


	// check on change of window.location.hash	
	var savedHash = null;	
	var historySaverInterval = null;
	function checkHash() {
		var timeout = 500 // every second
		historySaverInterval = setInterval("historySaver()", timeout);
	}
	function historySaver() {
		if (savedHash != null) {
			var currentHash = getLocationHash();
			
			if (currentHash != savedHash) {
				var url = domain+currentHash.substr(6);
				if (url.indexOf('/card') != -1) {
					showCardInfoWindow(url);	
				}
				else {
					savedHash = currentHash;
					closeCardInfoWindow();	
				}
			}
		}
	}
	function getLocationHash() {
		var hash = window.location.hash;	
		if (hash.length > 0 && hash.substr(0,1) == '#') {
			hash = hash.substr(1);
		}
		return hash;
	}

	function showCardInfoWindow(url) {
	
		savedHash = 'popup='+url;
		if(url.indexOf(domain) != -1) {
			savedHash = 'popup='+url.substr(domain.length);
		}
			
		window.location.hash = savedHash;		

		// if not already checking, start checking on change of window.location.hash
		if (historySaverInterval == null) {
			checkHash();					
		}
		
		// hide selectboxes for ie6
		$('#main select').css('visibility', 'hidden');
		
		var targetId = 'main';
		var getId	= 'card-info';
		//var url		= "/card/"+cardId;
		var data	= null;
		var popup	= true;
		getAjaxElementInto(getId, targetId, url, data, popup);
		return false;
	}
	function closeCardInfoWindow() {
		savedHash = 'popup-closed';		
		window.location.hash = savedHash;		
		
		// show selectboxes for ie6
		$('#main select').css('visibility', 'visible');
		$('#mask').hide();
		
		var cardContainer = $('.popup-container');
		if (cardContainer.length == 0) {
			return true;
		}
		else {
			cardContainer.remove();
			return false;
		}
	}
	
	function replaceMain(url, data) {
		if (typeof data == 'undefined') {
			getAjaxElementInto('main', 'main', url);
		}
		else {
			getAjaxElementInto('main', 'main', url, data);
		}
		return false;
	}
	
	function replaceColumnMain(url, data) {
		if (typeof data == 'undefined') {
			getAjaxElementInto('column-main', 'column-main', url);
		}
		else {
			getAjaxElementInto('column-main', 'column-main', url, data);
		}
		return false;
	}
	
	function replaceColumnMainByFormPost(form, url) {
		if (typeof url == 'undefined') {
			url = form.action;
		}
		getAjaxFormPostInto('column-main', 'column-main', url, form);
		return false;
	}	

	// function to get an element from another page after form post and insert it into the current page	
	function getAjaxFormPostInto(getId, targetId, url, form, popup) {
		if (typeof url == 'undefined') {
			url = form.action;
		}
		if (typeof popup == 'undefined') {
			var popup = false;
		}		
		var data = '';
		var formElements = form.elements;
		for (var i=0; i<formElements.length; i++) {
			data += formElements[i].name+'='+formElements[i].value+'&';
		}
		getAjaxElementInto(getId, targetId, url, data, popup);
	}
	
	// function to get an element from another page and insert it into the current page
	function getAjaxElementInto(getId, targetId, url, data, popup) {
		$('#ajax-loader').show();
		if (typeof data == 'undefined') {
			var data = '';
		}
		if (typeof popup == 'undefined') {
			var popup = false;
		}
		var targetEl = $('#'+targetId);
		
		var popupContainers = $('#current_popup');
		if (popupContainers.length > 0) {
			var popupContainer = $(popupContainers[0]);
		}
		else {
			var popupContainer = $('<div class="popup-container" id="current_popup"></div>');
			//popupContainer.css('display', 'none'); 
			$(popupContainer).prependTo(targetEl);
		}

		$.ajax({
			type: "POST",
			url: url,
			data: 'ajax=1&'+data,
			success: function(msg, textStatus){
				var html = $('<div>'+msg+'</div>');	

				var getEl = html.find('#'+getId);

				if (getEl.length > 0) {
					// If the requested element is found...
					if (popup === true) {
						getEl.addClass('popup');					
						popupContainer.html(getEl);
						repositionPopup();							
					}
					else {
						//alert(getEl.html());
						$(targetEl).html(getEl.html());
					}
				}
				else {
					// If the requested element could not be found, show whole requested page				
					if (popup === true) {
						popupContainer.html('<div class="popup">'+msg+'</div>');
						repositionPopup();
					}
					else {
						$(targetEl).html(msg);
					}
				}
				initTabs();
				setTimeout(function(){$('#ajax-loader').hide();}, 200);
			}
		});		
		return false;
	}

	function urlencode(str) {
		// URL-encodes string  
		// 
		// version: 911.718
		// discuss at: http://phpjs.org/functions/urlencode
		// +   original by: Philip Peterson
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +      input by: AJ
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   improved by: Brett Zamir (http://brett-zamir.me)
		// +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +      input by: travc
		// +      input by: Brett Zamir (http://brett-zamir.me)
		// +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   improved by: Lars Fischer
		// +      input by: Ratheous
		// +      reimplemented by: Brett Zamir (http://brett-zamir.me)
		// +   bugfixed by: Joris
		// +      reimplemented by: Brett Zamir (http://brett-zamir.me)
		// %          note 1: This reflects PHP 5.3/6.0+ behavior
		// %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
		// %        note 2: pages served as UTF-8
		// *     example 1: urlencode('Kevin van Zonneveld!');
		// *     returns 1: 'Kevin+van+Zonneveld%21'
		// *     example 2: urlencode('http://kevin.vanzonneveld.net/');
		// *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
		// *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
		// *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
		str = (str+'').toString();
		str = str.toLowerCase();		
		
		// Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
		// PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
		return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
		return string;
	}
	
	function checkAddress(value, returnId, message) {
		value = value.replace(/^\s+/,''); 
		value = value.replace(/\s+$/,'');		
		var valueParts = value.split(' ');
		if (valueParts.length > 1) {
			var digits = "0123456789";			
			var digitsFound = false;		
			var wordFound = false;
			var valuePart;
			var char;
			var isNumber;
			for (var i=0;i<valueParts.length;i++) {
				isNumber = false;
				valuePart = valueParts[i];
				for (var x=0;x<valuePart.length;x++) {
					char = valuePart.charAt(x);
					if (digits.indexOf(char) != -1) {
						isNumber = true;
						break;
					}
				}
				if (isNumber) {
					digitsFound = true;
				}
				else {
					wordFound = true;
				}
				if (wordFound && digitsFound) {
					$('#'+returnId).hide();
					return false;							
				}				
			}
		}
		$('#'+returnId).html(message);
		$('#'+returnId).show();
		return false;					
	}
	
	function checkActieCode(id) {
		var data = 'ajax=1&action_code='+$('#action-code').val();
				
		$.ajax({
			type: "POST",
			url: window.location.href,			
			data: data,
			success: function(msg, textStatus){
				$('#'+id).replaceWith(msg);
			}
		});		
	} 
	
	function setDonation() {
		var data = 'ajax=1&donation='+$('#donation').val();
				
		$.ajax({
			type: "POST",
			url: window.location.href,			
			data: data,
			success: function(msg, textStatus){
				if ($('#order-total-codes-in-shop').length == 0) {
					$('#order-total-no-codes').replaceWith(msg);
				}
				else {
					$('#order-total-codes-in-shop').replaceWith(msg);
				}
			}
		});		
	}
	
	function showTelefoonGids() {
		showCardInfoWindow('/telefoongids');
		setTimeout(function() {
			$('#telefoongids').find('input').keyup(function(e) {			
				if(e.keyCode == 13) {
					searchTelefoonGids();
				}
			});
		}, 200);
		
		return false;
	}
	
	function searchTelefoonGids() {
		$('#ajax-loader').show();
		var name = $('#telefoongids').find('.naam').val();
		var city = $('#telefoongids').find('.plaats').val();
		
		var cont = true;
		
		$('#telefoongids').find('.naam').removeClass('error');
		$('#telefoongids').find('.plaats').removeClass('error');
		
		if(name == '') {
			//alert('Vul een naam in...');
			$('#telefoongids').find('.naam').addClass('error');
			cont = false;
		}
		if(city == '') {
			//alert('Vul een plaatsnaam in...');
			$('#telefoongids').find('.plaats').addClass('error');
			cont = false;
		}
		
		if(cont) {		
			var url = '/telefoongids';
			
			var data = 'name='+name+'&city='+city;
			
			$.ajax({
				type: "POST",
				url: url,
				data: 'ajax=1&'+data,
				success: function(msg, textStatus){
					$('#current_popup').replaceWith(msg);
					
					setTimeout(function(){$('#ajax-loader').hide();}, 200);
					setTimeout(function() {
						$('#telefoongids').find('input').keyup(function(e) {			
							if(e.keyCode == 13) {
								searchTelefoonGids();
							}
						});
						repositionPopup();
					}, 200);
				}
			});
		}		
	}
	
	function insertTelefoonGidsAddress(name, address, zipcode, city) {
		$('#recipient_lastname').val(name);
		$('#recipient_address').val(address);
		$('#recipient_postal_code').val(zipcode);
		$('#recipient_city').val(city);
		
		closeCardInfoWindow();
	}
