var initIndex = Math.round(Math.random()*3);
var aborted = false;

function createGallery()
{
	// add overlay div
	$("body").append('<div id="modalGallery"><div class="close" title="Fenster schließen"></div><div class="overlay-content"><h3>Bildergalerie</h3><div class="bigimage"><img /><p></p></div><a class="prevPage browse left" title="zurückblättern">prev</a> <div class="scrollable"><div class="items"> </div> </div> <a class="nextPage browse right" title="vorblättern">next</a></div><div class="close close-bottom" title="Fenster schließen"></div></div>');
	// generate scrollpane thumb-list by cloning existing links
	$("a[target=enlargedPicture]").clone().appendTo("#modalGallery .items");
	// manipulation scrollpane item link-tags
	$("#modalGallery .items a").removeAttr("target");
	$("#modalGallery .items a img").removeAttr("width");
	$("#modalGallery .items a img").removeAttr("height");
		
	var offset = $('#rightcontent').offset();
	// adding click function
	$("#modalGallery .items a").each(function() {
		$(this).attr("title", "Klicken um Bild zu vergrößern");
		$(this).click(function() {
			$("#modalGallery .bigimage img").attr("src", this);
			$("#modalGallery .bigimage p").text($('img', this).attr("alt"));
			return false;
		});
	});
		
	// adding scrollpane functionality
	var api = $("div.scrollable").scrollable({ api: true });
		
	// adding modalGallery
//		$("#modalGallery .items a[href=" + $(this).attr("href") + "]").click();
		$("a[target=enlargedPicture]").overlay({
			target: '#modalGallery', 
			expose: '#333b46',
			left: (offset.left-716),
			top: '100',
			onBeforeLoad: function() 
			{
				window.scrollTo(0, 0);
				$("#modalGallery .bigimage img").attr("src", this.getTrigger().attr('href'));
				$("#modalGallery .bigimage p").text($("img", this.getTrigger()).attr('alt'));
				api.seekTo($("#modalGallery .items a").index($("#modalGallery .items a[href=" + this.getTrigger().attr('href') + "]")));
				ET_Event.eventStart('Galerie', 'http://www.wegweiser-demenz.de/'+this.getTrigger().attr('href'), 'Klicks', 'Overlay Galerie');
				$(window).scrollTop(0);
			}
		});
//		api.seekTo($("#modalGallery .items a").index($("#modalGallery .items a[href=" + $(this).attr("href") + "]")));
}

function enableTabs()
{
	$('#overlay ul.tabnavigation a').each(function(index) {
		var location = $(this).attr("href");
		if ( (location.search(/\?/)) != -1)
		{
			$(this).attr("href", $(this).attr("href")+'&ajax=true');
		}
		else
		{
			$(this).attr("href", $(this).attr("href")+'?ajax=true');
		}
	});	
    $("#overlay ul.tabnavigation").tabs("#overlay div.tabcontent", {
    	effect: 'ajax',
    	initialIndex: '-1',
    	current: 'active'
    });	
}

function formDefault()
{
	$('#institution-search input').each(function(index)
	{
		if (!$(this).attr("value"))
		{
			$(this).attr("value", $(this).attr("title"));
		}
		$(this).focus(function()
		{
			$(this).select();
		});
	});
}

function formOverlay()
{	
	var offset = $('#rightcontent').offset();
	var overlayApi = $('#institution-search-submit').overlay({
		api: true,
		target: '#overlay',
		expose: '#333b46',
		left: (offset.left-716),
		top: '100',
		onClose: function() 
		{
			removeOverlayPrint();
			$("#checkboxes").hide();
		}
	});	
	
	$('#institution-search-submit').click(function()
	{
		overlayApi.load();
		ET_Event.eventStart('Hilfe%20in%20meiner%20N%C3%A4he', $('#institution-search').attr("action"), 'Klicks Suchstart', 'Overlay Formular');
		var location = $('#institution-search').attr("action");
		$.ajax({
			type: "POST",
			url: transformLocation(location, "overlay=true"),
			data: $('#institution-search').serialize(),
			success: function(data) 
			{
				$('.overlay-content').html(data);
				addOverlayPrint();
				$(window).scrollTop(0);
			}
		});		
		return false;
	});
}

function scrollToAnchor(location)
{
	locationparts = location.split("#");
	if (locationparts.length>1)
	{
		oldlocation = window.location.href;
		newlocation = oldlocation.split("#");
		window.location.href = newlocation[0]+'#'+locationparts[1];
	}	
}

