//escape from frame
if (top!=self) top.location.replace(location.href);

$(document).ready(function(){
		defaultFocus();
		setMaxLength();
		initHelp();
		initBalloon();
		initDatePicker();
		initAltAsTitle();
		initThemeSelect();
		initFaq();
		initMenuPositionCheck();
		initWeblogSecurityDiv();
		initReadReceipt();
		initNewsEndDate();
		initCalendarEndDate();
		initNewsReadMore();
		initSlimBox();
		initNewsComment();
});


/* focus default input */
function defaultFocus() {
	$("input.focus").each(function() {
			//set focus
			$(this).focus();

			//position cursor at end
			this.value = this.value

			//select content if .select
			$(this).filter(".select").select();
	});
}


/* textarea maxlength */
function setMaxLength() {
	$("textarea[maxlength]").keypress(function(e) {
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;

			if ((code != 8) && (code != 9) && (code != 27) && (!((code >= 33) && (code <= 40))) && (code != 45) && (code != 46) && (code != 112) && (code != 116)) {
				if (this.value.length >= $(this).attr('maxlength')) {
					return false;
				}
			}
	});
}


/* questionmark button */
function initHelp() {
	$("#toggle_help").click(function(e) {
			$("#help").toggle("normal");
	});
}


/* check all checkboxes */
function toggleCheckBoxes(form) {
	checkAll(form, ($("form[name='" + form + "'] div.groupchecks input:checkbox:not(:checked)").length > 0))
}

function checkAll(form, check) {
	$("form[name='" + form + "'] div.groupchecks input:checkbox").each(function() {
			$(this).attr('checked', check)
	});
}


/* init balloon */
function initBalloon() {
	$("body").append("<div id='balloon'>TEST</div>");

	$("td")
	.filter(".data")
	//display balloon
	.mouseover(function(e){
			var offset = $(this).offset();
			var top = offset.top + 7 + "px";
			var left = offset.left + 31 + "px";

			$("#balloon")
			.html(eval('ballooncontent_' + $(this).attr('id')))
			.css("left", left)
			.css("top", top)
			.fadeIn("fast");
	})
	.end()
	.filter(":not(.data)")
	//hide balloon
	.mouseover(function(e){
			$("#balloon").hide();
	});

	$("td").mouseout(function(e){
			$("#balloon").hide();
	});

	$("img.help-popup")
	//display balloon
	.mouseover(function(e){
			var offset = $(this).offset();
			var top = offset.top + 7 + "px";
			var left = offset.left + 31 + "px";

			$("#balloon")
			.html(eval('ballooncontent_' + $(this).attr('id')))
			.css("left", left)
			.css("top", top)
			.fadeIn("fast");
	})

	$("img.help-popup").mouseout(function(e){
			$("#balloon").hide();
	});
}


/* init date picker */
function initDatePicker() {
	if (current_lang == 'de') {
		$.datepicker.regional.de = {
			closeText: 'schließen',
			prevText: '&#x3c;zurück',
			nextText: 'Vor&#x3e;',
			currentText: 'heute',
			monthNames: ['Januar','Februar','März','April','Mai','Juni',
				'Juli','August','September','Oktober','November','Dezember'],
			monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
				'Jul','Aug','Sep','Okt','Nov','Dez'],
			dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
			dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
			dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
			dateFormat: 'dd.mm.yy',
			firstDay: 1,
			isRTL: false,
			showMonthAfterYear: false,
			yearSuffix: ''};
		$.datepicker.setDefaults($.datepicker.regional.de);
	}
	else {
		$.datepicker.regional.nl = {
			closeText: 'Sluiten',
			prevText: '←',
			nextText: '→',
			currentText: 'Vandaag',
			monthNames: ['januari', 'februari', 'maart', 'april', 'mei', 'juni',
				'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
			monthNamesShort: ['jan', 'feb', 'maa', 'apr', 'mei', 'jun',
				'jul', 'aug', 'sep', 'okt', 'nov', 'dec'],
			dayNames: ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
			dayNamesShort: ['zon', 'maa', 'din', 'woe', 'don', 'vri', 'zat'],
			dayNamesMin: ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
			dateFormat: 'dd-mm-yy',
			firstDay: 1,
			isRTL: false,
			showMonthAfterYear: false,
			yearSuffix: ''};
		$.datepicker.setDefaults($.datepicker.regional.nl);
	}

	$('.datepicker').datepicker();
}

