/*-------------------- Globals --------------------*/
var mycarousel_itemList;

$(document).ready(function() {
						   
	if ($("body").hasClass("home")){
		$("body").addClass("ph-js-enabled");
		$("body").addClass("js-enabled");
	} else {
		$("body").addClass("js-enabled");
	}
	
/*-----------------------------------------------------------------------------------------------*/

	// open external-links in new window 
	$('a.external-link').click(function(){
		window.open(this.href);
		return false;
	});

/*-----------------------------------------------------------------------------------------------*/
	
	//add value to seachfield
	var searchVal = $('#searchfield').val();
	$(document).focus(function() {
		if($(this) != $('#searchfield')) {
			if($('#searchfield').val() == '') {
				$('#searchfield').val(searchVal);
			}
		}
	});
	
	// clear search field on focus
	$('#searchfield').focus(function() {
		if($(this).val() == searchVal) {
			$(this).val('');
		}
	});
	
/*-----------------------------------------------------------------------------------------------*/
//Medienmitteilungen Rotierende Liste
	
	
/*-----------------------------------------------------------------------------------------------*/
		
	// vertical align middle		
	$(".middle-align ul").each(function(){			
		var ulHeight = $(this).height()/10;
		$(this).css({"top" : "50%", "margin-top" : "-"+(ulHeight/2)+"em"});
	});		
	
	/* this is for BelatedPNG filter */
	if ( $.browser.msie && $.browser.version == 6.0 ) {
		DD_belatedPNG.fix('#header,.secondary-header, .secondary-header .search, #content .ic-transparent, #footer, .top-sidebar, .wrapper-logo, .title-page, .bottom-sidebar, .breadcrumb, .breadcrumb .right-breadcrumb, .module-teaser dd, .main-content, .module-feature dd, .lower-module .module dd, .caption, #content');	
	
		$('button').each(function() {
			$('button').hover(function() {
				$(this).css('color', '#ff6600');
				$(this).children('span').css('backgroundImage', 'url(_ui/images/btn-blue-arrow-2-left-hover.gif)');
			}, function() {
				$(this).css('color', '#0073BA');
				$(this).children('span').css('backgroundImage', 'url(_ui/images/btn-blue-arrow-2-left.gif)');
			});
		});
	}

/*-----------------------------------------------------------------------------------------------*/
	
	//init datepicker 
	$('.date-pick').each(function() {
		if($('#date-von').length > 0) {
			$('.date-pick').datePicker({
				clickInput: true,
				startDate: '01/01/1970',
				endDate: (new Date()).asString()
			});
				
		} else {
			try {
				$('.date-pick').datePicker({
					clickInput: true,
					startDate: '01/01/1970'
				});
			} catch (e) {
				// ignore
			}
		}
	});
	
/*-----------------------------------------------------------------------------------------------*/
	/* back to top */
	$('p.back-to-top a').each(function() {
		$('p.back-to-top a').click(function(){
			$.scrollTo( 0, 800);
			return false;
		});
		$('a.up').click(function(){
			$.scrollTo( 0, 800);
			return false;
		});
	});
	
/*-----------------------------------------------------------------------------------------------*/
	
	/* clear amount value onfocus */
	$('input.amount').each(function() {
		var val = $('input.amount').val();
		
		$(document).focus(function() {
			if($(this) != $('input.amount')) {
				$('input.amount').each(function() {
					if($(this).val() == '') {
						$('input.amount').val(val);
					}
				});
			}
		});
		
		$('input.amount').each(function() {
			$(this).focus(function() {
				if($(this).val() == val) {
					$(this).val('');
				}
			});
		});
	});
	
/*-----------------------------------------------------------------------------------------------*/
	
	/* jump to input field where error occured */
	$('.form-errors').each(function(){
		$('.form-errors').children('li').each(function() {
			$(this).children('a').click(function(){
				$($(this).attr('href')).focus();
				return false;
			});
		});
	});

/**
 * Replace the nospam-email address text
 * with a proper E-Mail address wrapped in a mailto:tag href tag.
**/
 	$("span[class^=nospamEmailAddress]").each(function(k) {
 	   var $self = $(this);
 	   var $classes = $self.attr("class").split(" ");
 	   var $params = $classes[0].substring(19).split(":");
 	   var $queryString = $params[0];
 	   var $text = unescape($params[1]).replace(" &#123;at&#125; ", "@");
 	   var $email = $self.html().replace(" {at} ", "@");
 	   var $emailAddress = $email;
 	   if($queryString.length > 0) {
 		   $emailAddress += unescape($queryString);
 	   }
 	   var $mailtoTag = $('<a href="mailto:' + $emailAddress + '" class="email"></a>')
       $self.html($text);
       $self.wrap($mailtoTag);
	});

/**
 * Activate automatically reloading images, such as webcam images.
 */
	$("img[class^=reload]").each(function(k) {
		var $self = $(this);
		var $params = $self.attr("class").split(":");
		// seconds to milliseconds.
		var $timeout = $params[1] * 1000;
		var $src = $self.attr("src");
		setInterval(function() {
			var $newSrc = $src + '?' + Math.random();
			$self.attr("src", $newSrc);	
		}, $timeout);
	});

/**
 * Enables scrolling to overflowing content.
 */
	$("a[href^=#]").each(function(k) {
		$(this).click(function(e) {
			//stop the click on the links
			e.preventDefault();
			//scroll to pos
			$.scrollTo(this.hash, 600);
		});
	});

/**
 * Enables swinging teasers on the homepage.
 */
	$('.home').each(function(){
		$('.swinging-content').hide();
		
		$(".sidebar-menu li").each(function() {
			var $li = $(this);
			$li.children("h3").each(function() {
				$h3 = $(this);
				$link = $('<a href="#" title="">' + $h3.text() + "</a>");
				$link.click(function(e) {
					/*if(!$(this).hasClass('expanded')) {
						resetToggleTeaserState();
					}*/
					$li.children('.swinging-content').slideToggle("normal");
					$(this).toggleClass('expanded');
					return false;				
				});
				$h3.html($link);
				if($h3.hasClass("defaultExpanded")) {
					$li.children('.swinging-content').slideToggle("normal");
					$link.toggleClass('expanded');					
				}				
			});
		});
	}); 

	//Medienmitteilungen Rotierende Liste
	//hide list items first for calculation exact page height	
	$('ul.rotate-list').each(function() {
		var rotateLis = $(this).children('li');
		var carouselParent = $(this).parent("div.jCarousel");
		var wrapperHeight = carouselParent.outerHeight(true);
		var totalLiHeight = 0;
		var lastLi;
		
		for(var i = 0; i < rotateLis.length; i++) {
			lastLi = $(rotateLis[i]);
			totalLiHeight += lastLi.outerHeight();
		}	
		
		var allItemsAreVisible = totalLiHeight <= carouselParent.height();
		
		if (allItemsAreVisible) {
			return;
		}
		
		var totalLiHeightWithoutLastElement = totalLiHeight - lastLi.outerHeight();
		var lastElementPartiallyVisible = totalLiHeightWithoutLastElement < wrapperHeight;
		
		if (lastElementPartiallyVisible) {
			wrapperHeight = totalLiHeightWithoutLastElement;
		}
		
		var interval = $(this).attr('class').split(' ').slice(-1);
		interval = interval[0].slice(8);
		if(interval > 0) {
			$(this).parent('.jCarousel').jcarousel({
				vertical: true,
				auto: 2,
				scroll: 1,
				animation: 750,
				buttonNextHTML: null,
				buttonPrevHTML: null,
				wrap: 'last' /*'last',
				itemFirstOutCallback: {onAfterAnimation: jCarousel_itemFirstOutCallback}*/
			});
			$(this).parent('div.jcarousel-clip').height(wrapperHeight);
		}
	});
	
	setEqualContentHeight();
/* end (document).ready */	
});

