// needed for sending the right language-url to google analytics
var lang = document.getElementsByTagName('html')[0].getAttribute('lang');

function addEvent(element, type, handler) {
    // assign each event handler a unique ID
    if (!handler.$$guid) handler.$$guid = addEvent.guid++;
    // create a hash table of event types for the element
    if (!element.events) element.events = {};
    // create a hash table of event handlers for each element/event pair
    var handlers = element.events[type];
    if (!handlers) {
        handlers = element.events[type] = {};
        // store the existing event handler (if there is one)
        if (element["on" + type]) {
            handlers[0] = element["on" + type];
        }
    }
    // store the event handler in the hash table
    handlers[handler.$$guid] = handler;
    // assign a global event handler to do all the work
    element["on" + type] = handleEvent;
};
// a counter used to create unique IDs
addEvent.guid = 1;

function removeEvent(element, type, handler) {
    // delete the event handler from the hash table
    if (element.events && element.events[type]) {
        delete element.events[type][handler.$$guid];
    }
};

function handleEvent(event) {
    // grab the event object (IE uses a global event object)
    event = event || window.event;
    // get a reference to the hash table of event handlers
    var handlers = this.events[event.type];
    // execute each event handler
    var returnval = true;
    for (var i in handlers) {
        this.$$handleEvent = handlers[i];
        returnval = returnval && this.$$handleEvent(event);
    }
    return returnval;
};

document.getAncorElementsByClassName = function(className) {
	var children = document.body.getElementsByTagName('a')
	var elements = new Array()

	for (var i = 0; i < children.length; i++) {
		var child = children[i]
		var classNames = child.className.split(' ')
		for (var j = 0; j < classNames.length; j++) {
			if (classNames[j] == className) {
				elements.push(child)
				break
			}
		}
	}

	return elements
}

// *** slideshow ***
function slidesNavi() {
	if (document.getElementById('slidesnavi')) {
		document.getElementById('slidesnavi').style.display='block';
	}
	if (document.getElementById('slides_1')) {
		document.getElementById('slides_1').style.display='block';
	}
	
	return true;
}
function slides_showimg(linkElement, number) {
	var slideId; 
	var curr; 
	var imgNode;
							
	if (number != null) slideId = number;
	else slideId = linkElement.name;
		
	curr = slides[slideId];
	imgNode = document.getElementById("slides_img");
	imgNode.style.visibility="hidden";
	imgNode.src = curr[1];

	document.getElementById('slideshow_actual').innerHTML=curr[5];
	document.getElementById('slideshow_sum').innerHTML=curr[6];

	// BU and Copy
	if(!curr[2] && !curr[10]) document.getElementById('slidestext').style.display="none"; //curr[10] will be copyright
	else {
		document.getElementById('slidestext').style.display="block"
								
		if (!curr[2]) document.getElementById('bu').style.display="none";
		else {
			document.getElementById('bu').style.display="inline"; 
			document.getElementById('bu').innerHTML=curr[2];
		}
		// if (!curr[7]) document.getElementById('slidescopy').style.display='none';
		// else { 
		//	document.getElementById('slidescopy').style.display='inline'; 
		//	document.getElementById('copy').innerHTML=curr[7];
		//}
	}
							
	// set name for navigation
	document.getElementById("back").name= eval(slideId) - 1 < 1 ?  curr[6] : eval(slideId) -1;
	document.getElementById("forward").name = eval(slideId) + 1 > curr[6] ? 1 : eval(slideId) +1;
							
	imgNode.width = curr[3];
	imgNode.height = curr[4];
	imgNode.alt = curr[7];
	imgNode.title = curr[7];

    // send google analytics request
    _gaq.push(['_trackPageview', '/wf/'+lang+'/170.'+parent_media_object_id+'/']);
}

init_myths = function() {
	var Next = document.getElementById('nav_next_myth')
	var Previous = document.getElementById('nav_previous_myth')
	
	Next.style.visibility = 'visible'
	addEvent(Next, 'click', slide_myths)
	
	Previous.style.visibility = 'visible'
	addEvent(Previous, 'click', slide_myths)
}