function initDatePicker_old() {
	/* Dutch (UTF-8) initialisation for the jQuery UI date picker plugin. */
	/* Written by Mathias Bynens <http://mathiasbynens.be/> */
	jQuery(function($){
			$.datepicker.regional.nl = {
				closeText: 'Sluiten',
				prevText: '←',
				nextText: '→',
				currentText: 'Vandaag',
				monthNames: ['januari', 'februari', 'maart', 'april', 'mei', 'juni',
					'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
				monthNamesShort: ['jan', 'feb', 'maa', 'apr', 'mei', 'jun',
					'jul', 'aug', 'sep', 'okt', 'nov', 'dec'],
				dayNames: ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
				dayNamesShort: ['zon', 'maa', 'din', 'woe', 'don', 'vri', 'zat'],
				dayNamesMin: ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
				dateFormat: 'dd-mm-yy', firstDay: 1,
				isRTL: false};
			$.datepicker.setDefaults($.datepicker.regional.nl);
	});

	$('.datepicker').datepicker();

	/*
	$("#datepicker").datepicker($.datepicker.regional['fr']);
	$("#locale").change(function() {
	$('#datepicker').datepicker('option', $.extend({showMonthAfterYear: false},
	$.datepicker.regional[$(this).val()]));
	});
	*/
}

/* alt-tag as title-tag -> IE8 */
function initAltAsTitle() {
	$("[alt]").each(function() {
			$(this).attr('title', $(this).attr('alt'))
	});
}


/* Header theme selection */
function initThemeSelect() {
	$('#theme_select').change(function(e) {
			var theme = this.value;

			if (mode=='school') {
				if (theme > '') {
					theme = 'url(\'/images/thema/' + theme + '.png\')';
				}
				else {
					theme = 'none';
				}

				$('#header').css('background-image', theme);
			}
			else {
				$('#style').removeClass('red');
				$('#style').removeClass('orange');
				$('#style').removeClass('yellow');
				$('#style').removeClass('green');
				$('#style').removeClass('blue');

				$('#style').addClass(theme);
			}
	})
}


function initMenuPositionCheck() {
	$('input.menuposition').click(function(e) {
			var id = $(this).attr('id')

			if (id == 'MenuLeftLeft') {
				$('#style').addClass('left');
			}
			else {
				$('#style').removeClass('left');
			}
	})
}


function initWeblogSecurityDiv() {
	$('#AagjeSecure').click(function(e) {

			if ($(this).attr('checked')) {
				jQuery('#WeblogSecureSettings').hide()
			}
			else {
				jQuery('#WeblogSecureSettings').show()
			}
	})
}


function initFaq() {
	$('.faq_link').click(function(e) {
			var id = $(this).attr('id')
			id = id.substring(9)

			$('.faq_category:not(#faq_category_' + id +')').slideUp()
			$('#faq_category_' + id).slideToggle()

	})
}

function initReadReceipt() {
	$('.readreceipt').click(function(e) {
			id = $(this).attr('id')
			id = id.substr(12, 10)

			$.getJSON(module_news_url + '?Action=MarkRead&NewsItemID=' + id, function(data) {
					id = data.NewsItemID

					if (id > "") {
						$("#readreceipt_" + id)
						.attr('id', '')
						.removeClass('readreceipt_unread')
						.children("img")
						.attr('src', '/images/news_readreceipt_read.png')
						.siblings("span")
						.html(lang_news_readreceipt_read)
					}
			});

			return false;
	});
}

function initNewsEndDate() {
	initEndDate("#OnlineOn", "#OfflineOn", true)
}

function initCalendarEndDate() {
	initEndDate("#DateStart", "#DateEnd", false)
}

function initEndDate(start, end, add) {
	$(start).change(function() {
			if (($(start).attr('value') > '') && ($(end).attr('value') == '')) {
				strdate = $(start).attr('value')
				date = new Date()

				if (current_lang == 'de') {
					date_separator = '.'
				}
				else {
					date_separator = '-'
				}

				arrdate = strdate.split(date_separator)

				if ((arrdate.length == 3) && (arrdate[0] > '') && (arrdate[1] > '') && (arrdate[2] > '')) {
					date.setDate(arrdate[0])
					date.setMonth(arrdate[1])
					date.setFullYear(arrdate[2])

					if (add) {
						date.setDate(date.getDate() + 1)
					}

					strdate = date.getDate() + date_separator + date.getMonth() + date_separator + date.getFullYear()
					$(end).attr('value', strdate)
				}

			}

	})
}

function initNewsReadMore() {
	$('a.readmore_expand').click(function() {
			var id = $(this).attr('id')
			$(this).hide()

			id = id.substring(16)

			$('#readmore_content_' + id).slideDown()

			return false;
	});

	$('a.readmore_collapse').click(function() {
			var id = $(this).attr('id')

			id = id.substring(18)

			$('#readmore_content_' + id).slideUp()
			$('#readmore_expand_' + id).show()

			return false;
	});

}

function initSlimBox() {
	if (current_lang == 'de') {
		lang_image = 'Bild {x} von {y}'
		lang_print = 'Drucken'
		lang_save = 'Speichern'
	}
	else {
		lang_image = 'Afbeelding {x} van {y}'
		lang_print = 'Afdrukken'
		lang_save = 'Opslaan'
	}

	$("a[rel^='lightbox']").slimbox({loop: true, overlayOpacity: 0.8, counterText: lang_image}, function(el) {
			return [el.href, '<a onclick="pageTracker._trackPageview(\'/print_weblog_photo\');" title="' + lang_print + '" href="/' + module_weblog_url + '/' + el.href.substring(el.href.lastIndexOf('/') + 1, el.href.lastIndexOf('.')) + '/print" id="lbPrintLink" target="_blank"></a><a title="' + lang_save + '" onclick="pageTracker._trackPageview(\'/save_weblog_photo\');" href="/' + module_weblog_url + '/' + el.href.substring(el.href.lastIndexOf('/') + 1, el.href.lastIndexOf('.')) + '/save" id="lbSaveLink"></a>' + el.title];
		}, function(el) {
			return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
	});
}


function initNewsComment() {
	$(".comment_form").submit(function(event) {
			event.preventDefault();

			var $form = $( this ),
			message = $.trim($form.find("textarea").val()),
			url = $form.attr("action");

			var id = $form.attr('id');
			id = id.substring(13);

			if (message > '') {
				$form.find("input[type='submit']").attr('disabled', true);

				$.post( url, { id: id, message: message },
					function(data) {
						if (data.success) {
							$form.remove();
							$("#comment_" + id).append(data.message);
						}
						else {
							alert(data.message);
							$form.find("input[type='submit']").attr('disabled', false);
						}
					},
					"json"
				);
			}
	});
}