// helper for circular carousel
function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt) {
  // The index() method calculates the index from a
  // given index who is out of the actual item range.
  var idx = carousel.index(i, mycarousel_itemList.length);
  carousel.add(i, jQuery(mycarousel_itemList[idx - 1]).html());
};

// helper for circular carousel
function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt) {
	console.debug("mycarousel_itemVisibleOutCallback");
  carousel.remove(i);
};

function resetToggleTeaserState() {
	$('.sidebar-menu').children('li').each(function() {
		$(this).children('h3').children('a').removeClass('expanded');
		$(this).children('.swinging-content').slideUp("normal");
	});
}

function jCarousel_itemFirstOutCallback(carousel, item, i, state, evt) {
	var jCarouselLi = $(carousel.clip).children('ul').children('li');
	var $innerHtml = $(item).html();
	carousel.add(jCarouselLi.length  + 1, $innerHtml);
	carousel.remove(i);	
};

/**
 * Applies and toggles a default value
 * to input fields.	
 */
jQuery.fn.defaultValue = function(defaultValue, defaultValueColor) {
	return this.each(
		function(e, element) {
			var $t = $(element);
		  	element._defaultValue = defaultValue;
		  	element._modified = false;
		  	element._originalColor = $t.css("color");
		  	element._defaultValueColor = defaultValueColor == null? $t.originalColor : defaultValueColor;
		  	element.provideDefaultIfEmpty = function() {
			  	if ($t.val() == "") {
				  	$t.css("color", element._defaultValueColor);
			  		$t.val(element._defaultValue);
			  	}
		  	};
		  	
		  	element.isDefaultValue = function() {
		  		var isDefault = !element._modified && $t.val() == element._defaultValue;
		  		return isDefault;
		  	}
		  	
		  	element.clearIfDefault = function() {
			  	if (element.isDefaultValue()) {
			  		$t.val("");
			  	}	
		  	}
		  	
		  	$t.change(function() {
		  		if($t.val() != element._defaultValue && $t.val() != "") {
		  			$t.css("color", element._originalColor);
			  		element._modified = true;
		  		}
		  	});
		  	
		  	$t.focus(function() {
		  		$t.css("color", element._originalColor);
		  		element.clearIfDefault();
		  	});

		  	$t.blur(function() {
		  		element.provideDefaultIfEmpty();
		  	});
		  	
		  	$t.parents("form").submit(function() {
		  		element.clearIfDefault();
		  	});
		  	
		  	element.provideDefaultIfEmpty();
		  	return this;
		}
	);
};