slide_myths = function() {
	
	// get actual slide-ID
	var oldId = Number(this.name)
	var direction = this.className
	var titleObj = $('.carousel #myth_title')
	var textObj = $('.carousel #myth_text')
	var citeBoxObj = $('.carusel .citebox')
	var fontSize = "25px"
	var paddingTop = "22px"
	var paddingBottom = "23px"
	
	if (direction == 'next') {
		newId = slides[oldId+1] ? oldId+1 : 0
	}
	else { // previous
		newId = slides[oldId-1] ? oldId-1 : slides.length - 1
	}
	
	var textLength = slides[newId][0].length
	
	switch (true) {
		case textLength > 70:
			fontSize = "17px";paddingTop = "27px";paddingBottom = "28px";break;
		case textLength > 65:
			fontSize = "18px";paddingTop = "27px";paddingBottom = "27px";break;
		case textLength > 60:
			fontSize = "19px";paddingTop = "26px";paddingBottom = "27px";break;
		case textLength > 55:
			fontSize = "20px";paddingTop = "25px";paddingBottom = "26px";break;
		case textLength > 50:
			fontSize = "21px";paddingTop = "25px";paddingBottom = "25px";break;
		case textLength > 45:
			fontSize = "22px";paddingTop = "24px";paddingBottom = "25px";break;
		case textLength > 40:
			fontSize = "23px";paddingTop = "23px";paddingBottom = "24px";break;
		case textLength > 35:
			fontSize = "24px";paddingTop = "22px";paddingBottom = "23px";break;
	}
	
	if (isReady) {
		isReady = false
		
		titleObj.fadeOut('medium', function() {
			titleObj.text(slides[newId][0])
			titleObj.css({fontSize:fontSize})
			citeBoxObj.css({paddingTop: paddingTop, paddingBottom: paddingBottom})
			titleObj.fadeIn('fast')
			isReady = true
			$('.carousel .title a#nav_next_myth').attr('name', newId)
			$('.carousel .title a#nav_previous_myth').attr('name', newId)
		})
		
		textObj.fadeOut('medium', function() {
			textObj.text(slides[newId][1])
			textObj.append('<br/><a href="'+slides[newId][2]+'"><strong>mehr <span class="add" style="color: #C80202;">»</span></strong></a>')
			textObj.fadeIn('fast')
			isReady = true
		})
	}
	
	return false;

}

init_faqs = function() {
	
	var n = Math.floor(Math.random()*slides.length)
	var s = get_faq_sizes(slides[n][0].length)
	var Next = document.getElementById('nav_next_faq')
	var Title = document.getElementById('faq_title')
	var Text = document.getElementById('faq_text')
	var CiteBox = document.getElementById('citebox')
	
	Title.style.fontSize = s[0]
	CiteBox.style.paddingTop = s[1]
	CiteBox.style.paddingBottom = s[2]
	Title.innerHTML = slides[n][0]
	Text.innerHTML = slides[n][1]
		+ '<a href="'+slides[n][2]+'"><strong>&nbsp;mehr&nbsp;<span class="add" style="color: #C80202;">»</span></strong></a>'
	
	Next.name = n
	Next.style.visibility = 'visible'
	addEvent(Next, 'click', slide_faqs)
}

get_faq_sizes = function(textLength) {
	
	switch (true) {
		case textLength > 60:
			fontSize = "15px";paddingTop = "22px";paddingBottom = "23px";break;
		case textLength > 55:
			fontSize = "16px";paddingTop = "22px";paddingBottom = "22px";break;
		case textLength > 50:
			fontSize = "17px";paddingTop = "21px";paddingBottom = "22px";break;
		case textLength > 45:
			fontSize = "18px";paddingTop = "20px";paddingBottom = "21px";break;
		case textLength > 40:
			fontSize = "19px";paddingTop = "20px";paddingBottom = "20px";break;
		case textLength > 35:
			fontSize = "20px";paddingTop = "19px";paddingBottom = "20px";break;
		case textLength > 30:
			fontSize = "21px";paddingTop = "18px";paddingBottom = "19px";break;
		case textLength > 25:
			fontSize = "22px";paddingTop = "17px";paddingBottom = "18px";break;
	}
	
	var sizes = new Array(fontSize, paddingTop, paddingBottom)
	return sizes
}

