var timeouts = new Object();
var cookie_ablauf = 30;	// 30 Tage
var objExpandableDivs = { Pressestimmen:1, Veranstaltungen:5, Mediatheksbeitraege:1, News:1, Preise:1 };

// resize the main fonts
function resizeFont (offset) {
	var sizes = new Array ('smaller', 'small', 'normal', 'big', 'bigger');
	var $obj = $('#page');
	var actual_size = Math.floor(sizes.length / 2);
	var new_size = actual_size + offset;
	for (var i = 0; i < sizes.length; i++) {
		if ($obj.hasClass('size_' + sizes[i])) {
			actual_size = i;
			if (i + offset >= 0 && i + offset < sizes.length) {
				new_size = i + offset;
			} else {
				new_size = i;
			}
		}
	}
	$obj.removeClass('size_' + sizes[actual_size]).addClass('size_' + sizes[new_size]);
	createCookie("FONTSIZE",sizes[new_size],cookie_ablauf);
	$("#fontsize a[rel='smaller'], #fontsize a[rel='bigger']").fadeTo("fast",1);
	if (new_size == 0) {
		// kleiner gehts nimmer
		$("#fontsize a[rel='smaller']").fadeTo("fast",0.3);
	} else if (new_size == sizes.length - 1) {
		// größer gehts nimmer
		$("#fontsize a[rel='bigger']").fadeTo("fast",0.3);
	}
//	$(".expandableText").each(function(){isExpandableText($(this));});
// jQuery.each(objExpandableDivs, function(type, anzahl) { $(".expandable" + type).each(function(){isExpandableDiv($(this), type, anzahl);}); } );
}

// Texte ein und ausblenden
function expandToggle(e,org,exp,txt_lo,txt_hi) {
	var animationTime = 600; // millisekunden
	var $element = $(e).parent().parent().children(".expandableText");
	if(txt_hi.match(/Mediatheksbeitraege/)) 
		txt_hi = "Alle Mediatheksbeitr&auml;ge &raquo;";
	if($element.children(".shorttext").length > 0 && $element.children(".longtext").length > 0 && $element.children(".shorttext").height()!=null) {
		if($element.children(".longtext").css("display") == "none") {
			$element.children(".shorttext").hide();
			$element.children(".longtext").css({height:org+"px"}).show().animate({ height:exp }, animationTime ,"swing",function(){$(this).css({height:"auto"})});
			if (txt_lo && txt_hi) $(e).html(txt_lo);
		} else {
			$element.children(".longtext").animate({ height:org }, animationTime ,"swing",function(){
				$(this).hide();
				$element.children(".shorttext").show();
			});
			if (txt_lo && txt_hi) $(e).html(txt_hi);
		}
	} else {
		var $element = $(e).parent().parent().children("div:first");
		if ($element.height() == org) {
			$element.animate({ height:exp }, animationTime ,"swing",function(){$(this).css({height:"auto"})});
			if (txt_lo && txt_hi) $(e).html(txt_lo);
		} else {
			$element.animate({ height:org }, animationTime, "swing" );
			if (txt_lo && txt_hi) $(e).html(txt_hi);
		}
	}
/*
	$element.children(".longtext").slideDown(10000,function(){
		var $element = $(e).parent().prev().children("div:first");
		if($element.children(".shorttext") && $element.children(".longtext")) {
			if($element.children(".longtext").css("display") == "none") {
				$element.children(".shorttext").hide();
				$element.children(".longtext").show();
				if (txt_lo && txt_hi) $(e).html(txt_lo);
			} else {
				$element.children(".longtext").hide();
				$element.children(".shorttext").show();
				if (txt_lo && txt_hi) $(e).html(txt_hi);
			}
		}
	})
*/
	$(e).blur();
	return false;
}

