// JavaScript Document
if (document && document.execCommand) {
	try { document.execCommand("BackgroundImageCache",false,true); }
	catch (e) { }
};

$.ie6() ? $(window).ready(init) : $(init);

function init() {

	if ($.ie6()) {
		$.ifixpng('assets/images/pixel.gif');
		$('#logo, #maildoorLink, #bookletLink img, #bgHelperExtra, .polaroids li.collection_item img, a.followOnTwitter img, a.followOnLinkedin img').ifixpng();
	}
	
	// Make the footer openable and closable
	$('#footerLayer').each(function() {
		var self = $(this), opened = true;

		var button = self.find('#toggleFooter').click(function() {
			opened ? toggleClose() : toggleOpen();
		});
		
		function toggleOpen (callback) {
			opened = true;
			button.find('span').attr('class', 'open');
			$('#contentLayer').css('marginBottom', 172);
			self.stop().animate({bottom: -20}, 600, 'easeOutExpo', callback);
		}
		
		function toggleClose(callback) {
			opened = false;
			button.find('span').attr('class', 'closed');
			$('#contentLayer').css('marginBottom', 60);
			self.stop().animate({bottom: 0}, 300, 'easeOutCubic').animate({bottom: -120}, 1200, 'easeOutBounce', callback);
		}
		
		setTimeout(function() {
			toggleClose(function() {
				button.fadeIn();
			});
		}, 2000);
	});

	
	// Set a global AJAX loader.
	var loader = $('<div class="ajaxLoader"/>').hide().appendTo('body'), loaderTimer;
	$('body').ajaxStart(function() {
		clearTimeout(loaderTimer);
		loader.fadeIn();
	}).ajaxComplete(function() {
		clearTimeout(loaderTimer);
		loaderTimer = setTimeout(function() { loader.fadeOut(); }, 1000);
	}).ajaxError(function() {
		PopupMessage().lightbox("<h2>Oops!</h2><p>We apologise.. something went wrong!</p><p>You can contact us at <a href=\"mailto:info@ilovemyitdepartment.com?subject=Probleem op pagina: " + ($('#contentLayer .contentBlockWrapper:visible a.activeItem').attr('href') || $('#menuTopWrapper a.activeItem').attr('href')) + "\">info@ilovemyitdepartment.com</a> to let us know about the problem!</p>");
		clearTimeout(loaderTimer);
		loaderTimer = setTimeout(function() { loader.fadeOut(); }, 1000);
	});
	
	// lightbox links
	$('#maildoorLink, #tipsLink').lightbox({onShow: processContent});
	
	// Init the main ajax navigation
	$('body').addClass('js');
	$('#menu a').ajaxNav({
		target: '#contentLayer > div.contentBlockWrapper',
		root: rootURL,
		trackGA: true,
		createWorkspace: true,
		subMenu: 'div.subMenu a.level1',
		onShow: processContent,
		ajaxParams: {retrieve: 'template', output: 'json'},
		keyNav: true,
		windowResize: true,
		callback: function() {
			if (window.addthis) {
				if (window.addthis.ost) {
					window.addthis.ost = 0;
					window.addthis.ready();
				}
			}
			$.addthis();
		}
	});
	
	$.addthis();
	
	// Process the current content page
	processContent.apply($('div.contentBlockWrapper'));
	
	// For css awareness
	$('body').addClass('js');

	// Close link of lightbox
	$('#lightboxCloseLink').click(function() {
		PopupMessage().hide();
	});
	
	setTimeout(function() {
		$('#logo').hover(
			function() {
				$(this).stop().animate({top: '-10px'}, 'normal', 'easeOutQuad');
			}, function() {
				$(this).stop().animate({top: '-30px'}, 'normal', 'easeOutQuad');
			}
		).animate({top: '-30px'}, 'normal', 'easeout');
		
		if (!$.ie6()) $('#hateLogo').hover(
			function() {
				$(this).stop().animate({marginBottom: '-120px'}, 'normal', 'easeOutQuad');
			}, function() {
				$(this).stop().animate({marginBottom: '-150px'}, 'normal', 'easeOutQuad');
			}
		).animate({marginBottom: '-150px'}, 'normal', 'easeOutQuad');
	}, 2000);
}

function processContent() {
	var nav, field;
	if ((nav = $('#homepageCollectionPane div.collection_navigation')).length) {
		$('a.page', nav).ajaxNav({
			target: '#homepageCollectionPane ul',
			createWorkspace: true,
			fixViewport: true,
			onShow: processContent,
			classActive: 'activePage',
			ajaxParams: {output: 'json', retrieve: 'pane', pane: 'homepageCollectionPane'},
			find: 'ul',
			hash: false,
			buttons: {left: 'assets/new/buttons/left.png', right: 'assets/new/buttons/right.png'}
		});
	}
	
	$('a.lightbox_link').lightbox({onShow: processContent});

	$('div.polaroids a:not(.processed)', this).addClass('processed').wrap('<span class="js"/>').each(function() {
		var self = $(this), short = self.find('span.collection_item_short');
		short.show();
		setTimeout(function() {
			short.fadeOut(function() {
				self.hoverIntent(function() {
					short.stop().fadeIn(500);
				}, function() {
					short.fadeOut(500);
				});
			});
		}, 2000);
	});
	
	$('#bookletForm', this).not('.processed').addClass('processed').ajaxForm({dataType: 'json', success: ajaxFormReply, beforeSubmit: beforeFormSubmit});
	//$('img', this).ifixpng();
	$('div.download-posters ul li').hoverClass('hover').children('span[class^=helper]').ifixpng();
		//$('div.download-posters ul li')
	
	$('form', this).not('.processed, #loginForm, #orderForm').addClass('processed')
		.args({output: 'json', retrieve: 'data', data: ['missing', 'validated', 'error']})
		.ajaxForm({dataType: 'json', success: ajaxFormReply, beforeSubmit: beforeFormSubmit});
		
	processForm();
}