slide_faqs = function() {
	// get actual slide-ID
	var oldId = Number(this.name)
	var direction = this.className
	var titleObj = $('.carousel #faq_title')
	var textObj = $('.carousel #faq_text')
	var citeBoxObj = $('.carusel .citebox')
	var fontSize = "18px"
	var paddingTop = "21px"
	var paddingBottom = "22px"
	
	if (direction == 'next') {
		newId = slides[oldId+1] ? oldId+1 : 0
	}
	else { // previous
		newId = slides[oldId-1] ? oldId-1 : slides.length - 1
	}
	
	var sizes = get_faq_sizes(slides[newId][0].length)
	
	if (isReady) {
		isReady = false
		
		titleObj.fadeOut('medium', function() {
			titleObj.text(slides[newId][0])
			titleObj.css({fontSize:sizes[0]})
			citeBoxObj.css({paddingTop: sizes[1], paddingBottom: sizes[2]})
			titleObj.fadeIn('fast')
			isReady = true
			$('.carousel .title a#nav_next_faq').attr('name', newId)
			$('.carousel .title a#nav_previous_faq').attr('name', newId)
		})
		
		textObj.fadeOut('medium', function() {
			textObj.text(slides[newId][1])
			textObj.append('<a href="'+slides[newId][2]+'"><strong>&nbsp;mehr&nbsp;<span class="add" style="color: #C80202;">»</span></strong></a>')
			textObj.fadeIn('fast')
			isReady = true
		})
	}
	
	return false;

}

get_cite_sizes = function(textLength) {
    switch (true) {
        case textLength > 300:
            return "font-size:13px;padding-top:14px;height:136px";
        case textLength > 250:
            return "font-size:14px;padding-top:14px;height:136px";
        case textLength > 200:
            return "font-size:14px;padding-top:21px;height:129px";
        case textLength > 175:
            return "font-size:16px;padding-top:22px;height:128px";
        case textLength > 150:
            return "font-size:16px;padding-top:22px;height:128px";
        case textLength > 125:
            return "font-size:18px;padding-top:23px;height:127px";
        case textLength > 100:
            return "font-size:19px;padding-top:27px;height:123px";
        case textLength > 75:
            return "font-size:20px;padding-top:30px;height:120px";
        case textLength > 50:
            return "font-size:21px;padding-top:32px;height:118px";
        case textLength > 25:
            return "font-size:22px;padding-top:34px;height:116px";
    }
}

init_soap_quiz = function() {
    var arVersion = navigator.appVersion.split("MSIE")
    if (arVersion) {
        if (parseFloat(arVersion[1]) < 6) return false
    }
    
    var e = document.getElementsByTagName('div')
    for (i = e.length-1; i>=0; i--) {
        if (e[i].className == 'box') e[i].style.visibility = 'visible'
        if (e[i].className == 'nojs') e[i].style.display = 'none'
    }
    var QuizButton = document.getElementById('quiz_button')
    addEvent(QuizButton, 'click', changeQuizItemRequest)
}

changeQuizItemRequest = function()
{
    var url = "/wf/webservice/public_kas_de"
    var name_array = this.name.split('_')
    var quiz_id = Number(name_array[0])
    var question_id = Number(name_array[1])
    var user_answer = ''
    
    var QuizForm = document.getElementById('quiz_form')
    if (QuizForm) {
        for (i=0; i<QuizForm.length; i++)
            if (QuizForm.elements[i].checked == true) user_answer = QuizForm.elements[i].value
        // do nothing until user chooses anything
        if (user_answer == '') return false
    }
    
    var pl = new SOAPClientParameters();
    var timeout = 3500; // in Millisekunden
    //alert(quiz_id + ', ' + question_id + ', ' + user_answer)
    
    pl.add('quiz_id', quiz_id)
    pl.add('question_id', question_id)
    pl.add('user_answer', user_answer)
    
    // we cannot fade, because box gets hidden and footer flips up on slower browsers
    //$('.quiz .box').fadeOut('slow')
    
    SOAPClient.invoke(url, "get_quiz_item", pl, true, changeQuizItem, soap_quiz_error, timeout);
    
    return false
}