function isExpandableText (obj) {
	if(obj.children(".shorttext").length > 0 && obj.children(".longtext").length > 0) {
		var $longHeight = obj.children(".longtext").outerHeight();
		if ($longHeight > 0) {
			var $shortHeight = obj.children(".shorttext").outerHeight();
			obj.children(".longtext").hide();
			obj.children(".shorttext").show();
			obj.parent().append("<div class=\"link_expand\"><a href='#' class=\"link_inverted\" onclick=\"return expandToggle(this," + $shortHeight + "," + $longHeight + ",'&laquo;&nbsp;weniger','ausf&uuml;hrlich&nbsp;&raquo;')\">ausf&uuml;hrlich&nbsp;&raquo;</a></div>");
		}
	}
/*
	var $expanded = obj.height();
	var $original = obj.parent().height();
	if (obj.parent().parent().children(".link_expand").length > 0) {
		if ($original+10 < $expanded) {
			obj.parent().parent().children(".link_expand").html("<a href='#' class=\"link_inverted\" onclick=\"return expandToggle(this," + $original + "," + $expanded + ",'&laquo; weniger','ausf&uuml;hrlich &raquo;')\">ausf&uuml;hrlich &raquo;</a>");
		} else {
			obj.parent().parent().children(".link_expand").remove();
		}
	} else {
		if ($original+10 < $expanded) {
			obj.parent().parent().append("<div class=\"link_expand\"><a href='#' class=\"link_inverted\" onclick=\"return expandToggle(this," + $original + "," + $expanded + ",'&laquo; weniger','ausf&uuml;hrlich &raquo;')\">ausf&uuml;hrlich &raquo;</a></div>");
		}
	}
*/
}

function isExpandableDiv (obj,type,anzahl) {
	if (type == "Mediatheksbeitraege") type = "Mediatheksbeitr&auml;ge";
	if (!anzahl) anzahl = 1;
	var $expanded = obj.outerHeight();
	var $original = 0;
	if(obj.children("#listNews").length)
		obj.children("#listNews").children("div").each(function(i) { if (i < anzahl) $original += $(this).height(); });
	else
		obj.children("div").each(function(i) { if (i < anzahl) $original += $(this).outerHeight(); });
	if ($original+10 < $expanded) {
		$(obj).height($original).css("overflow", "hidden");
		if (obj.parent().find(".link_expand").length == 0) {
			obj.parent().append("<div class=\"link_expand p10\"><a href='#' class=\"link_inverted\" onclick=\"return expandToggle(this," + $original + "," + $expanded + ",'&laquo; weniger','Alle " + type + " &raquo;')\">Alle " + type + " &raquo;</a></div>");
		} else {
			obj.parent().find(".link_expand").replaceWith("<div class=\"link_expand p10\"><a href='#' class=\"link_inverted\" onclick=\"return expandToggle(this," + $original + "," + $expanded + ",'&laquo; weniger','Alle " + type + " &raquo;')\">Alle " + type + " &raquo;</a></div>");
		}
	}
}


// Merkzettel aktualisieren, ein und ausblenden
function initDoMerkzettel () {
	var elements_array = new Array("titel", "personen", "veranstaltungen");
	for(var x = 0; x < elements_array.length; x++) {
		var element_typ = elements_array[x];
		$("#doMerkzettel[title^=" + element_typ + "]").each(function(){
			var cookie_array = readCookie("MERKZETTEL_" + element_typ.toUpperCase()).split(",");
			var element_id = $(this).attr("title");
			element_id = eval('element_id.replace(/' + element_typ + '_/, "")');
			if(jQuery.inArray(element_id,cookie_array) >= 0) {
				$(this).append("<span class=\"link_merkzettel_off\">Gemerkt</span>");
			} else {
				$(this).append("<a href='#' class=\"link_inverted link_merkzettel\" onclick=\"return addToMerkzettel(" + element_id + ",'" + element_typ + "')\">Merken</a>");
			}
		});
		$(".kachel_link_merken[name^=" + element_typ + "]").each(function(){
			var cookie_array = readCookie("MERKZETTEL_" + element_typ.toUpperCase()).split(",");
			var element_id = $(this).attr("name");
			element_id = eval('element_id.replace(/' + element_typ + '_/, "")');
			if(jQuery.inArray(element_id,cookie_array) >= 0) {
				$(this).replaceWith("<span class=\"kachel_link_gemerkt\">Gemerkt</span>");
			} else {
				$(this).replaceWith("<a href='#' class=\"kachel_link_merken\" name=\"" + element_typ + "_" + element_id + "\" onclick=\"return addToMerkzettel(" + element_id + ",'" + element_typ + "',true)\">Merken</a>");
			}
		});
	}
}