function processForm() {
	$('form#orderForm:not(.processed)')
		.addClass('processed')
		.args({output: 'json', retrieve: 'data', data: ['missing', 'validated', 'error']})
		.ajaxForm({dataType: 'json', success: ajaxFormReply2, beforeSubmit: beforeFormSubmit, timeout: 60000})
}
function ajaxFormReply2(json, a, form) {
	$form = $(form);
	$form.find('.ajaxLoader').fadeOut('slow', function() { $(this).remove(); } );
	setTimeout("$('div.please_wait').fadeOut('slow', function() { $(this).remove(); } )", 1000);
	if (!json.validated) {
		$form.add($(':submit, :image', form)).removeAttr('disabled');
		if (json.missing && json.missing.length > 0) {
			$.each(json.missing, function() {
				var el = $('[name="' + this + '"]:not(.error)', form);
				if (el.length) {
					var error = el.metadata().error;
					textarea = $(form).find('textarea#' + el.attr('id'));
					input = $(form).find('input#' + el.attr('id'));
					sel = $(form).find('select#' + el.attr('id'));
					
					if (el.is('textarea')) {
						var css = textarea.position();
						css.left += textarea.outerWidth() + 5;
					} else if (el.is('select')) {
						var css = sel.position();
						css.left += sel.outerWidth() + 5;
					} else {
						var css = input.position();
						css.left += input.outerWidth() + 5;						
					}
					css.position = 'absolute';
					css.cursor = 'pointer';
					if (error) {
						var message = $('<span class="errorMessage"/>')
							.text(error)
							.appendTo(el.parent())
							.css(css)
							.click(function() {
								el.focus();
							});
					}
					el.addClass('error').one('focus click', function() {
						if (error) message.remove();
						$(this).removeClass('error');
					});
				}
			});
		}
	} else PopupMessage().lightbox(json.message);
}

function ajaxFormReply(json, a, form) {
	//$('img.ajaxLoader', form).fadeOut('slow', function() {$(this).remove()});
	if (json.reply === false || json.validated === false) form.add($(':submit, :image', form)).removeAttr('disabled');
	else setTimeout(function() {
		PopupMessage().hide();
	}, 2500);
	if (form.is('#mailpageForm') || form.is('#suggestieForm')) $('.popupmessageInfo', form).css('color', json.reply ? 'green' : 'red').html(json.message).fadeIn('fast');
	else {
		PopupMessage().lightbox(json.message);
	}
	if (json.field) $('input[name="' + json.field + '"]', form).focus();
}

function beforeFormSubmit(a, form) {
	//$('<img class=\"ajaxLoader\" src="assets/images/ajax-loader.gif">').insertAfter($('input:submit', form)).fadeIn('fast');
	$(form).add($(':submit, :image', form)).attr('disabled','disabled');
}

// Returns an array with either the current get-arguments or the get-arguments of the given url.
function parseGetParameters(url, noEnv) {
	var array = {}, index, args, arg, i, key;
	if ((url || (!noEnv && (url = window.location.search))) && (index = url.indexOf('?')) !== -1) {
		args = url.substring(index + 1).split(/&amp;|&/);
		for (i = 0; i < args.length; i++) {
			arg = args[i].split('=');
			// Remove the first entry; it's our key in this pair
			key = arg.shift();
			// If the value also contains unencoded '=' signs, we save the value by rejoining the remainings
			arg = arg.join('=');
			array[key] = (typeof(arg) != 'undefined') ? decodeURIComponent(arg) : '';
		}
	}
	return array;
};

// Show a link in a lightbox
$.fn.lightbox = function(options) {
	this.filter('a:not(.processedLink)').addClass('processedLink').each(function() {
		$(this).bind('click', function(e) {
			e.preventDefault();
			if ($.fn.metadata) options = $.extend({}, options, $(this).metadata());
			openLinkInLightbox(this.href, options);
		});
	});
	return this;
}

$.fn.args = function(args) {
	return this.each(function() {
		if (/FORM|A/.test(this.nodeName)) {
			var url = this.href || this.action, index;
			var oldArgs = parseGetParameters(url);
			if ((index = url.indexOf('?')) > -1) url = url.substring(0, index || url.length);
			args = $.extend({}, oldArgs, args);
			$(this).attr(this.nodeName == 'FORM' ? 'action' : 'href', $.makeURL(url, args));
		}
	});
}

function openLinkInLightbox(href, options, doNotStack) {
	options = options || {};

	var base = href.split('?')[0], args = parseGetParameters(href), url;
	$.extend(args, {output: 'json', retrieve: 'content'});
	url = $.makeURL(base, args);
	
	$.getJSON(url, function(json) {
		try { pageTracker._trackPageview(json.name); } catch (e) { if (window.console) console.log("Tracking error in AJAX page '" + json.name + "': " + e); }
		PopupMessage().lightbox(json.content, options);
	});
}