function removeAnchor()
{
	location = window.location.href;
	locationparts = location.split("#");
	if (locationparts.length>1)
	{
		window.location.href = locationparts[0];
	}
}

function transformLocation(location, param)
{
	locationparts = location.split("#");
	if (locationparts.length>1)
	{
		return locationparts[0]+'?'+param;
	}
	else
	{
		locationparts2 = locationparts[0].split("?");
		if (locationparts2.length>1)
		{
			return locationparts[0]+'&'+param;			
		}
		else
		{
			return locationparts[0]+'?'+param;
		}		
	}
}


function hideAndEnableDropdownMouseover()
{
	// hide faq dropdown
	$("#faqselect .dropdown ul").hide();	
	$('#faqselect .dropdown').mouseover(function() 
	{
		$("#faqselect .dropdown ul").show();
	}).mouseout(function() 
	{
		$("#faqselect .dropdown ul").hide();
	});	
	// hide target navigation dropdown
	//$("#tgnavigation .dropdown ul").hide();	
	//$('#tgnavigation .dropdown').mouseover(function() 
	//{
	//	$("#tgnavigation .dropdown ul").show();
	//}).mouseout(function() 
	//{
	//	$("#tgnavigation .dropdown ul").hide();
	//});	
	// hide checkboxes
	$('#institution-search').focusin(function() 
	{
		$("#checkboxes").show();
	});
		
	$("#checkboxes p.title").after('<div class="quickselect"><p class="uncheck-all" title="Alle Kriterien abwählen">Alle abwählen</p><p class="check-all" title="Alle Kriterien auswählen">Alle auswählen</p></div>');
	$(".quickselect .uncheck-all").click(function() 
	{
		$("#checkboxes input").removeAttr("checked");
	});
	$(".quickselect .check-all").click(function() 
	{
		$("#checkboxes input").attr("checked", "checked");
	});	
	$("#checkboxes").hide();
}

function hideAndEnableGlossarItems()
{
	$(".tx-kfglossary-pi1 .item .desc").hide();
	$(".tx-kfglossary-pi1 .item h3").click(function() 
	{
		$(".desc", $(this).parent()).toggle();
	});
}

function hideAndEnableDbinfoItems()
{
	$("p.bodytext", $(".tabcontent h2").parent().parent()).hide();
	$(".tabcontent h2").click(function() 
	{
		$("p.bodytext", $(this).parent().parent()).toggle();
	});
}

function hideAndEnableFAQItems()
{
	$("p.bodytext", $("#main-content h3").parent().parent()).hide();
	$("#main-content h3").click(function() 
	{
		$("p.bodytext", $(this).parent().parent()).toggle();
	});
}

function hideAndEnableOfferItems()
{
	$(".tx-wwdinstitutions-pi5 .item-offers p.internal-link").click(function() 
	{
		$("p.bodytext", $(this).parent()).toggle();
	});
}

function enableStartTeaser()
{
	$("#media-navigation").tabs("#media-panel .stage", { 
		history: true,
		effect: "fade",
		fadeOutSpeed: "slow",		
		rotate: true,
		initialIndex: initIndex
	});
}

function setSearchboxLabel()
{
	$("#searchform-sn input").attr("value", $("#searchform-sn input").attr("title"));
	$("#searchform-sn input").focus(function()
	{
		var title = $("#searchform-sn input").attr("title");
		var text = $("#searchform-sn input").attr("value");
		if (text == title)
		{
			$("#searchform-sn input").attr("value", '');
		}
		var text = $("#searchform-sn input").select();
	});
	$("#searchform-sn input").focusout(function()
	{
		var title = $("#searchform-sn input").attr("title");
		var text = $("#searchform-sn input").attr("value");
		if (text == '')
		{
			$("#searchform-sn input").attr("value", title);
		}
	});
}