function addToMerkzettel (id,type,classes) {
	var name = "MERKZETTEL_" + type.toUpperCase();
	var value = readCookie(name);
	if (!classes) var classes = false;
	if(value.length > 0) value += ",";
	value += id;
	createCookie(name,value);
	// Anzahl erhöhen
	value = readCookie("MERKZETTEL");
	if(value >= 0) value++; else value = 1;
	createCookie("MERKZETTEL",value);
	if (value == 1) $("#merkzettel > h3 > a").html("Sie haben einen gemerkten Eintrag &raquo;");
		else $("#merkzettel > h3 > a").html("Sie haben "+ value +" gemerkte Eintr&auml;ge &raquo;");
	// "Vormerken" schreiben
	if (classes == true) {
		$(".kachel_link_merken[name=" + type + "_" + id + "]").replaceWith("<span class=\"kachel_link_gemerkt\">Gemerkt</span>");
	} else {
		$("#doMerkzettel > a").replaceWith("<span class=\"link_merkzettel_off\">Gemerkt</span>");
	}
	toggleMerkzettel("show");
	return false;
}

function deleteFromMerkzettel (id,type) {
	var name = "MERKZETTEL_" + type.toUpperCase();
	var value = readCookie(name);
	value = jQuery.grep(value.split(","), function (a) { return a != id; });
	createCookie(name,value.join(","));
	// Div mit dem Element löschen
	$("#merkzettel_" + type + "_" + id).slideUp();
	if(value.length == 0) {
		$("#merkzettel_" + type).slideUp();
	}
	// Anzahl verkleinern
	value = readCookie("MERKZETTEL");
	if(value >= 1) value--; else value = 0;
	createCookie("MERKZETTEL",value);
	if(value > 0)
		if (value == 1) $("#merkzettel > h3 > a").html("Sie haben einen gemerkten Eintrag &raquo;");
			else $("#merkzettel > h3 > a").html("Sie haben "+ value +" gemerkte Eintr&auml;ge &raquo;");
	else
		toggleMerkzettel();
	// Überschrift
	if (value == 1)
		$("#merkzettel_head").html("Sie haben einen gemerkten Eintrag");
	else if (value > 1)
		$("#merkzettel_head").html("Sie haben " + value + " gemerkte Eintr&auml;ge");
	else
		$("#merkzettel_head").html("Ihr Merkzettel ist noch leer");
	return false;
}

function toggleWako(what) {
	if (($("#warenkorb").css("display") == "none" && !what) || what == "show") {
		$("#warenkorb").fadeIn();
	} else {
		$("#warenkorb").fadeOut();
	}
}
function toggleMerkzettel(what) {
	if (($("#merkzettel").css("display") == "none" && !what) || what == "show") {
		$("#merkzettel").fadeIn();
	} else {
		$("#merkzettel").fadeOut();
	}
}
function clearBread() {
	$("#breadcrumb_container").html("");
}

function initDoWako() {
	if (ajaxAbility()) {

	}
}

//	Google Maps Ajax-Tooltip
function gm_tooltip(id,obj,x,y) {
	$.ajax({
			url: '/veranstaltungen/maptooltip/'
		   ,type: 'post'
		   ,data: { id: id }
		   ,success: function(data) {
				obj.openInfoWindowHtml(data);
			}
		   ,error: function() { alert("Keine Informationen vorhanden"); }
	});
}

// JCarousel Item Click
function jcarousel_clicker() {
	if (window.location.hash.search(/Bild=[0-9]+/) > -1) {
		var myBild = window.location.hash.split("=");
		var mySrc = $("#gallery_480b img").attr("src");
		var myHref = $("#gallery_480b a").attr("href");
		$("#gallery_480b img").attr("src",mySrc.replace(/img[0-9]+/, "img" + myBild[1]));
		$("#gallery_480b a").attr("href",myHref.replace(/img[0-9]+/, "img" + myBild[1]));
		$(".gallery_texts").hide();
		$("#gallery_description" + myBild[1]).show();
	}
	$(".jcarousel-item a").click(function(){
		var myBild = $(this).attr("href").split("=");
		var mySrc = $("#gallery_480b img").attr("src");
		var myHref = $("#gallery_480b a").attr("href");
		$("#gallery_480b img").attr("src",mySrc.replace(/img[0-9]+/, "img" + myBild[1]));
		$("#gallery_480b a").attr("href",myHref.replace(/img[0-9]+/, "img" + myBild[1]));
		$(".gallery_texts").hide();
		$("#gallery_description" + myBild[1]).show();
	})
}

