/**
 * site
 */
var site = function() {
	/* CONFIGURATION */
	var homeId = 115;
	var siteWidth = 930;
	var navSlideDuration = 200;
	var homeFadeDuration = 300;
	var maskFadeDuration = 300;
	var maskOpacity = 0.80;
	var debug = false;

	/* PRIVATE */
	var userIsAlive = false;
	var busyLoadingContent = false;
	var siteUrl = window.location.protocol + '//' + window.location.host;

	/**
	 * handleMenuClick
	 */
	function handleMenuClick(clickedAnchor) {
		site.showDebugMessage('site.handleMenuClick');

		$('#site .active').removeClass('active');
		$(clickedAnchor).addClass('active');

		var parentDivId = $(clickedAnchor).parents('div').attr('id');
		var anchorHref = clickedAnchor.attr('href');

		// remove site and trailing slash
		anchorHref = anchorHref.replace(siteUrl + '/', '');
		anchorHref = anchorHref.substring(0, anchorHref.length - 1);

		// split
		var posts = anchorHref.split('/');

		// nav-main & nav-top
		if ( posts.length > 0 ) {
			var firstUl = $('ul a[href="' + siteUrl + '/' + posts[0] + '/"]').parent().children('ul:first');
			if ( firstUl.size() == 0 || firstUl.css('display') == 'none' ) {
				$('ul li > ul').each(function() {
					if ( $(this).css('display') == 'block'  ) {
						$(this).slideToggle(navSlideDuration);
					}
				});
				firstUl.slideToggle(navSlideDuration);
			}
		}

		// nav-sub
		if ( posts.length > 1 ) {
			var secondAnchor = $('ul a[href="' + siteUrl + '/' + posts[0] + '/' + posts[1] + '/"]');
			if ( secondAnchor.attr('class') != 'active' ) {
				secondAnchor.addClass('active');
			}
		}
	}

	/**
	 * loadPost
	 */
	function loadPost(postUrl, postData) {
		site.showDebugMessage('site.loadPost: ' + postUrl);

		postData = typeof(postData) != 'undefined' ? postData : {};

		busyLoadingContent = true;

		// stop loading background
		siteBackground.stopLoading();

		// google analytics
		_gaq.push(['_trackPageview', postUrl]);

		// get content
		postData.ajax = 1;
		postData.screenwidth = screen.width;
		$.post(postUrl, postData, function(data) {
			site.showDebugMessage('site.postLoaded: ' + data.post.title);

			// set title
			document.title = data.post.title;

			// set readspeaker
			$('.readspeaker a').attr('href', 'http://app.readspeaker.com/proreader/proreader.php?cid=4928&amp;lang=nl_nl&url=' + postUrl.replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+'));

			// set correct class
			if ( data.post.id != homeId ) {
				$('body').attr('class', data.post.bodyclass);

				// set data
				$('#crumbs').html(data.breadcrumbs);
				$('#nav-sub').html(data.post.navsub);
				$('#post').html(data.post.content);

				// make sure clicks are handled again
				$('#post-container a').click(site.handleClick);

				// make sure forms are handled again
				$('#post form').submit(site.handleFormSubmit);

				// make sure youtube-videos are handled again
				$('#post a[href^="http://www.youtube.com"]').click(openJWPlayer);
				$('#post a[href^="http://youtu.be"]').click(openJWPlayer);

				// attempt 2 to find correct link and handle it
				$('#post-container a[href="' + postUrl + '"]').first().each(function() {
					if ( !$(this).hasClass('active') ) {
						handleMenuClick($(this));
					}
				});

				$('#news-post').fadeOut(homeFadeDuration, function() {
					$('#post-container').fadeIn(homeFadeDuration);
					$('#news-actueel').fadeIn(homeFadeDuration);
				});
			}
			else {
				// don't set class to avoid css interference with fade-effect
				$('body').attr('class', data.post.bodyclass.replace('home', ''));
				$('#post-container').fadeOut(homeFadeDuration);

				$('#news-actueel').fadeOut(homeFadeDuration, function() {
					$('#news-post').fadeIn(homeFadeDuration);
				});
			}

			// background-image
			siteBackground.load(data.bgimage);

			busyLoadingContent = false;
		});
	}

	/**
	 * openJWPlayer
	 */
	function openJWPlayer(e) {
		var youTubeUrl = $(this).attr('href');
		$('#mask').fadeTo(maskFadeDuration, maskOpacity, function() {
			$('#jwplayer-close-container').show();
			jwplayer('jwplayer').setup({
				flashplayer: siteUrl + '/wp-content/themes/biblionetid/swf/player.swf',
				file: youTubeUrl,
				skin: siteUrl + '/wp-content/themes/biblionetid/swf/vimeo-skin.swf',
				width: 546,
				height: 350,
				autostart: true
			});
		});

		e.stopPropagation();
		return false;
	}

	/**
	 * closeJWPlayer
	 */
	function closeJWPlayer() {
		$('#mask').fadeOut(maskFadeDuration);
		$('#jwplayer-close-container').hide();
		jwplayer('jwplayer').remove();
	}

	return {
		/* PUBLIC */

		/**
		 * init
		 */
		init: function() {
			site.showDebugMessage('site.init');

			// fadein payoff
			$('.payoff').hide().delay(2000).fadeIn(2000);

			// handle all clicks
			$('#site a').click(site.handleClick);

			// handle all forms
			$('#site form').submit(site.handleFormSubmit);

			// rewrite css classes to avoid conflicts
			$('#site li.current_page_ancestor').each(function() {
				if ( $(this).children('ul').size() == 0 ) {
					$(this).children('a:first').addClass('active');
				}
				$(this).removeClass('current_page_ancestor');
				$(this).children('ul').css('display', 'block');
			});
			$('#site li.current_page_item').each(function() {
				$(this).removeClass('current_page_item');
				$(this).children('a:first').addClass('active');
				$(this).children('ul:first').css('display', 'block');
			});

			// keep track of site-location if user uses back/forward-button
			$.History.bind(site.handleHistory);

			// keep track of window size
			$(window).resize(site.handleWindowResize);

			// jwplayer
			$('a[href^="http://www.youtube.com"]').click(openJWPlayer);
			$('a[href^="http://youtu.be"]').click(openJWPlayer);
			$('#mask').click(closeJWPlayer);
			$('#jwplayer-close').click(closeJWPlayer);
			$('#mask').hover(
				function() {
					if ( $(this).css('display') == 'block' ) {
						$('#jwplayer-close').hide();
					}
				},
				function() {
					if ( $(this).css('display') == 'block' ) {
						$('#jwplayer-close').show();
					}
				}
			);
			$('#jwplayer-close').hover(
				function() {
					$(this).show();
					$(this).addClass('hover');
				},
				function() {
					$(this).removeClass('hover');
				}
			);

			if ( debug ) {
				$('#partner').click(function() {
					$('#debug').toggle();
				});
			}

			// readspeaker popup
			$('.readspeaker a ').click(function() {
				window.open(this.href+"&amp;selhtml="+escape(selectedString), this.target, "width=190, height=120, resizable=1, scrollbars=1, screenX=0, screenY=0, left=0, top=0");
				return false;
			});

			// init background
			siteBackground.init();
		},

		showDebugMessage: function(s) {
			if ( debug ) {
				$('#debug').prepend(s + '<br/>');
			}
		},

		/**
		 * handleClick
		 * user clicked on a link somewhere on the site.
		 */
		handleClick: function(e) {
			site.showDebugMessage('site.handleClick');

			userIsAlive = true;

			realPostUrl = $(this).attr('href');

			// if no http then add correct http
			if ( realPostUrl.substring(0, 4) != 'http' && realPostUrl.substring(0, 6) != 'mailto' ) {
				if ( realPostUrl.substring(0, 1) != '/' ) {
					realPostUrl = '/' + realPostUrl;
				}
				realPostUrl = siteUrl + realPostUrl;
			}

			// determine if link is within site
			if ( realPostUrl.substring(0, siteUrl.length) == siteUrl ) {
				if ( realPostUrl.substring(realPostUrl.length - 4) != '.pdf' ) {
					hashPostUrl = realPostUrl.replace(window.location.host + '/', window.location.host + '/#/');
					if ( !busyLoadingContent && hashPostUrl != window.location.href ) {
						$.History.go(hashPostUrl);
					}

					// don't execute href
					e.stopPropagation();
					return false;
				}
				else { // link to file
					// do nothing
				}
			}
			else { // other site
				// do nothing
			}
		},

		/**
		 * handleFormSubmit
		 * user has submitted a form.
		 */
		handleFormSubmit: function(e) {
			site.showDebugMessage('site.handleFormSubmit');

			// get post data
			var postData = {};
			var query = $(this).serializeArray();
			for ( i in query ) {
				postData[query[i].name] = query[i].value;
			}

			// load post
			loadPost($(this).attr('action'), postData);

			// stop from submitting
			e.stopPropagation();
			return false;
		},

		/**
		 * handleHistory
		 */
		handleHistory: function(state) {
			site.showDebugMessage('site.handleHistory');

			// ignore first post because initial postload somehow triggers this event
			if ( userIsAlive && !busyLoadingContent) {
				if ( !siteBackground.isSiteVisible() ) {
					siteBackground.fadeInSite();
				}

				// attempt 1 to find correct link and handle it, attempt 2 is in loadPost
				// links in nav-sub aren't loaded at this moment
				$('#site a[href$="' + state + '"]').first().each(function() {
					handleMenuClick($(this));
				});

				loadPost(siteUrl + state);
			}
		},

		/**
		 * handleWindowResize
		 */
		handleWindowResize: function() {
			site.showDebugMessage('site.handleWindowResize');
			siteBackground.resize();
		}

	}; // end public
}();

/**
 * siteBackground
 */
var siteBackground = function() {
	/* CONFIGURATION */
	var fadeDuration = 1000;
	var progressStartWidth = 146;
	var progressEndWidth = 546;

	/* PRIVATE */
	var flashEnabled = false;
	var flashLoaded = false;
	var busyLoading = false;
	var busyResizing = false;
	var busyFading = false;
	var initialBackground = {}; // temp var for flash
	var currentBackground = {};

	/**
	 * setBackgroundDescription
	 */
	function setBackgroundDescription(description) {
		site.showDebugMessage('bg.setBackgroundDescription: ' + description);

		if ( description != '' ) {
			$('#bg-image-info-description').html(description);
			if ( $('#bg-image-info').is(':hidden') ) {
				$('#bg-image-info').show();
			}
		}
		else {
			$('#bg-image-info').hide();
		}
	}

	return {
		/* PUBLIC */

		/**
		 * init
		 */
		init: function() {
			site.showDebugMessage('bg.init');

			// check for flash
			flashEnabled = swfobject.hasFlashPlayerVersion('9.0.0');

			// fade site when mouseclick or bg-image-info
			$('#bg-image-info').click(siteBackground.handleFadeClick);
			$('body').click(siteBackground.handleFadeClick);

			// bg-image-info-show hover
			$('#bg-image-info-show').hover(function() {
				$(this).addClass('hover');
			},
			function() {
				$(this).removeClass('hover');
			});

			if ( flashEnabled ) {
				var flashvars = { fadeDuration: fadeDuration/1000 };
				var params = { wmode: 'transparent' };
				var attributes = { allowscriptaccess: 'always', wmode: 'transparent' };
				swfobject.embedSWF('/wp-content/themes/biblionetid/swf/bg.swf', 'bg-image-swf', '100%', '100%', '9.0.0', '', flashvars, params, attributes);
			}
			else {
				// create needed dom-elements
				$('<img>').attr({ id: 'bg-image-js', src: '' }).appendTo('#bg-image-js-container');
				$('<img>').attr({ id: 'bg-image-js-dummy', src: '' }).appendTo('#bg-image-js-container');

				// trigger fadein when site-bg-image is loaded
				$('#bg-image-js').load(siteBackground.loaded);
			}
		},

		/**
		 * flashHasLoaded
		 * executed by swf when movie.
		 */
		flashHasLoaded: function() {
			site.showDebugMessage('bg.flashHasLoaded');

			flashLoaded = true;
			siteBackground.load(initialBackground);
		},

		/**
		 * load
		 */
		load: function(bg) {
			site.showDebugMessage('bg.load ' + bg.url);

			if ( bg.url != '' && currentBackground.url != bg.url ) {
				if ( busyLoading ) {
					siteBackground.stopLoading();
				}

				busyLoading = true;
				$('#bg-image-progress').css('width', progressStartWidth);
				$('#bg-image-progress').show();
				setBackgroundDescription('');

				if ( flashEnabled  ) {
					if ( flashLoaded ) {
						swf = swfobject.getObjectById('bg-image-swf');
						if ( swf ) {
							currentBackground = bg;
							swf.showImage(bg.url);
						}
					}
					else {
						initialBackground = bg;
						busyLoading = false;
					}
				}
				else {
					currentBackground = bg;

					var mainImage = $('#bg-image-js');
					var dummyImage = $('#bg-image-js-dummy');

					// copy to dummy
					if ( mainImage.attr('src') != '' ) {
						dummyImage.hide();
						dummyImage.width(mainImage.width());
						dummyImage.height(mainImage.height());
						dummyImage.css('top', mainImage.css('top'));
						dummyImage.css('left', mainImage.css('left'));
						dummyImage.attr('src', mainImage.attr('src'));
						dummyImage.show();
					}

					// hide & load new image
					mainImage.hide();
					mainImage.attr('width', bg.width);
					mainImage.attr('height', bg.height);
					mainImage.attr('title', bg.width + 'x' + bg.height);
					mainImage.attr('src', bg.url);
				}
			}
		},

		/**
		 * stopLoading
		 */
		stopLoading: function() {
			site.showDebugMessage('bg.stopLoading');

			if ( busyLoading) {
				if ( flashEnabled ) {
					var swf = swfobject.getObjectById('bg-image-swf');
					if ( swf ) {
						swf.stopLoading();
					}
				}
				else {
					$('#bg-image-js').attr('src', '/wp-content/themes/biblionetid/img/body-pixel.gif');
				}
				$('#bg-image-progress').hide();
				busyLoading = false;
			}
		},

		/**
		 * handleFadeClick
		 * user clicked left or right beside the site or on the background-description.
		 */
		handleFadeClick: function(e) {
			site.showDebugMessage('bg.handleFadeClick');

			if ( !busyLoading ) {
				if ( !busyFading ) {
				  if ( !siteBackground.isSiteVisible() ) {
						siteBackground.fadeInSite();
					}
					else {
						var targetId = e.target.id;
					  if (
					  	targetId == 'bg-image-info-show' ||
					  	targetId == 'header' ||
					  	targetId == 'site' ||
					  	targetId == 'content' ||
					  	targetId == 'bg-image-swf-container'
					  ) {
							siteBackground.fadeOutSite();
						}
					}
				}
			}

			e.stopPropagation();
		},

		/**
		 * loadProgress
		 */
		loadProgress: function(progress) {
			var w = progressStartWidth + (progress * ((progressEndWidth - progressStartWidth) / 100));
			$('#bg-image-progress').css('width', w);
		},

		/**
		 * loaded
		 * called when img has been loaded (javascript & flash).
		 *
		 */
		loaded: function() {
			site.showDebugMessage('bg.loaded');

			if ( !flashEnabled ) {
				// cache background by adding it to the DOM
				if ( $('#bg-image-js-cache img[src="' + $(this).attr('src') + '"]').size() == 0 ) {
					$('<img>').attr({ src: $(this).attr('src'), width: $(this).attr('width'), height: $(this).attr('height'), title: $(this).attr('title') }).appendTo('#bg-image-js-cache');
				}

		  	$(this).hide();
		  	siteBackground.resize();
		  	$(this).fadeIn(fadeDuration);
		  }

	  	setBackgroundDescription(currentBackground.description);
	  	$('#logo').attr('class', 'fade ' + currentBackground.logo_class);
	  	$('#bg-image-progress').hide();
	  	busyLoading = false;
		},

		/**
		 * resize
		 */
		resize: function() {
			if ( !busyResizing ) {
				site.showDebugMessage('bg.resize');

				busyResizing = true;

				var bg = $('#bg-image-js');
				var ratio = currentBackground.height / currentBackground.width;

				// browser window size
				var browserWidth = $(window).width();
				var browserHeight = $(window).height();

				// scale the image
				if ( (browserHeight / browserWidth) > ratio ) {
					bg.height(browserHeight);
					bg.width(browserHeight / ratio);
				}
				else {
					$(bg).width(browserWidth);
					$(bg).height(browserWidth * ratio);
				}

				// center image
				// bg.css('left', (browserWidth - bg.width()) / 2);
				// bg.css('top', (browserHeight - bg.height()) / 2);

				busyResizing = false;
			}
		},

		/**
		 * isSiteVisible
		 */
		isSiteVisible: function() {
			return ( $('#logo').css('display') == 'block' );
		},

		/**
		 * fadeInSite
		 */
		fadeInSite: function() {
			busyFading = true;
			$('.fade').fadeIn(fadeDuration, function() {
				busyFading = false;
			});
			$('#bg-image-info-description').hide();
			$('#bg-image-info-show').show();
		},

		/**
		 * fadeOutSite
		 */
		fadeOutSite: function() {
			busyFading = true;
			$('.fade').fadeOut(fadeDuration, function() {
				busyFading = false;
			});
			$('#bg-image-info-show').hide();
			$('#bg-image-info-description').show();

			var oldHeight = $('#bg-image-info-show').innerHeight();
			var newHeight = $('#bg-image-info-description').innerHeight();
			$('#bg-image-info-description').css('top', oldHeight + newHeight * -1);
		}

	}; // end public
}();