function changeQuizItem(r) {
    $('.quiz').replaceWith(r.html_string)
    init_soap_quiz();
}

function soap_quiz_error(status) {
    // do something here if an error occures
}

init_soap_calendar = function() {
    var Next = document.getElementById('nav_next_calendar_item')
    var Previous = document.getElementById('nav_previous_calendar_item')
    
    addEvent(Next, 'click', changeCalendarItemRequest);
    addEvent(Previous, 'click', changeCalendarItemRequest);
    
    Next.style.visibility = 'visible'
    Previous.style.visibility = 'visible'
}

function changeCalendarItemRequest()
{
	// calendar_carousel

	var url = "/wf/webservice/public_kas_de"
	var current_calendar_item = Number(this.name)
	var direction = this.className
	var pl = new SOAPClientParameters();
	var timeout = 3500; // in Millisekunden

	//$('#calendar_carousel').slideUp()
	$('.carousel .calendar_info').fadeOut('medium')
	$('.box_calendar_date .calendar_date_daybig').fadeOut('medium')
	$('.box_calendar_date .calendar_date').fadeOut('medium')
	
	pl.add("direction", direction);
	pl.add("current_calendar_item", current_calendar_item);
	
	SOAPClient.invoke(url, "get_calendar_item", pl, true, changeCalendarItem, soap_calendar_error, timeout);
	return false;
}

function soap_calendar_error(status) {
	location.href = $('.c_6_8 .carousel a.next').attr('href')
}

function changeCalendarItem(r)
{
	$('.c_6_8 .carousel').replaceWith(r.html_string)
	$('.c_6_8 .carousel .previous').click(changeCalendarItemRequest)
	$('.c_6_8 .carousel .next').click(changeCalendarItemRequest)
	$('.c_6_8 .carousel a.next').css('visibility', 'visible')
	$('.c_6_8 .carousel a.previous').css('visibility', 'visible')

	$('.box_calendar_date .calendar_date_daybig').fadeIn('fast')
	$('.box_calendar_date .calendar_date').fadeIn('fast')
	$('.carousel .calendar_info').fadeIn('fast')

}

// For manipulating the flash-player.
// This variable gets automatically filled with the object, when flash-player
// exists on a page.
var player=[];
function playerReady(thePlayer) {
	player.push(window.document[thePlayer.id]);
    player[player.length -1].addModelListener("STATE", "playTracker");
    player[player.length -1].addModelListener("STATE", "playTrackerNews");
}

var started = false;
function playTracker(obj) {
    if (obj.newstate == 'BUFFERING' && started == false) {
        started = true;
        var arr = obj.id.split('_');
        // send google analytics request
        _gaq.push(['_trackPageview', '/wf/'+lang+'/170.'+arr[2]+'/']);
    }
}

//stop (pause) animation of news caroussell if flash element is playing or loading
function playTrackerNews(obj) {
	if (obj.newstate == 'PLAYING' || obj.newstate == 'BUFFERING') {
		$('#news_slides').cycle('pause');
	}
}

var isReady = true
slide_news = function() {
    var direction = this.className
    var oldId = Number(this.name)
    var newId = 0
    var news = $('.topnews_carousel_content')
    
    if (direction == 'next') {
        newId = news[oldId+1] ? oldId+1 : 0
    }
    else { // previous
        newId = news[oldId-1] ? oldId-1 : news.length - 1
    }
    
    if (isReady) {
        isReady = false
        $('.topnews_carousel .topnews_carousel_content:eq('+(oldId)+')').fadeOut('fast', function(){
           
        	stopPlayer();
        	
            $('.topnews_carousel .topnews_carousel_content:eq('+(newId)+')').fadeIn('fast')
            $('#topnews_carousel_nav a').attr('name', newId)
            $('#topnews_carousel_nav h6 .current').text(String(newId+1))
            isReady = true
        })
    }
    
    return false
}

// test if we have player on this div and stop them if necessary
function stopPlayer(){
	for (i=0; i< player.length; i++){
		if (typeof player[i] == 'object' && typeof player[i].sendEvent == 'function') {	
			player[i].sendEvent('STOP');
        }
	}
}

