(function ($) {
	$(document).ready(function () {
		$("#header li:first-child").addClass("first");
		$("#header li:last-child").addClass("last");
		$("#company-selector").sSelect();
		$("#tabs-container").tabs().tabs("option", "disabled", false);
		// start slideshow
		$('#tabs-container').auto_slideshow({ speed: 10000 });

		$("#banner-box .newsletterForm label").inFieldLabels();

		buildSidebarMenu();

		buildQuestionSection();

		hideEmptyElements();

		zebraStripesInDownloadTables();

		arrangeGalleryThubms();

		toggleBannerBox();

		activateGlossarOverlays();

		if ($("#fancyboxItems .item").length) {
			$("#fancyboxItems .item:lt(9)").addClass("itemsVisible");
		}
		if ($("#fancyboxItems .item").length > 9) {
			generateGalleryPaging();
		}

		// remove skype style phone numbers
		window.setTimeout(function () {
			$('.skype_pnh_container').html('');
			$('.skype_pnh_print_container').removeClass('skype_pnh_print_container');
		}, 750);


		$("#fancyboxItems li.item a").fancybox({
			"autoDimensions": false,
			"autoScale": false,
			"width": 700,
			"height": "auto",
			"overlayShow": true,
			"overlayColor": "#000",
			"overlayOpacity": 0.5,
			"showCloseButton": true,
			"showNavArrows": true,
			"padding": 15,
			"scrolling": "no"
		});

		if ($(".contactForm .EditingFormTable .allCategories input[type=checkbox]").length) {
			$(".contactForm .EditingFormTable .allCategories input[type=checkbox]").click(function () {

				$(this).parents("td.EditingFormValueCell").find("input[type=checkbox]").attr("checked", $(this).attr("checked"));
			});
		}

		paginateDownloads();

		// forward text on wigeogis page "senderkataster"
		if ($("#senderKataster").length) {
			setTimeout(
				function () {
					$("#senderKatasterForwardText").fadeOut(500, function () {
						$("#senderKataster").fadeIn(500);
					})
				}, 10000
			);

		}

		//news sidebar click
		$("li.news-sidebar")
			.css({ "cursor": "pointer" })
			.click(function (e) {
				var link = $(this).find(".inner h4 a"),
					target = $(this).hasClass("rss") ? "_blank" : "_self";
				e.preventDefault();
				e.stopPropagation();
				window.open($(link).attr("href"), target);
			});
	});


	function activateGlossarOverlays() {
		var offsetY = 0;
		if ($("span.glossarLink").length == 0)
			return;
		$("#main").append("<div class=\"glossarLinkOverlay\" />");
		offsetY = parseInt($("span.glossarLink:first").parent().offset().top - $("#main").offset().top) + 20;
		$("span.glossarLink").hover(function () {
			$("#main .glossarLinkOverlay").html($(this).find("span.glossarText").html()).css({ "top": ($(this).position().top + offsetY) }).show();
		},
			function () {
				$("#main .glossarLinkOverlay").hide();
			});
	}


	function generateGalleryPaging() {
		var pageLength = 9,
			itemsCount = $("#fancyboxItems .item").length,
			pagesCount = Math.ceil(itemsCount / 9);
		$("#main .box").append("<div class='PagerControl'><div class='PagerNumberArea' /></div>");
		for (var i = 1; i <= pagesCount; i++) {
			$("#main .box .PagerNumberArea").append(((i != 1) ? " | " : "") + "<a href='#'>" + i + "</a>");
		}
		$("#main .box .PagerNumberArea a:first-child").addClass("SelectedPage");
		$("#main .box .PagerNumberArea a").click(function (ev) {
			var pageNr = parseInt($(this).html()) - 1,
				visibleItemsStart = "",
				visibleItemsEnd = "";
			ev.preventDefault();
			if (pageNr > 0) visibleItemsStart = ":gt(" + ((pageNr * 9) - 1) + ")";
			visibleItemsEnd = ":lt(" + ((pageNr + 1) * 9) + ")";
			$("#main .box .PagerNumberArea a").removeClass("SelectedPage").parent().find("a:eq(" + pageNr + ")").addClass("SelectedPage");

			$("#fancyboxItems .item").removeClass("itemsVisible").parent().find("li" + visibleItemsEnd + visibleItemsStart).addClass("itemsVisible");
		});
	}


	function toggleBannerBox() {
		// toggle banner box button
		$("#banner-box .wide-frame .btnToggleBannerBox").click(function () {
			var targetHeight = 180,
				targetBgPosTop = "0";
			if ($("#banner-box").hasClass("big")) {
				targetHeight = 20;
				targetBgPosTop = "-100px";
			}
			$("#banner-box").animate({
				height: targetHeight,
				backgroundPosition: "0 " + targetBgPosTop
			}, 1000, function () {
				if ($("#banner-box").hasClass("big")) {
					$("#banner-box").removeClass("big");
				} else {
					$("#banner-box").addClass("big");
				}
			});
		});
	}


	function arrangeGalleryThubms() {
		$("#main .box .gallery .item:nth-child(3n+1)").css({ "clear": "left" });
	}


	function hideEmptyElements() {
		// hide bread-crumb if empty (required for ie)
		if ($("div.bct").length && $.trim($("div.bct").html()) == "") {
			$("div.bct").hide();
		}

		// hide empty headline and intro-box on faq-page
		if ($(".faq-wrapper h2").length && $.trim($(".faq-wrapper h2").html()) == "") {
			$(".faq-wrapper h2").hide();
		}
		if ($(".faq-wrapper .inner").length && $.trim($(".faq-wrapper .inner").html()) == "") {
			$(".faq-wrapper .inner").hide();
		}
	}


	function zebraStripesInDownloadTables() {
		//zebra-stripes for table rows (ie doesn't know about CSS3 tr:nth-child)
		$("#main .tbDownloads tr:even").addClass("even");
		$("#main .tbDownloads tr:odd").addClass("odd");
		$(".sidebar .SARteaser tr:even").addClass("even");
		$(".sidebar .SARteaser tr:odd").addClass("odd");
	}

	function buildSidebarMenu() {
		var menu = $("#sub-navigation");
		$("li > a", menu).wrap("<div class='item'></div>");
		$("li > .item", menu).prepend("<div class='arrow'>&nbsp;</div>");
		$("li:has(> ul) > ul", menu).hide();
		$("ul:has(.CMSListMenuHighlightedLI)").show();

		$("li:has(> ul) > .item > .arrow", menu).click(function () {
			var ul = $("> ul", $(this).parent().parent());
			var count = $("> ul:hidden", $(this).parent().parent()).length;

			if (count <= 0) {
				$(this).parent().removeClass("open");
				ul.hide();
			} else {
				$(this).parent().addClass("open");
				ul.show();
			}
		}).addClass("switch");

		$("div:has(> .CMSListMenuLinkHighlighted)").addClass("current").find("div.arrow.switch").trigger("click");
		$("li:has(> ul:visible) > .item", menu).addClass("open");
	}

	function buildQuestionSection() {
		$(".questions li div").hide();
		$(".questions li a.question-button").click(function (e) {
			if ($("~ .answer", this).is(":hidden")) {
				// hide all opened questions
				$(".questions li .answer:visible").hide();
				$(".questions li a.question-button").removeClass("opened");
				// show current one
				$("~ .answer", this).slideDown();
				$(this).addClass("opened");
			} else {
				$("~ .answer", this).slideUp();
				$(this).removeClass("opened").addClass("closed");
			}

			e.preventDefault();
			return false;
		});
	}

	var items = null;
	var max_page_items = 50;
	var pages = 0;
	var cur_page = 1;

	function paginateDownloads() {
		items = $(".download-area .tbDownloads tr:not(header)");
		pages = Math.ceil(items.length / max_page_items);

		// return if not on download page
		if (items.length <= 0 || pages <= 1) {
			return;
		}

		// building pagination
		items.hide();
		var pagination = $("<ul class='pagination'></ul>");
		for (var i = 0; i < pages; i++) {
			pagination.append("<li><a rel='" + (i + 1) + "' href='#p" + (i + 1) + "'>" + (i + 1) + "</a></li>");
		}
		pagination.prepend("<li class='prev' style='display:none'><a href='#p1' rel='1'>&lt;</a></li>");
		pagination.append("<li class='next'><a href='#p2' rel='2'>&gt;</a></li>");

		$(".pagination-container").append(pagination);
		$(".pagination-container .pagination a").live("click", function () {
			showPage($(this).attr("rel"));
		});

		// jump to first page
		showPage(1);
	}

	function showPage(p) {
		// set the page to a valid number
		p = (p < 1) ? 1 : p;

		// show only rows that are on the current page
		items.hide();
		var i = 0;
		var bottom = max_page_items * (p - 1);
		items.each(function () {
			if (i >= bottom && i < (max_page_items * p)) {
				$(this).show();
			}
			i++;
		});

		// show prev and next links
		if (p > 1) {
			var li = $(".pagination-container .pagination li.prev").show();
			var temp = parseInt(p) - 1;
			li.find("a").attr("href", "#p" + temp).attr("rel", temp);
		} else {
			$(".pagination-container .pagination li.prev").hide();
		}

		if (p < pages) {
			var li = $(".pagination-container .pagination li.next").show();
			var temp = parseInt(p) + 1;
			li.find("a").attr("href", "#p" + temp).attr("rel", temp);
		} else {
			$(".pagination-container .pagination li.next").hide();
		}

		$(".pagination-container .pagination li a.current").removeClass("current");
		$(".pagination-container .pagination li a[rel=" + p + "]").addClass("current");
	}

})(jQuery);