jQuery.fn.hasDefaultValue = function() {
	var $result = {"isDefault": false};
	this.each(function(index, element) {
		$result.isDefault = element.isDefaultValue && element.isDefaultValue();
	});
	return $result.isDefault;
};

/**
 * Methods for form validation (popup bubbles, AJAX-based validation)
 */
jQuery.fn.showBubble = function(bubbleContents) {
	this.each(function(index, element) {
  		var $input = $(element);
		$("label[for=" + $input.attr("id") + "]").each(function() {
			var $label = $(this);
			$label.children("em.bubble").each(function() {
				var $oldMessage = $(this);
				$oldMessage.stop(true, true).animate({opacity: "hide", height: 0}, 300, function() {
					$oldMessage.remove();	
  				});
			});
			var $message = $('<em class="bubble"><span>' + bubbleContents + '</span></em>');
			$label.prepend($message);
			var $formRow = $label.parent("div.form_row");
			var relativeDistanceToInput = $input.position().left - $label.position().left;
			var backgroundImageRadix = 10;
			var backgroundX = relativeDistanceToInput - backgroundImageRadix + $input.width() / 2;
			$message.css("background-position", backgroundX + "px 100%");
			$message.stop(true, true).animate({opacity: "show", top: 0}, 750);
			$formRow.animate({paddingTop: $message.height() + 3}, 300, function() {
				updateContentHeight();
			});
			return this;
		});
		return this;
  	});
};
		
jQuery.fn.hideBubble = function() {
	this.each(function(index, input) {
	var $id = $(input).attr("id");
		$("label[for=" + $id + "]").each(function() {
			$(this).parent("div.form_row").animate({paddingTop: 0}, 500);
			$(this).children("em.bubble").each(function() {
				var $message = $(this); 
				$message.stop(true, true).animate({opacity: "hide", height: 0}, 700, function() {
					$message.remove();	
  				});
  			});
  		});
  	});
};

jQuery.fn.validate = function(url, synchronous) {
	var $result = {"passed": true};
	this.each(function(index, input) {
		var $input = $(input);
		var callback = function(validation) {
	    	if (validation.hasErrors) {
	    		$result.passed = false;
	    		$input.css("border-color", "red")
	    		      .showBubble(validation.message);
	    		$input.focus();
	    	} else {
	    		$input.css("border-color", "")
	    			  .hideBubble();
	    	}
		};
		var value = $input.hasDefaultValue()? "" : $input.val();
		$.ajax({
			  async: synchronous != true,
			  url: url,
			  dataType: 'json',
			  data:"value=" + value,
			  success: callback
		});
	});
	return $result.passed;
}

function updateContentHeight() {
	var $mainContent = $("#maincontent");
	var $contentWrapper = $("#content");
	if ($contentWrapper() != $mainContent.height() + 50) {
		$contentWrapper.height($mainContent.height());
	}
}

function setEqualContentHeight() {
	// equal height
	var _breadcrumb = $(".breadcrumb").innerHeight();
	var _main = $(".main-content").innerHeight();
	var _leftWrap = $(".left-sidebar").innerHeight();
	var _rightWrap = $(".right-sidebar").innerHeight();
	var _bottomSide = $(".bottom-sidebar").height();
	var _right = _rightWrap - _bottomSide;
	var _left = _leftWrap - _bottomSide;
	var maxColumnHeight = Math.max(_left, _right);
	
	if(maxColumnHeight > _main) {
		var titleHeight = $("div.title-page").innerHeight();
		$("#content").height(maxColumnHeight);		
		$("#content .main-content .inside-content").height(maxColumnHeight - titleHeight);
		$(".right-sidebar div.section:last").css("margin-bottom",0).css("border-bottom","1px solid #fff");
	} else {
		$("#content").css({'height' : (_main) + 'px'});			
	}
					
	$(".home #content").css({'height' : (_main) + 'px'});	
}