function createOverlays()
{
	$('#wrapper').after('<div id="overlay" style="display: none;"><div class="close" title="Fenster schließen"></div><iframe src="" name="hiddenframe" id="hiddenframe"></iframe><div id="printstyle"></div><div class="overlay-content"></div><div class="close close-bottom" title="Fenster schließen"></div></div>');
	var offset = $('#rightcontent').offset();
	$("a.overlay").overlay({
		target: '#overlay',
		expose: '#333b46',
		left: (offset.left-716),
		top: '0',
		onClose: function() 
		{
			removeOverlayPrint();
		},
		onBeforeLoad: function() 
		{ 		
			var wrap = this.getContent().find(".overlay-content");
			var location = this.getTrigger().attr("href");
			var newlocation = transformLocation(this.getTrigger().attr("href"), "overlay=true");
			wrap.load(newlocation, function() {scrollToAnchor(location); enableTabs(); createOverlayTooltips();}); 
			category = getCategoryForOverlay(location);
			if (category != false)
			{
				ET_Event.eventStart(category, 'http://www.wegweiser-demenz.de'+location, 'Klicks', 'Overlay');
			}
			
			addOverlayPrint();
			$(window).scrollTop(0);
		}
	});	
}

function getCategoryForOverlay(location)
{
	if (location == '/alzheimer-telefon.html')
	{
		return encodeURI('Alzheimer Telefon');
	}
	else if (
			location == '/informationen-fuer-demenzkranke.html' || 
			location == '/informationen-fuer-angehoerige.html' || 
			location == '/informationen-fuer-freunde.html' || 
			location == '/informationen-fuer-ehrenamtliche.html' || 
			location == '/informationen-fuer-helfende.html'
		)
	{
		return encodeURI('Informationen für');
	}
	else if (
		location == '/fragen-und-antworten.html#c758' || 
		location == '/fragen-und-antworten.html#c757' || 
		location == '/fragen-und-antworten.html#c756' || 
		location == '/fragen-und-antworten.html#c756' || 
		location == '/fragen-und-antworten.html#c771'
	)
	{
		return encodeURI('Fragen und Antworten');
	}
	else
	{
		return false;
	}
}

function createOverlayTooltips()
{
	$(".overlay-content .tooltip").tooltip({ 
		tip: '#tooltip',  
		offset: [37, 30], 		
		position: 'top right',
		effect: 'slide',
		onBeforeShow: function() {
			var id = this.getTrigger().attr("id");
			var gid = id.split("-");
			var location = "http://www.wegweiser-demenz.de/index.php?id=187&ajax=true&gid="+gid[1];
			$('#tooltip').html('<div id="tooltipcontent"><img src="http://www.wegweiser-demenz.de/fileadmin/templates/img/spinner.gif" title="Inhalt wird geladen" alt="Inhalt wird geladen" /></div><div class="edge"></div>');
			$('#tooltipcontent').load(location);		
		},
		onHide: function() {
			$("#tooltip").empty();
		}
	});	
}

function createTooltips()
{
	$("#wrapper").after('<div id="tooltip" style="display: none;"></div>');
	$(".tooltip").tooltip({ 
		tip: '#tooltip',  
		offset: [37, 30], 		
		position: 'top right',
		effect: 'slide',
		onBeforeShow: function() {
			var id = this.getTrigger().attr("id");
			var gid = id.split("-");
			var location = "http://www.wegweiser-demenz.de/index.php?id=187&ajax=true&gid="+gid[1];
			$('#tooltip').html('<div id="tooltipcontent"><img src="http://www.wegweiser-demenz.de/fileadmin/templates/img/spinner.gif" title="Inhalt wird geladen" alt="Inhalt wird geladen" /></div><div class="edge"></div>');
			$('#tooltipcontent').load(location);		
		},
		onHide: function() {
			$("#tooltip").empty();
		}
	});	
}

function createTabnavs()
{
	$('ul.tabnavigation a').each(function(index) {
		var location = $(this).attr("href");
		if ( (location.search(/\?/)) != -1)
		{
			$(this).attr("href", $(this).attr("href")+'&ajax=true');
		}
		else
		{
			$(this).attr("href", $(this).attr("href")+'?ajax=true');
		}	    
	});	
    $("ul.tabnavigation").tabs("div.tabcontent", {
    	effect: 'ajax',
    	initialIndex: -1,
    	current: 'active'   	
    });	
}


function createMarker(point, content) {
	var blueIcon = new GIcon();
	blueIcon.image = "http://www.wegweiser-demenz.de/fileadmin/templates/css/img/map_icon.png";
	blueIcon.shadow = "";
	blueIcon.iconSize = new GSize(32, 32);
	blueIcon.shadowSize = new GSize(0, 0);
	blueIcon.iconAnchor = new GPoint(0, 0);
	blueIcon.infoWindowAnchor = new GPoint(16, 2);
	markerOptions = { icon:blueIcon };
	

	var marker = new GMarker(point, markerOptions);
	if ((typeof content) != 'undefined')
	{
		var html = content;	
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(html);
		});
	}
	return marker;
}