function slideshow(){
	var direction = this.id;
	//id is called slide_0, slide_1, ...
	var currentId = Number($('.slideshow_actual').attr('id').substring(6));
    var newId = 0;
    var slides = $('.slidesimg');
    
    if (direction == 'forward') {
        newId = slides[currentId+1] ? currentId+1 : 0;
    }
    else { // back
        newId = slides[currentId-1] ? currentId-1 : slides.length - 1;
    }
   
   
    // no animation
	$('.slidesimg:eq('+(currentId)+')').addClass("hidden"); 
	$('.slidesimg:eq('+(newId)+')').removeClass("hidden"); 
	
	$('.slideshow_actual').text(String(newId+1));
	newId = 'slide_'+newId;
    $('.slideshow_actual').attr('id', newId);  
   
    // send google analytics request
    //todo: works this url also for slideshows at sites of branchoffices?
    _gaq.push(['_trackPageview', '/wf/'+lang+'/170.'+parent_media_object_id+'/']);

    return false;
}

// *** google analytics document counter ***
// adds an onclick-event for links to documents
function addGaDocumentTracker() {
    $('a').filter(function(){
        // send ga request for files, but leave pdfs served from wf untouched.
        // this is done while loading file through webfriend.
        return /\.(doc|xls|ppt|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3|txt)$/i.test(this.pathname)||(!/^\/?wf\/doc\//i.test(this.pathname)||!/\.pdf$/i.test(this.pathname))
    }).click(function(){
        _gaq.push(["_trackPageview",this.pathname])
    })
}

// this function is old and could be removed in future
function addGaDocumentTracker_old() {
	var hrefs = document.getElementsByTagName("a");
	var link_path = "";
	for (var l = 0; l < hrefs.length; l++) {
		try {
			var link_path = hrefs[l].pathname;
			if (location.host == hrefs[l].hostname) {
				if (link_path.match(/\.(doc|pdf|xls|ppt|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3|txt)$/)) {
					addtrackerlistener(hrefs[l]);
				}
			}
		}
		catch(err) { }
	}
}
function addtrackerlistener(obj) {
	if (obj.addEventListener) {
		obj.addEventListener('click', trackfiles, true);
	} else if (obj.attachEvent) {
		obj.attachEvent("on" + 'click', trackfiles);
	}
}
function trackfiles(array_element) {
	file_path = "";
	file_path = ((array_element.srcElement) ? "/" + array_element.srcElement.pathname : this.pathname);

    _gaq.push(['_trackPageview', file_path]);
}

// *** Google Maps ***
// call a google map - insert it in an element on page with Id "map"
// data xml via GDownloadUrl/Webfriend 
function load_gmap(data_source, center_lat, center_lng, zoomlevel, language) {
	var data_source = "/" + data_source + "/";
	var lat = parseFloat(center_lat);
	var lng = parseFloat(center_lng);
	var zoom = parseFloat(zoomlevel);
	var lang = language;
	var markerOptions = {};
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(lat, lng), zoom);
		// map.setCenter(new GLatLng(51.5025472379655, 13.439583778381348), 4);
		// map.addControl(new GLargeMapControl());
		map.setMapType(G_NORMAL_MAP);
	
		//GEvent.addListener(map, 'moveend', function() {
			// Display current map center
			//document.getElementById("centerlatitude").value = map.getCenter().lat();
			//document.getElementById("centerlongitude").value = map.getCenter().lng();
		//}) // GEvent.addListener
		
		if (zoom < 3) {
			// Create our "tiny" marker icon
			var tinyIcon = new GIcon();
			tinyIcon.image = "/img/mm_20_red.png";
			tinyIcon.shadow = "/img/mm_20_shadow.png";
			tinyIcon.iconSize = new GSize(12, 20);
			tinyIcon.shadowSize = new GSize(22, 20);
			tinyIcon.iconAnchor = new GPoint(6, 20);
			tinyIcon.infoWindowAnchor = new GPoint(5, 1);
			
			// Set up our GMarkerOptions object literal
			markerOptions = { icon:tinyIcon };
		}
		
		function createMarker(point, point_title) {
			var marker = new GMarker(point, markerOptions);
			var myHtml = point_title;
			GEvent.addListener(marker, "click", function() {
				map.openInfoWindowHtml(point, myHtml);
			});
			return marker;
		}
	
		GDownloadUrl("/wf/"+ lang + data_source, function(data, responseCode) {
		  var xml = GXml.parse(data);
		  if (lang == 'en') {
		  	var str_link_website = 'Visit Website';
		  }
		  else if (lang == 'de') {
		  	var str_link_website = 'Webseite besuchen';
		  }
		  
		  var markers = xml.documentElement.getElementsByTagName("marker"); 
		  for (var i = 0; i < markers.length; i++) {
			var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
									parseFloat(markers[i].getAttribute("lng")));
									
			// var point_title = String(markers[i].childNodes[1].getAttribute("title"));
			// point_title = point_title + String(markers[i].childNodes[1].getAttribute("href"));
			
			var point_title ="";
			var items = markers[i].getElementsByTagName("item");								
			for (var j = 0; j < items.length; j++) {
				//var point_title = j;
				point_title += "<div style=\"padding-right: .8em; background-color: #fff;";
				if (j > 0) {
					point_title += "margin-top: 1em; ";
				}
				point_title += "\">";
				point_title += "<strong><a href=\"";
				point_title += String(items[j].getAttribute("href"));
				point_title += "\" style=\"color: #1C277F\">";
				point_title += String(items[j].getAttribute("title"));
				point_title += "</a></strong>";
				if (j < 2 ) {
					point_title += "<span style=\"display: block; font-size: 76%; margin-top: .05em; \">" + String(items[j].getAttribute("address")) + "</span>";
				}
				point_title += "<span style=\"display: block; margin-top: .4em;\"><a href=\"" + String(items[j].getAttribute("href")) + "\" style=\"font-size: 76%;\">" + str_link_website + "</a></span>";
				point_title += "</div>";
			}
			//var point_title = String(markers[i].getAttribute("infoWindowHtml"));
			map.addOverlay(createMarker(point, point_title));
		  }
		});
	}  	
}