(function ($) {
	$.fn.auto_slideshow = function (options) {
		var opts = $.extend({}, $.fn.auto_slideshow.defaults, options);
		return this.each(function () {
			var $this = $(this),
				o = $.meta ? $.extend({}, opts, $this.data()) : opts,
				slideshowInterval;
			
			startSlideshow($this);

			$this
				.mouseover(function(){clearInterval($this.data('timer'));})
				.mouseout(function(){startSlideshow($this);});

			function startSlideshow(){
				$this.data('timer', setInterval(
					(function ($this) {
						return function () {
							show_next_slide($this);
						}
					})($this)
					, opts.speed)
				);
			}
		});
	};

	function show_next_slide(parent) {
		var current = parent.find('ul li.ui-state-active'),
			last = parent.find('ul li:last'),
			next = (last[0] == current[0]) ? parent.find('ul li:first') : current.next('li'),
			liCount = parent.find("li").length,
			lOffset = next.position().left + next.width();

		if (lOffset > 433){
			var lMargin = parseInt(parent.find("ul").css("margin-left"));
			parent.find("ul").css("margin-left", (lMargin-next.width()));
		}
		if (last[0] == current[0]) {
			parent.find("ul").css("margin-left", 0);
		}
		$("a", next).trigger("click");
	}

	$.fn.auto_slideshow.defaults = {
		speed: 1000
	};
})(jQuery);


