(function($) {
	$(document).ready(function () {

		/*
		 * ActiviteitControl is used for storing and retrieving activiteit data.
		 */
		var activiteitControl = {};

		activiteitControl.getActiviteit = function() {
			locs = activiteitControl.location.split("/");

			return locs[locs.length - 1];
		}

		activiteitControl.getUrl = function() {
			if(activiteitControl.location.indexOf("/index/activiteit/") == -1) {
				return activiteitControl.location + "/index/activiteit/" + activiteitControl.activiteit;
			}
			else return activiteitControl.location;
		}

		activiteitControl.location = window.location.href;
		activiteitControl.activiteit = activiteitControl.getActiviteit();

		/*
		 *	add datepicker control by class
		 */
		$('input.date').livequery(
			function () {
				$(this).datepicker();
			},
			function () {
				$(this).unbind();
			}
		);

		/*
		 *	remove hidden fields in questions
		 */
		$('.vraag input[@type=hidden]').livequery(function () {
			$(this).remove();
		}).remove();

		var loadContent = function (ret) {
			var first = "<body>";
			var last = "</body>"

			startPos = ret.indexOf(first) + first.length;
			endPos = ret.indexOf(last);

			if(startPos != -1 && endPos != -1) {
				str = ret.substr(startPos, endPos - startPos);
				var content = $('<div></div>').html(str).find('.content').eq(0).html();
				$('.content').html(content);
			}
		}

		/*
		 *	form uploader
		 */
		var autoSendForm = function (selector) {

			var baseData = $(selector).serialize();
			var sendFunction = function () {
				// check if the form has been changed (not necessarily the case in a change event...)
				var serialized = $(selector).serialize();
				if (serialized == baseData) {
					return;
				}
				baseData = serialized;

				// read form data
				var data = $(selector).formHash();

				// disable input elements
				$(selector + ' input').attr('disabled', 'disabled');

				// send to server
				$.post(window.document.location.href, data, function (ret) {
					loadContent(ret);
					jQuery.getScript("http://"+window.location.hostname+"/js/menu.js");
				});
				
			};
			var allQuestionsAnswered = function (o) {
				var questionsAnswered = true;
				$(':radio', o).each(function() {
					if(!$(":radio[@name='" + $(this).attr("name") + "']", o).is(":checked")) {
						questionsAnswered = false;
					}
				});

				if($(":checkbox", o).length && !$(":checkbox", o).is(":checked")) {
					questionsAnswered = false;
				}
				return questionsAnswered;
			}

			$(selector + ' input:text').livequery('change', sendFunction);
			$(selector).livequery(function() {
				$('div.questionBlock', this).each(function() {
					var block = this;
					$('div.default-answer a', block).click(function() {
						// create hash from questions within this block.
						var currentHash = $(':checkbox, :radio', block).serialize();
						// disable input elements.
						$(selector + ' input').attr('disabled', 'disabled');
						// append an action to be used serverside.
						switch ($(this).attr('class')) {
							case 'default-answer-remover':
								var action = 'delete';
								break;
							case 'default-answer-updater':
								var action = 'update';
								break;
							case 'default-answer-inserter':
								var action = 'insert';
								break;
						}
						// post hash + action + block.
						$.post(window.location.href, currentHash + '&do=' + action + '&block=' + $(this).attr('block'), function(data) {
							loadContent(data);
						});
						return false;
					});
					// if not all questions within this questionblock are answered, hide it.
					if (!allQuestionsAnswered(block)) {
						$('div.default-answer', block).hide();
					}
				});
				$(':checkbox, :radio', this).click(function(e) {
					sendFunction();
					return false;
				});
			});
		};

		autoSendForm('form.vragen');
		autoSendForm('form.aanvraagInput');

		/*
		 *	info sections for the aanvraag screen
		 */
		$('.aanvraagInfo .section').hide();
		var show = $("input[@name='sections[]']", this).fieldArray();
		for (var i = 0; i < show.length; i++) {
			$('.aanvraagInfo .section.' + show[i]).show();
		}
		$('.aanvraagInfoSections input').livequery('click', function () {
			var jq = $('.aanvraagInfo .section.' + this.value);
			if (this.checked) {
				jq.show('fast');
			} else {
				jq.hide('fast');
			}
		});

		/*
		 *	make the table sortable
		 */
		$.tablesorter.addParser({
	        id: 'dateDutch',
	        is: function(s) { return false; },
	        format: function(s) {
	            var d = s.replace(/^[0-9]{1,2}\-[a-z]{3}\-[0-9]{4}/, '$1').split(' ');
	            var monthMap = {
	            	'jan': '01', 'feb': '02', 'mrt': '03', 'apr': '04', 'mei': '05', 'jun': '06',
	            	'jul': '07', 'aug': '08', 'sep': '09', 'okt': '10', 'nov': '11', 'dec': '12' };
	            return d[2] + '-' + monthMap[d[1]] + '-' + d[0];
	        },
	        type: 'text'
	    });

		$('table.overzicht').tablesorter({
			cssAsc: 'overzichtHeaderSortAsc',
			cssDesc: 'overzichtHeaderSortDesc',
			cssHeader: 'overzichtHeader',
			headers: {
				1: { sorter: 'dateDutch' },
				2: { sorter: false },
				3: { sorter: false },
				4: { sorter: false }
			}
		});

		$('#activiteitenVerwijderen').click(function () {
			return confirm('Weet u zeker dat u alle activiteiten wilt verwijderen?');
		});

		/*
		 *	Will remove all question blocks when empty.
		 */
		$("input.date.hasDatepicker").livequery(function() {
			$("div.questionBlock").each(function() {
				if ($(this).find('div.vraag').length == 0) {
					$(this).remove();
				}
			});
		});


		/*
		 *	Facebox windows.
		 */
		$("a[rel*=facebox]").livequery("click", function() {
			var link = this;

			$.get($(this).attr("href"), function(data) {
				if($(".newWindow").length < 1) {
					var node = document.createElement("div");
					$(node).addClass("newWindow").css({zIndex: "3000", top: ($(document).scrollTop() + 150) + "px"}).html(data).appendTo("body");
				}
				else {
					$(".newWindow").css({ top: ($(document).scrollTop() + 150) + "px" }).html(data).show();
					$(".newWindow")[0].scrollTop = 0;
				}

				var hyperlink = $("a", $(".newWindow"));
				hyperlink.each(function() {
					if(!($(this).attr('target') == '_blank' || $(this).attr('target') == '_top')) {
						$(this).attr('target', '_blank');
					}
				});
			});

			return false;
		});

		$(".closeNewWindow").livequery("click", function() {
			$(".newWindow").hide();
		});

		/*
		 *	Change fontsize.
		 */
		var changeFz = true;
		$("#fontSizer").css({ cursor: "pointer" }).click(function() {
			var objs = $(".content, .content p, .content span, .content h1");

			if(changeFz) {
				objs.css("font-size", "110%");
				changeFz = false;
			}
			else {
				objs.css("font-size", "100%");
				changeFz = true;
			}
		});

		$(".searchViewMore").click(function() {
			$(".openSearchDoc").not($(this).parents("div:eq(0)").next("div:eq(0)")).removeClass("openSearchDoc").hide();
			$(this).parents("div:eq(0)").next("div:eq(0)").addClass("openSearchDoc").toggle("slow");
		});

		$('span.is-wabo').livequery('click', function() {
			var box = $('div.box-is-wabo');

			if (box.length < 1) {
				box = document.createElement('div');
				$(box)
					.addClass('box-is-wabo')
					.appendTo('body')
					.text('Dit is een aanvraag voor een Omgevingsvergunning. De aanvragen voor een Omgevingsvergunning kunnen soms apart worden ingediend en moeten soms tezamen worden ingediend. Dit is aan strikte regels gebonden en kan voor uw projectplanning van groot belang zijn. Laat u hierover adviseren door een deskundige.')
					.hide()
			}

			$(box).css({
				left: $(this).position().left - 50,
				top: $(this).position().top - 50
			}).fadeIn('normal');
		});

		$(document).click(function(e) {
			var target = e.target;
			if(!($(target).is('.box-is-wabo') || $(target).is('span.is-wabo'))) {
				$('.box-is-wabo').fadeOut('normal');
			}
		});

		$('div.how-to-use-vergunningentool a').click(function() {
			var self = this;

			$.get($(this).attr('href'), function(data) {
				var box = $('div.box-is-wabo');

				if (box.length < 1) {
					box = document.createElement('div');
					$(box)
						.addClass('box-is-wabo')
						.appendTo('body')
						.text($('div#content-part', data).text())
						.hide()
				}

				$(box).css({
					left: $(self).position().left - 50,
					top: $(self).position().top - 50
				}).fadeIn('normal');
			});

			return false;
		});
	});
})(jQuery);



