$(init);

var currentURL = window.location.protocol + '//' + window.location.host + window.location.pathname;

if (!window.console) {
	window.console = {
		log: function() {}
	};
}

function init() {
	if ($.browser.msie){
		try {
			document.execCommand("BackgroundImageCache", false, true);
		}
		catch (err) {}
	}
	
	$('body').removeClass('nonJS').addClass('js');
	
	PopupMessage().set({lightboxButton: 'assets/images/buttons/close.png', width: 750});
	
	// Read more functionality
	var content = $('#contentWrapper'), contentHeight = content.height(); 
	$('#read_more').click(function() {
		if (content.hasClass('open')) {
			content.animate({height:contentHeight+'px'});
			$(this).html('Read more');
		} else {
			content.animate({height:content[0].scrollHeight+'px'});
			$(this).html('Read less');
		}
		content.toggleClass('open');		
	});
	
	$('#country_select').selectbox({'hideFirstItem' : true});
	$('#country_select').parent().find('.selectbox-wrapper li').click(function(){
        location = $(this).attr('id');
    });
	
	$('.collection_selectbox').selectbox().parent().find('input.collection_selectbox_submit').hide();
	$('form.collection_selectbox_form div.selectbox-wrapper li').click(function(){
       $(this).parents('form.collection_selectbox_form').submit();
    });
	
	$('.sfeer_home').each(function() {
    	var self = $(this),
			params = {output: 'json', retrieve: 'collectionview', view: self.metadata().view},
			target = self.find('ul.collection_items li');
			
		$('a.page', this).ajaxNav({
			target: target,
			hash: false,
			preload: false,
			fade: false,
			dimensional: false,
			createViewport: false,
			createWorkspace: true,
			fixViewport: true,
			processBackLinks: false,
			ajaxParams: params,
			classActive: 'activePage',
			find: 'ul.collection_items li'
		});
	});
	
	/*
	$('.media_centre li.collection_item a.collection_item_url')
		.click(function() {
			$(this).parent().parent().find('li.collection_item span.collection_item_no_url').slideUp();
			$(this).parent().find('span.collection_item_no_url').slideDown();
			return false;
		})
		.parent().parent().find('li.collection_item:not(.firstCollectionItem) span.collection_item_no_url').hide();
		//.parent().parent().parent().parent().find('.collection_innerWrapper li.firstCollectionItem a.collection_item_url').addClass('open');
	*/
	
	
	$('#divContent img:not(.media), #nav_img img').each(function(){
		var args = 'width=192&height=136';
		var src = $(this).attr('src').replace('img_T','img_L');
		//$(this).attr('src', $(this).attr('src') + '?' + args);
		src = src + '&' + args;
        var a = $('<a class="lightbox_image" />').attr('href', src);
        $(this).wrap(a);
	});
	
	$.ewyseGallery.set({
		imgPath: 'assets/images/gallery/',
		maxHeight: 467,
		minHeight: 467,
		minWidth: 697,
		maxWidth: 697,
		autoMaxDimension: true,
		fitImage: true,
		cacheAjaxRequests: true,
		flashparams: {height: 330}
	});

	$('div#print_mail_newsletter a.print').click(function(){
    	$('#mainContent').print({
    		css : 	"body { background-color: white !important; }" +
					"div.print_area { padding: 15px; }" +
					"div.print_area h1, div.print_area h2, div.print_area h3 { padding: 10px 0; } " +
    				"div.print_area span.image { float: left; margin-right: 10px; width: 282px; border: 1px solid #f2f2f2; } " +
    				"div.print_area ul.links { display: none; }"
    	});
    	return false;
    });
	
	$('img.media').flashembed();
	
	setTimeout('nextSfeerBeeld()', 5000);
	processContent(document);
}

function nextSfeerBeeld() {
	if($('#sfeerCollectionPane div.collection_navigation a.activePage + a.page').length > 0) {
		$('#sfeerCollectionPane div.collection_navigation a.activePage + a.page').trigger('click');
	} else {
		$('#sfeerCollectionPane div.collection_navigation a.page:first').trigger('click');
	}
	setTimeout('nextSfeerBeeld()', 5000);
}