/* iframe "handy-suche" as overlay */
$(function () {
	if ($('#handySuche').length !== 1 || $('.openHandySearch').length !== 1) {
		return;
	}
	if ($('#cover').length === 0) {
		$('body').append('<div id="cover" />');
	}
	if ($('#overlay').length === 0) {
		$('body').append('<div id="overlay" />');
	}
	$('#handySuche').hide();

	$('.openHandySearch').click(function (e) {
		e.preventDefault();
		$('html, body').css({ 'height': '100%', 'overflow-y': 'hidden' });
		$('#overlay')
			.html('<a href="#" class="closeHandySearchOverlay">schlie&szlig;en &nbsp; X</a><iframe frameborder="0" framespacing="0" src="' + $('#handySuche').attr('src') + '"></iframe>')
			.show();
		$('#cover').show();
		if ($(window).width() >= 1280) {
			$('#overlay').addClass('wide');
		}
	});
	$(window).resize(function () {
		if ($(window).width() >= 1280) {
			$('#overlay').addClass('wide');
		} else {
			$('#overlay').removeClass('wide');
		}
	});
	$('body').delegate('#cover, .closeHandySearchOverlay', 'click', function (e) {
		e.preventDefault();
		$('#cover, #overlay').hide()
		$('html, body').css({ 'height': 'auto', 'overflow': 'visible' });
	});
});
