$(init);

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

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

function init() {
	var full = new Array();
	var i = 0;
	
	if ($.browser.msie){
		try {
			document.execCommand("BackgroundImageCache", false, true);
		}
		catch (err) {}
	}
    
	Cufon.replace('.cufon-header-white-1, .cufon-header-white-2, .cufon-date-white, #mainMenu li a span, #subMenu li a span, #centerCollectionPane h2.collection_title, #divContent h1');

	$('body').removeClass('nonJS').addClass('js');

    jQuery.each($('.google_maps'), function(){
        $(this)
        .after('<SMALL><A class="google_maps_link" style="color: rgb(0,0,255); text-align: left" href="'+$(this).attr('href')+'">Grotere kaart weergeven</A></SMALL>')
        .after('<iframe marginwidth="0" marginheight="0" frameborder="0" height="350" scrolling="no" width="425" src="'+$(this).attr('href')+'&output=embed">')
        .remove();
    });


    $('#aanmeld_link').replaceWith('<iframe class="iframeObject" frameborder="0" src="'+$('#aanmeld_link').attr('href')+'"></iframe>');

    $('.top-logos a, .google_maps_link').click(function(){
        window.open(this.href);
        return false;
    });
	
	// Set a global AJAX loader.
	var loader = $('<div class="ajaxLoader"/>').css('opacity', 0.4).hide().appendTo('body'), loaderTimer;
	$('body').ajaxStart(function() {
		clearTimeout(loaderTimer);
		loader.fadeIn();
	}).ajaxComplete(function() {
		clearTimeout(loaderTimer);
		loaderTimer = setTimeout(function() { loader.fadeOut(); }, 1000);
	}).ajaxError(function() {
		clearTimeout(loaderTimer);
		loaderTimer = setTimeout(function() { loader.fadeOut(); }, 1000);
	});

    $('.news, .downloads, .item_list').each(function() {
		var container = $(this), items = container.find('li'), active = false;

		function set(title, fold, active) {
			if (active) {
				title.removeClass('closed').addClass('open');
				fold.slideDown('slow', 'easeOutCubic');
			} else {
				title.removeClass('open').addClass('closed');
				fold.slideUp('slow', 'easeOutCubic');
			}
		}

		items.each(function() {
			var li = $(this), fold = li.find('span.collection_item_content').hide(), title = li.find('span.collection_item_no_url').addClass('closed');

			li.bind('foldOpen', function () { set(title, fold, true); });
			li.bind('foldClosed', function () { set(title, fold, false); });

			title.click(function() {
				if (active) active.trigger('foldClosed');
				if (active[0] != li[0]) active = li.trigger('foldOpen');
				else active = false;
			});
		});
	});
	
	$('.extraInfo:not(.open)').each(function() {
		$(this).find('.extraInfoButton').click(function() {
			$(this).parent('.extraInfo').addClass('open');
			$(this).siblings('.extraInfoContent').fadeIn('normal', function() {
				$(this).click(function() {
					$(this).fadeOut('normal', function() {
						$(this).parent('.extraInfo').removeClass('open').addClass('closed');		
					});					   
				});															
			});
		});									 
	});
	
	$('#programForm span.timeFrame').each(function() {
		$(this).slide($(this).next('div.checkbox_group'));							  
	});

	$('input:checkbox').click(function() {
		var frame = $(this).parent('.checkbox_group');
		var id = frame.attr('id');
		
		if ($(this).is(':checked')) {		
			full[id] = frame.parseTime();
			$(frame).addClass('checked');
			if ($(this).siblings('input').is(':checked')) {
				$(this).siblings('input:checked').attr('checked', false);	
				return;
			}
		}
		else {
			delete full[id];
			$(frame).removeClass('checked');
		}
		processForm(full);
	});
	
	$('input#generalSubmit').click(function(){
		var possibilties = $('form#programForm div.checkbox_group:not(.disabled, .checked)');
		if(possibilties.length > 0 || possibilties.length == 15) {
			return confirm("U heeft geen volledige keuze aangegeven in het formulier,  weet u zeker dat u uw keuze wilt versturen?");
		} else {
			return true;
		}
	});
}

function processForm(full) {
	$('#programForm div.checkbox_group:not(.checked)').each(function() {
		var disabalize = false;
		var time = $(this).parseTime();
		time.start = parseInt(time[0]);
		time.end = parseInt(time[1]);

		for(var index in full) {
			var reserved = full[index];
			reserved.start = parseInt(reserved[0]);
			reserved.end = parseInt(reserved[1]);

			if(time.start < reserved.start) {
				if (time.end > reserved.start) {
					disabalize = true;
				}
			}
			else if(time.start < reserved.end) {
				disabalize = true;
			}
		}
		if(disabalize) {
			$(this).disabalize();	
		}
		else {
			$(this).enabalize();	
		}
	});
}

$.fn.enabalize = function() {
	$(this).removeClass('disabled');
	$(this).prev('.timeFrame').slideShit($(this), true);
	$(this).children('input:checkbox:not(.full)').each(function() {
		$(this).enable();									 
	});
	$(this).prev().find('.notice').empty();
}

$.fn.disabalize = function() {
	if (!$(this).hasClass('disabled')) {
		$(this).addClass('disabled');
		$(this).prev('.timeFrame').slideShit($(this), false);
		$(this).children('input:checkbox').each(function() {
			$(this).disable();
		});
		$(this).prev().find('.notice').append('Een vorige keuze overlapt met dit tijdsdeel');
	}
}

$.fn.parseTime = function() {
	return $(this).attr('title').split('_');
}

$.fn.slideShit = function(subject, disable) {
	var $this = $(this);	
	
	if (disable) {
		subject.slideDown('normal', function() {
			$this.removeClass('closed').addClass('open');
		});
	}
	else {
		subject.slideUp('normal', function() {
			$this.removeClass('open').addClass('closed');	//text('Een vorige keuze overlapt met dit tijdsdeel');		
		});
	}
}

$.fn.slide = function(subject) {
	var $this = $(this);

	$this.click(function() {
		if ($this.hasClass('closed')) {
			subject.slideDown('normal', function() {
				$this.removeClass('closed').addClass('open'); 									  
			});	
		}
		else {
			subject.slideUp('normal', function() {
				$this.removeClass('open').addClass('closed');  
			});	
		}
	});					
}

function beforeFormSubmit(a, form) {
	$(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');
						});
					}
				}
			});
			//$.scrollTo('.error:first', 500, {easing: 'easeout'});
		} else PopupMessage().lightbox(json.message);
	} else PopupMessage().lightbox(json.message);
}