if (document && document.execCommand) {
	try { document.execCommand("BackgroundImageCache",false,true); }
	catch (e) { }
};

function init() {
	$('div.brochure a, #printPageLink').click(function(e) {
		e.stopPropagation();
		e.preventDefault();
		window.open(this.href, 'popUpWin','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=yes,width=900,height=600');
	});

	if ($.ie6()) {
		$('#mainMenu > li').hoverClass('hover');
		$.ifixpng('assets/images/pixel.gif');
		$('#logoBig, #logoSmall, #popupClose, #logo4Gas img').ifixpng();
	}

	// Reset external link selection in case browser remembers last selection
	// and bind change event when user makes a selection to go the specified website
	$('#websiteLinks').val('').change(function() {
		window.location.href = $(this).val();
	});

	// SET THE GALLERY
	$.ewyseGallery.set({
		imgPath: 'assets/images/gallery/',
		maxHeight: 600,
		minHeight: 500,
		minWidth: 300,
		maxWidth: 900,
		borderSpace: 25,
		autoMaxDimension: true
	});
	
	$('.ewyse_collection:not(.collections),.ewyse_collection.collections .collection_item').each(function() {
		var $$ = $(this);
		$$
			.filter(':has(.collection_item_id)')
			.ewyseGallery('a.collection_item_viewLarger', 
				{
					mode: 'json',
					url: 'ajax/getdata.php?type=getCollectionImages&id=' + parseGetParameters($$.find('a.collection_item_id').attr('href'))['doc_id'],
					rewriteFunction: resizeImage
				}
			);
		$$.not(':has(.collection_item_id)').ewyseGallery('a.collection_item_viewLarger', {thumbnails: '.collection_item_image img', rewriteFunction: resizeImage});
	});
	
	$('.collection_item_image img').css('cursor', 'pointer').click(function() { $(this).parents('.collection_item:first').find('a.collection_item_viewLarger').trigger('click') } );
	
	// END GALLERY
	
	$('#mailpageForm').ajaxForm({dataType: 'json', success: processMailpageReply, beforeSubmit: beforeFormSubmit});
	$('#contactFormulier').ajaxForm({method: 'post', dataType: 'json', success: contactFormReply, beforeSubmit: beforeFormSubmit});
	
	$('#popupClose').click(function () { PopupMessage().hide(); });
	$('#mailButton').click(showMailpage);
	
	if (window.collectie > 0) $.getJSON('ajax/getdata.php?type=getCollectionImages&id=' + collectie, function (images) {
		if (images.length > 1) {
			alert(images.length);
			($.sfeerbeelden = {
				images: images,
				index: 0,
				img: $('#topImage'),
				showNext: function() {
					$.sfeerbeelden.index = $.sfeerbeelden.index < ($.sfeerbeelden.images.length - 1) ? $.sfeerbeelden.index + 1 : 0;
					preload($.sfeerbeelden.images[$.sfeerbeelden.index], showImage);
				},
				setTimeout: function() {
					window.setTimeout($.sfeerbeelden.showNext, 5000);
				}
			}).setTimeout();
		}
	});
	
	if (window.formResult) {
		setTimeout(function() {
			PopupMessage().showMessage(formResult.message);
			if (formResult.reply) $('#careersForm').submit(function(e) { e.stopPropagation(); e.preventDefault(); return false; });
		}, 0);
	}
};

$(init);

function showImage(img) {
	$.sfeerbeelden.img.fadeOut(1500, function() { $(this).remove(); });
	$.sfeerbeelden.img = $(img).css({display: 'none'}).addClass('topImage').appendTo('#imageLayer').center().fadeIn(1500);
	$.sfeerbeelden.setTimeout();
}

function preload(img, callback) {
	// Store the context, because THIS won't be available in callback functions
	var self = this;
	// If we already have an image object, check what to do with it.
	if (img.obj) {
		if (callback) {
			if (img.obj.complete) {
				callback.apply(self, [img.obj]);
				return;
			} else {
				$(img.obj).one('load', function(e) {
					callback.apply(self, [this]);
				});
				return;
			}
		}
	} else img.obj = new Image();

	if (callback) {
		$(img.obj).one('load', function(e) {
			callback.apply(self, [this]);
		});
	}
	
	// Store the currently used width and height, so we know when to reload the images
	img.obj.title = img.obj.alt = $.trim(img.title) || '';
	img.obj.src = img.src;
};

function contactFormReply(json, a, form) {
	$('.ajaxLoader').fadeOut('slow', function() {$(this).remove()});
	if (json.reply === false) form.add($('input:submit', form)).removeAttr('disabled');
	PopupMessage().showMessage(json.message);
}

function beforeFormSubmit(a, form) {
	if (form[0].id != 'mailpageForm') $('<img class=\"ajaxLoader\" src="assets/images/ajax-loader.gif" style=\"margin-left: 5px; display: none;\">').insertAfter($('input:submit', form)).fadeIn('fast');
	$(form).add($('input:submit', form)).attr('disabled','disabled');
}

function showMailpage() {
	$('#mailpageForm, #popupmessageSubmit').removeAttr('disabled');
	$('#mailpageForm').find('input[name^=recipient], textarea').val('');
	$('#popupmessageInfo').hide();
	PopupMessage().show('popupmessage');
	return false;
}

function processMailpageReply(json, a, form) {
	if (!json.result) $(form).add($('input:submit', form)).removeAttr('disabled');
	else setTimeout(function() { PopupMessage().hide(); }, 2500);
	$('#popupmessageInfo').css('color', json.result ? 'green' : 'red').html(json.message).fadeIn('fast');
	if (json.field) $('input[name="' + json.field + '"]').focus();
}

function parseGetParameters(url, noEnv) {
	if (!url) {
		if (noEnv) return {};
		url = window.location.href;
	}
	var array = {};
	if ((index = url.indexOf('?')) !== -1) {
		var args = url.substring(index + 1).split(/&amp;|&/);
		for (var i = 0; i < args.length; i++) {
			var arg = args[i].split('=');
			array[arg[0]] = (typeof(arg[1]) != 'undefined') ? arg[1] : '';
		}
	}
	return array;
};

function resizeImage(url, width, height) {
	var parts = url.split('?');
	var args = parseGetParameters(url, true);
	args['width'] = width;
	args['height'] = height;
	return $.makeURL(parts[0], args);
};