function processContent(context) {
	context = $(context || this);
	
	$('div.captcha a').trigger('click');
	
	$('div.assets:not(.jq_gallery)', context).addClass('jq_gallery').each(function() {
		var id = $(this).attr('id').split('_'), args = {output: 'json', retrieve: 'collectionImages'};
		
		if($(this).metadata().view != 0) {
			args['view'] = $(this).metadata().view;
		} else {
			args['doc_id'] = $(this).metadata().col;
		}
		
		$('a.collection_item_url', this).ewyseGallery({rewriteFunction: resizeImage, mode: 'json', url: $.makeURL(rootURL, args)});
	});
	
	$('div.help:not(.processed)').addClass('processed').click(function() {
		if($(this).parent().find('div.text').css('display') == 'block') {
			$(this).parent().find('div.text').css('display', 'none');
		} else {
			$(this).parent().find('div.text').css('display', 'block');
		}
	});
	
	var form = $('form', context).not('.processed');
	form.find('input, textarea').example(function() {
		return $(this).metadata().example;
	});
	form.filter('#mailpageForm, #mailToContactForm, #sampleRequestForm').addClass('processed')
		.args({output: 'json', retrieve: 'data', data: ['missing', 'validated', 'error']})
		.ajaxForm({
			dataType: 'json',
			success: ajaxFormReply,
			beforeSubmit: beforeFormSubmit,
			iframe: true
		});
	
	$('a.lightbox, div#print_mail_newsletter a.mail, a.contact_me').lightbox({output: 'json', retrieve: 'content'}, {cache: true, onShow: processContent});
	
	$('a.lightbox_image').click(function() {
		PopupMessage().lightbox('<div class="imgDiv"><img src="' + resizeImage($('img',this).attr('src'), 733, 500) + '"></div>');
		return false;
	});
};

function lightboxImage(img) {
	PopupMessage().lightbox('<div class="imgDiv">' + img + '</img>');
}

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');
}

function ajaxFormReply(json, a, form) {
	$form = $(form);
	if (!json.validated) {
		$form.add($(':submit, :image', form)).removeAttr('disabled');
		if (json.missing && json.missing.length > 0) {
			$.each(json.missing, function() {
				var el = $(':input[name="' + this + '"]:not(.error)', form);
				if (el.length) {
					var error = el.metadata().error;
					//if (el.is(':radio') || el.is(':checkbox')) el = $(form).find('label[for="' + el.attr('id') + '"]:not(.error)');
					if (el.is(':radio')) {
						var newEl = $([]);
						el.each(function() {
							newEl = newEl.add($(form).find('label[for="' + this.id + '"]:not(.error)'));
						});
						el = newEl;
					}
					if (el.length) {
						var pos = el.position();
						if (error) {
							var message = $('<span class="errorMessage"/>')
								.text(error)
								.appendTo(el.parent())
								.css({
									position: 'absolute',
									left: pos.left + 5,
									top: pos.top - 5,
									cursor: 'pointer'
								}).one('click', function() {
									el.focus();
								});
						}
						el.addClass('error').one('focus click', function() {
							if (error) message.remove();
							el.removeClass('error');
						});
					}
				}
			});
			$('div.captcha a').trigger('click').parent().find('input').val('');
			//$.scrollTo('.error:first', 500, {easing: 'easeout'});
		} else PopupMessage().lightbox(json.message);
	} else PopupMessage().lightbox(json.message);
}

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);
}

(function(){
	jQuery.fn.print = function(options){
		//var o = $.extend({css:"",},options);
		var html = 	"<HTML>\n<HEAD>\n<style type='text/css'>\n"+
					options.css+"</style>"+
					$("head").html()+"\n</HEAD>\n<BODY>\n";
		this.each(function(i,e){
			html += "<DIV class=\"print_area\">\n"+
					$(e).html()+"</DIV>\n";
		});
			html += "</BODY>\n</HTML>";
		var printWP = window.open("","printWebPart", 'width=800,height=600,scrollbars=yes' );
		printWP.document.open();
		printWP.document.write(html);
		printWP.document.close();
		printWP.print();
		return false;
	};
})();