function drawCircle(lat, lng, radius, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity) {
	var d2r = Math.PI/180;
	var r2d = 180/Math.PI;
	var Clat = radius * 0.014483;  // Convert statute miles into degrees latitude
	var Clng = Clat/Math.cos(lat*d2r); 
	var Cpoints = []; 
	for (var i=0; i < 33; i++) { 
		var theta = Math.PI * (i/16);
		Cy = lat + (Clat * Math.sin(theta));
		Cx = lng + (Clng * Math.cos(theta));
		var P = new GLatLng(Cy, Cx);
		Cpoints.push(P);
	}
	
	var polygon = new GPolygon(Cpoints, strokeColor, strokeWidth, strokeOpacity, fillColor, fillOpacity);
	map.addOverlay(polygon);
}

function prepareOverlayLinks()
{
	$('#overlay a.ajax').live('click', function(event) 
	{
		if (aborted == true)
		{
			aborted = false;
			return false;
		}
				
		
		event.preventDefault();

		url = $(this).attr("href");
//		ET_Event.click(url, 'Overlay');
		ET_Event.eventStart('Hilfe%20in%20meiner%20N%C3%A4he', url, 'Klicks', 'Overlay');
		
		if ( (url.search(/\?/)) != -1)
		{
			url += '&overlay=true';
		}
		else
		{
			url += '?overlay=true';
		}
		$('.overlay-content').load(url, function() {
			createOverlayTooltips();
		});
		$(window).scrollTop(0);
		return false;		
	});	
}


function prepareOverlayForms()
{
	$('#overlay form button').live('click', function(event)
	{
//		ET_Event.click($('#overlay form').attr("action"), 'Overlay Formular');
		ET_Event.eventStart('Hilfe%20in%20meiner%20N%C3%A4he', $('#overlay form').attr("action"), 'Klicks', 'Overlay Formular');
		
		if ($('#overlay form').attr('class') == 'hiddenframe')
		{
			$(window).scrollTop(0);				
			return true;
		}
		
		var location = $('#overlay form').attr("action");
		$.ajax({
			type: "POST",
			url: transformLocation(location, "overlay=true"),
			data: $('#overlay form').serialize()+'&ds-submit=1',
			success: function(data) 
			{
				$('.overlay-content').html(data);
				$(window).scrollTop(0);				
			}
		});		
		return false;
	});
}

function prepareIforms()
{
	$('#overlay form').attr('target', 'hiddenframe');
	$('#overlay form').attr('action', transformLocation($('#overlay form').attr('action'), 'overlay=true'));
	$('#hiddenframe').load(function() {
		moveIform();
	});	
}

function moveIform()
{
	$('.overlay-content').html(parent.hiddenframe.getContent());
}

function addOverlayPrint()
{
	$('#printstyle').html('<link rel="stylesheet" type="text/css" href="fileadmin/templates/css/print_overlay.css" media="print" />');
}

function removeOverlayPrint()
{
	$('#printstyle').html('');	
}

function enableCharacterCount()
{
	$(document).ready(function() 
	{
		$('textarea#ds-description').keyup(function() 
		{
			var charCount = $(this).val().length;
			$('.charcount').text(charCount + ' Zeichen eingegeben');
			if(charCount >= 1000)
			{
				$('span.maxchars').addClass('red');
				$('.charcount').addClass('red');
			}
			else
			{
				$('span.maxchars').removeClass('red');
				$('.charcount').removeClass('red');				
			}
		});		
	});
}

function alertBacklink()
{
	check = confirm("Sie verlassen damit das Formular und alle Änderungen gehen verloren!");
	if (check == false)
	{
		aborted = true;
		return false;
	}
	else
	{
		return true;
	}
	
}

$(document).ready(function() 
{
	createTooltips();	
	createOverlays();
	createTabnavs();
    
    // create gallery overlay
    createGallery();    
    
    // change address search form to ajax form
    formOverlay();
//    formDefault();
    
    // hide form checkboxes and dropdowns in service box and enable hover functions
    hideAndEnableDropdownMouseover();
    
    // hide glossary and make clickable
    hideAndEnableGlossarItems();
    
    // create click events for teaser items
    enableStartTeaser();
    
    // initialize searchbox
	setSearchboxLabel();
	
	prepareOverlayLinks();
	prepareOverlayForms();
});