/* diplays drop down for entering search period */
function displaySearchPeriod(){
	$("table.fieldDate").addClass("hidden");
	$(".c_4_7 p").removeClass("hidden");
	$(".c_4_7 p a").click(function() {
		$(this).parents("p").addClass("hidden");
		$(".c_4_7 table").removeClass("hidden");
		return false;
	});
}

function printPage(){
	$('li.printout').removeClass('hidden');
	$('li.printout a').click(function() {
		window.print();
		return false;	
	});
}

/*  old google maps
<xsl:text disable-output-escaping="yes"><![CDATA[
	<script type="text/javascript">
		//<![CDATA[
		function load_gmap_old() {
			if (GBrowserIsCompatible()) {
				var map = new GMap2(document.getElementById("map"));
				map.setCenter(new GLatLng(51.5025472379655, 13.439583778381348), 4);
				//map.addControl(new GLargeMapControl());
				map.setMapType(G_NORMAL_MAP);
		 
				function createMarker(point, point_title, point_address, point_href) {
					var marker = new GMarker(point);
					var myHtml = "<strong><a href=\"" + point_href + "\" style=\"color: #1C277F\">" + point_title + "</a></strong><br />" +
									"<p style=\"font-size: 76%; margin-top: 0.05em;\">" + point_address + "</p>" + 
									"<p style=\"margin-top: .8em; font-size: 78%;\"><a href=\"" + point_href + "\">Visit Website</a></p>";
					GEvent.addListener(marker, "click", function() {
						map.openInfoWindowHtml(point, myHtml);
					});
					return marker;
				}
		 
		 
				GDownloadUrl("/wf/en/188.1/", function(data, responseCode) {
				  var xml = GXml.parse(data);
				  var markers = xml.documentElement.getElementsByTagName("marker");
				  for (var i = 0; i < markers.length; i++) {
					var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
											parseFloat(markers[i].getAttribute("lng")));
					var point_title = String(markers[i].getAttribute("title"));
					var point_address = String(markers[i].getAttribute("address"));
					var point_href = String(markers[i].getAttribute("href"));
					map.addOverlay(createMarker(point, point_title, point_address, point_href));
				  }
				});
			}  	
		}
		//]]>]]&gt;
	&lt;/script>
</xsl:text>
*/
			