/*
 start scripts, when Document has finished loading
 onLoad...
*/
$(document).ready(function(){

// Check for expandable Texts
	$(".expandableText").each(function(){isExpandableText($(this));});

// Check for expandable Divs
	jQuery.each(objExpandableDivs, function(type, anzahl) { $(".expandable" + type).each(function(){isExpandableDiv($(this), type, anzahl);}); } );


// Check for "Vormerken" links
	initDoMerkzettel();

// Check if Ajax Available
	initDoWako();

//	Ergebnisliste
//	$("#ergebnisliste input[name='t_s']").attr("autocomplete","off");

//	Lupe hovern
	$("input.button_lupe").hover(
		function(){$(this).attr("src",themepath + "images/suche_lupe_schwarz.gif");},
		function(){$(this).attr("src",themepath + "images/suche_lupe_blau.gif");}
	);

// Schriftgröße ändern
	$("#fontsize a[rel='smaller']").click(function(){resizeFont(-1);});
	$("#fontsize a[rel='bigger']").click(function(){resizeFont(1);});
// Schriftgröße aus Cookie lesen
	if (readCookie("FONTSIZE") == "bigger") {
		$("#fontsize a[rel='bigger']").fadeTo("fast",0.3);
	} else if (readCookie("FONTSIZE") == "smaller") {
		$("#fontsize a[rel='smaller']").fadeTo("fast",0.3);		
	}


/*
	Dropdown Boxen
*/
// alle Dropdowns verstecken
	$("#t_sel1, #t_sel2, #t_sel3").css("display","none");

// Dropdown aufklappen
	$(".dropdown_selector").click(function(){
		var mySelectorDiv = "#" + $(this).attr("rel");
		$(mySelectorDiv).css({left: $(this).parent().offset().left + 'px', top: $(this).parent().offset().top + 'px', 'z-index': 9999}).slideDown("fast");
		return false;
	});

// aufgeklappt lassen, wenn Mouse darueber
	$("#t_sel1, #t_sel2, #t_sel3").hover(function(){var myId = $(this).attr("id");clearTimeout(timeouts["dropdown_" + myId]);},function(){var myId = $(this).attr("id");timeouts["dropdown_" + myId] = window.setTimeout(function(){$("#" + myId).fadeOut("normal")},400);});

	$("#t_sel1 > a, #t_sel2 > a, #t_sel3 > a").click(function(){
		var myText = $(this).text();
		var myId = $(this).parent().attr("id");
		$(".dropdown > a[rel="+myId+"]").next(".dropdown_text").text(myText);
		$(this).parent().hide();
	});
//	Dropdown Boxen ENDE


//	Highlight für Listenelemente
	$(".itemlist .tr0").hover(function(){
/*		var bg_style = {
			"background-image": "url('" + themepath + "images/kachel_back.png')"
			,"background-repeat": "repeat-x"
			,"background-position": "left top"
		}
		$(this).css(bg_style);
*/
		$(this).css("background-color","#e7edfc");	// Achtung: addClass('tr1').removeClass('tr0') verursacht DIV-Bug im IE!
		$(this).find(".kachel_links:first > div").show();
/*		Klick geht mit Kachelansicht nicht!
		$(this).click(function(){
			window.location = $(this).find("a:first").attr("href");
		});
*/
	},function(){
		$(this).css("background-color","transparent");
		$(this).find(".kachel_links:first > div").hide();
	});

//	Warenkorb
	if (readCookie("WAKO_SUM") > 0 || readCookie("WAKO_ITEMCOUNT") > 0) {
		toggleWako("show");
		$('#warenkorb > h3 > a').html(readCookie("WAKO_ITEMCOUNT") + " Artikel: " + CurrencyFormatted(readCookie("WAKO_SUM")) + " &euro; &raquo;");
	} else {
		toggleWako("hide");
	}

//	Cluetips bei Bestellung
	$('a.kachel_link_order, a.list_button_order, a.button_order').cluetip({    
		showTitle: false,
		sticky: true,
		delayedClose: 0,
		dropShadow: true,
		dropShadowSteps: 3,
		hoverIntent: false,
		mouseOutClose: true,
		closePosition: 'title',
		closeText: '',
		local: false,
		hideLocal: true,
		arrows: true,
		activation: 'click',
		width: '200px',
		height: '150px',
		positionBy: 'bottomTop',
		waitImage: true,
		attribute: 'rel',
		fx: {
			open: 'fadeIn',
			openSpeed: 'fast'
		},
		onShow: function(ct,c) {
			ct.animate({ top: '+=5px' }, 250, 'swing', function() {});
			if (readCookie("WAKO_SUM") > 0 || readCookie("WAKO_ITEMCOUNT") > 0) {
				toggleWako("show");
				$('#warenkorb > h3 > a').html(readCookie("WAKO_ITEMCOUNT") + " Artikel: " + CurrencyFormatted(readCookie("WAKO_SUM")) + " &euro; &raquo;");
			} else {
				toggleWako("hide");
			}
		}
	});

//	Cluetips bei Theater / Medien
	$('a.button_tmorder').cluetip({    
		showTitle: false,
		sticky: true,
		delayedClose: 0,
		dropShadow: true,
		dropShadowSteps: 3,
		hoverIntent: false,
		mouseOutClose: true,
		closePosition: 'title',
		closeText: '',
		local: false,
		hideLocal: true,
		arrows: true,
		activation: 'click',
		width: '200px',
		height: '150px',
		positionBy: 'bottomTop',
		waitImage: true,
		attribute: 'rel',
		fx: {
			open: 'fadeIn',
			openSpeed: 'fast'
		},
		onShow: function(ct,c) {
			ct.animate({ top: '+=5px' }, 250, 'swing', function() {});
		}
	});

//	Veranstaltungen aus und einklappen
	$(".link_veranstaltung").click(function(){
		var myid = $(this).attr("rel");
		var $obj = $("#" + myid);
		if ($obj.find(".veranstaltung_info_box").length > 0) {
		if ($obj.children(".veranstaltung_info_box").css("display") == "none") {
			$("div[id^='veranstaltung_id_']").find(".veranstaltung_info_box").slideUp();
			$("div[id^='veranstaltung_id_']").find(".link_arrow_down").removeClass("link_arrow_down").addClass("link_arrow_right");
			$obj.find(".link_arrow_right").removeClass("link_arrow_right").addClass("link_arrow_down");
			$obj.children(".veranstaltung_info_box").slideDown();
		} else {
			$obj.find(".link_arrow_down").removeClass("link_arrow_down").addClass("link_arrow_right");
			$obj.children(".veranstaltung_info_box").slideUp();
		}
		return false;
		} else {
		return true;
		}
	});
	
	$(".media_preview").each(function(){
		$(this).children(".media_video, .media_audio, .media_gallery").css("opacity",.7);
		// $(this).children(".media_video").css('top',  $(this).height() / 2 - 15 + "px");
		// $(this).children(".media_gallery").css("right", ($(this).width() - $(this).find("img").width()) / 2 + 10 + "px");
		$(this).hover(function(){
			if ($(this).find(".imageswap").length > 0) {
				var myid = $(this).find("img").attr("id");
				myid = myid.split("_");
				img_swap_id = myid[2];
				img_swap_path = '/mediathek/video';
				intervalID = setInterval("changeImg()", 600);
				changeImg();
			}
		},function(){
			if (typeof(intervalID) != "undefined") clearInterval(intervalID);
		});
	});

	// Add Styleguide Link
	$("#stylguidelink").css({'position':'absolute','top':'5px','left':'5px','opacity':.7,'z-index':999}).html('<h2><a href="/styleguide" class="link_info_inverted">Styleguide &raquo;</a></h2>');

	// nyroModal Settings
	$.nyroModalSettings({
		minWidth: 200,
		minHeight: 100,
		closeButton: '<a href="#" class="nyroModalClose" id="closeBut" title="Schlie&szlig;en">Schlie&szlig;en</a>'
	});

});