(function($) {

	var Blocker = function(el, options) {
		// Setup
		el = $(el);
		var plugin = this;
		var settings = $.extend({}, $.fn.blocker.defaults, options);
		var vars = { blockContentOpen: false };
		var postData;
		var supportOnhashchange = ('onhashchange' in window);
		var hoverButtons = ['btn-wat-voegt','btn-waar-benaderen','btn-wat-wordt','btn-archive'];

		// Find elements
		var blocks = el.children('.block');
		var buttons = blocks.filter('a');
		var blockHighlight = el.children('.block-highlight');
		var blockContent = el.children('.block-content');
		var content = blockContent.children('.content');
		var overview = content.find('.overview').first();

		// Initialize tiny scrollbar
		content.tinyscrollbar({ axis: 'y'});

		// Update scrollbar on click blockContent
		overview.click(function() {
			content.tinyscrollbar_update('relative');
		});

		var hashChange = function () {
			if ( ! window.location.hash || window.location.hash === '#') {
				plugin.showTemplate('page-template-default');
				vars.blockContentOpen = false;
				return;
			}

			var url = window.location.protocol+'//'+window.location.host+'/'+window.location.hash.replace('#', '');
//console.log('hashChangeFunction');
			overview.fadeOut().load(url, postData, function() {

				_gaq.push(['_trackPageview', '/'+window.location.hash.replace('#', '')]);

				postData = undefined;

				// Update scrollbar
				content.tinyscrollbar_update();

				// Fade in after load
				overview.fadeIn(700, function () {
					content.tinyscrollbar_update();
				});

				// Load clicked links with loadPage
				content.find('a:not([target="_blank"])').click(function (e) {
					if ($(this).attr('href') !== '#') {
						if ( ! $(this).hasClass('post-edit-link')) {
							plugin.loadPage($(this).attr('href'));
						}
					} else {
						content.tinyscrollbar_update('relative');
					}

					e.preventDefault();
				});
			});

			vars.blockContentOpen = true;
		};

		var changeHash = function (hash) {
			//console.log('changeHashFunction');
			window.location.hash = hash;
			if ( ! supportOnhashchange)
				hashChange();
		};

		// Dispatch hashchange event if hash is present
		if (window.location.hash && window.location.hash !== '#') {
			//console.log('firstHashChange');
			hashChange();
		}

		// Load new page on hash change
		$(window).bind('hashchange', function() {
			//console.log('hashChangeEvent');
			hashChange();
		});

		var getClassData = function(element, prefix, delimiter) {
			var data = [];
			var cls = $(element).attr('class');
			delimiter = delimiter || '-';
			var re = new RegExp('(?:^|\\s)'+prefix+delimiter+'(\\S+)', 'g');
			while (arr = re.exec(cls))
				data.push(arr[1]);
			return data.join(' ');
		};

		var blockMouseEnter = function(block, swap) {
			var top = (block.children('.text-1').html() === '') ? '41px' : undefined;
			block.children('img').fadeOut(350);
			//block.children('.text-'+(swap?0:1)).css({left: '200px', top: top}).animate({left: '0px'}, 300);
			//block.children('.text-'+(swap?1:0)).css({left: '-200px', top: top}).animate({left: '0px'}, 300);
			block.children('.text-'+(swap?0:1)).css({left: '0px', fontSize: '0px', top: top}).animate({fontSize: '13px'}, 300);
			block.children('.text-'+(swap?1:0)).css({left: '0px', fontSize: '0px', top: top}).animate({fontSize: '13px'}, 300);
		};

		var blockMouseLeave = function(block, swap) {
			var top = (block.children('.text-1').html() === '') ? '41px' : undefined;
			block.children('img').fadeIn(350);
			//block.children('.text-'+(swap?0:1)).animate({left: '200px', top: top}, 300);
			//block.children('.text-'+(swap?1:0)).animate({left: '-200px', top: top}, 300);
			block.children('.text-'+(swap?0:1)).animate({fontSize: '0px', top: top}, 300);
			block.children('.text-'+(swap?1:0)).animate({fontSize: '0px', top: top}, 300);
		};

		buttons.mouseenter(function() {
			if (vars.blockContentOpen)
				return;

			var button = $(this);

			if ($.inArray('btn-'+getClassData(button, 'btn'), hoverButtons) === -1)
				return;

			var row = parseInt(getClassData(button, 'row'));
			var col = parseInt(getClassData(button, 'col'));

			if (row > 2) row = 2;
			if (col > 6) col = 6;

			var startBlock = blocks.filter('.row-'+row+'.col-'+col);

			blockHighlight.hide().css({
				left: startBlock.css('left'),
				top: startBlock.css('top')
			}).fadeIn(300);

			blockMouseEnter(startBlock);
			blockMouseEnter(blocks.filter('.row-'+row+'.col-'+(col+1)));
			blockMouseEnter(blocks.filter('.row-'+(row+1)+'.col-'+col));
			blockMouseEnter(blocks.filter('.row-'+(row+1)+'.col-'+(col+1)), true);
		});

		buttons.mouseleave(function() {
			if (vars.blockContentOpen)
				return;

			var button = $(this);

			if ($.inArray('btn-'+getClassData(button, 'btn'), hoverButtons) === -1)
				return;

			var row = parseInt(getClassData(button, 'row'));
			var col = parseInt(getClassData(button, 'col'));

			if (row > 2) row = 2;
			if (col > 6) col = 6;

			var startBlock = blocks.filter('.row-'+row+'.col-'+col);

			blockMouseLeave(startBlock);
			blockMouseLeave(blocks.filter('.row-'+row+'.col-'+(col+1)));
			blockMouseLeave(blocks.filter('.row-'+(row+1)+'.col-'+col));
			blockMouseLeave(blocks.filter('.row-'+(row+1)+'.col-'+(col+1)), true);

			blockHighlight.fadeOut(300);
		});

		// Dispatch click event immediately instead of :hover on touch devices
		buttons.bind('touchend', function (e) {
			e.preventDefault();
			$(this).click();
		});

		// On button click load new page or show default template
		buttons.click(function() {
			var button = $(this).mouseleave();

			if (button.attr('href') === window.location.href.replace('#', '')) {
				changeHash('#');
			} else {
				plugin.loadPage(button.attr('href'));
			}

			return false;
		});

		var initHideShortcode = function () {
			var hideButton = $(document.createElement('a')).attr('href', '#').addClass('hide-shortcode-btn');
			var ellipsis = $(document.createElement('span')).html('...').addClass('hide-shortcode-ellipsis');
			var seperator = $(document.createElement('div')).addClass('hide-seperator');
			var seperatorIcon = $(document.createElement('div')).addClass('icon');
			seperator.append(seperatorIcon);

			hideButton.click(function () {
				var btn = $(this);

				if (btn.hasClass('open')) {
					btn.prev().children('.hide-shortcode').fadeOut('normal', function () {
						content.tinyscrollbar_update('relative');
						btn.removeClass('open').prev().children('.hide-shortcode-ellipsis').show();
					});
				} else {
					btn.addClass('open').prev().children('.hide-shortcode').fadeIn('normal');
					btn.prev().children('.hide-shortcode-ellipsis').hide();
				}

				return false;
			});

			content.find('.hide-shortcode').hide().after(ellipsis).parent().after(seperator).after(hideButton);
		};

		// Use this method to change hash
		this.loadPage = function(url, data) {
			//console.log('loadPageFunction');
			postData = data;
			var pathname = $(document.createElement('a')).attr('href', url).get(0).pathname;

			if (pathname.substr(0,1) === '/')
				pathname = pathname.substr(1);

			if (window.location.hash === '#'+pathname)
				hashChange();
			else
				changeHash('#'+pathname);
		};

		this.showTemplate = function(name) {

			// Activate button
			buttons.removeClass('active');
			buttons.filter('.btn-'+name.substring(18, name.length - 4)).addClass('active');

			// Init hide shortcode
			initHideShortcode();

			// Get all stylesheet rules
			var rules = document.styleSheets[0].cssRules || document.styleSheets[0].rules;

			for (var i in rules) {
				if (rules[i].selectorText)
				{
					// Construct new template style selector
					var selector = '.'+name+' .blocks';

					// Try to find the new template styles
					if (rules[i].selectorText.substr(0, selector.length) === selector) {
						var animClass = rules[i].selectorText.substr(selector.length + 1);
						var animStyle = rules[i].style;

						// Animate block-content and buttons to new template styles
						if (animClass === '.block-content') {
							blockContent.css({
								background: animStyle.background || '',
								left: animStyle.left || undefined,
								top: animStyle.top || undefined,
								width: animStyle.width || undefined,
								height: animStyle.height || undefined
							});

							if (animStyle.display === 'none') {
								blockContent.fadeOut();
							} else {
								blockContent.fadeIn();
							}
						} else {
							var block = blocks.filter(animClass);

							if (animStyle.display !== 'none')
								block.show();

							block.animate({
								opacity: (animStyle.display === 'none') ? 0 : 1,
								left: animStyle.left || undefined
							}, settings.animSpeed, function(){
								if ($(this).css('opacity') === '0')
									$(this).css('display', 'none');
							});
						}
					}
				}
			}
		};

		return plugin;
	};

	$.fn.blocker = function(options) {
		return this.each(function() {
			var el = $(this);
			if ( ! el.data('blocker')) {
				//console.log('init');
				var blocker = new Blocker(this, options);
				el.data('blocker', blocker);
			}
		});
	};

	$.fn.blocker.defaults = {
		animSpeed: 700
	};

})(jQuery);
