// settings and global functions
var ntv = new Object();
ntv = {
	debug: true,
	hasFirebug: "console" in window && "firebug" in window.console,
	random:	Math.round( Math.random() * 999998 + 1 ),
	basepath: window.location.protocol+"//"+window.location.host,
	videotag: "video",
	log: function( message ) {
		if( this.debug && this.hasFirebug ) {
			console.debug( message );
		}
	}
};


function videotracking() {
	var ivw_image = new Image();
	ivw_image.src="http://ntv.ivwbox.de/cgi-bin/ivw/CP/"+ntv.videotag+"_m;"+ntv_location+"/"+ntv_navipath+"?r="+escape(document.referrer)+"&d="+(Math.random()*100000);
}



// jquery functions

(function($) {

	$.fn.ntv_bookmarking = function() {
		var html = "";
		html += "<p>";
		html += "Lesezeichen im Browser setzen<br />";
		html += "<button class=\"bookmark\" type=\"button\">Lesezeichen</button>";
		html += "</p>";

		var event = null;
		if( navigator.userAgent.toLowerCase().indexOf('ie') != -1 ) {
			event = function() {
				try {
					window.external.AddFavorite( window.location, document.title );
				} catch ( e ) {	ntv.log(e);}
			};
		} else if( navigator.userAgent.toLowerCase().indexOf('moz') != -1 ) {
			event = function() {
				try {
					window.sidebar.addPanel( document.title, window.location, '' );
				} catch ( e ) { ntv.log(e);	}
			};
		}

		return this.each( function() {
			if ( event != null ) {
				$( this ).html( html ).find( "button.bookmark" ).click( event );
			} else {
				$( this );
			}
		});
	};


	$.fn.ntv_bookmarking_home = function() {
		if( navigator.userAgent.toLowerCase().indexOf('ie') != -1 ) {
			$(this).prepend('<li><a href="http://www.n-tv.de" onclick=" document.body.style.behavior=\'url(#default#homepage)\'; document.body.setHomePage( \'http://www.n-tv.de/\' ); return false; " title="n-tv.de als Startseite einrichten"><img src="http://www.n-tv.de/ads/images/icon_startseite.gif" alt="n-tv.de als Startseite einrichten"/></a></li>');
		} else if( navigator.userAgent.toLowerCase().indexOf('moz') != -1 ) {
			$(this).prepend('<li><a href="http://www.n-tv.de" onclick="window.sidebar.addPanel( \'n-tv.de\', \'http://www.n-tv.de\', \'\' ); return false" title="n-tv.de als Lesezeichen hinzuf&uuml;gen"><img src="http://www.n-tv.de/ads/images/icon_startseite.gif" alt="n-tv.de als Lesezeichen hinzuf&uuml;gen"/></a></li>');
		}
	};

	// click to big pictures
	$.fn.ntv_click_to_big = function() {
		return this.each( function() {
			var image = new Image();

			image.onload = function() {

				var $container = $( "<div class='big_pic' />" ).append( image );
				var img = $container.find( "img" ).get( 0 );

				$container.css( "height", $( "body" ).height()+"px" );
				$( "body" ).prepend( $container );

				var posX = $( self ).scrollTop() + ( $( self ).height()/2 - img.height/2 );
				var posY = $( self ).width() / 2 - img.width / 2;

				$( img ).css( "top", posX+"px" );
				$( img ).css( "left", posY+"px" );

				$container.fadeIn( "slow" );
				$container.bind( "click", function() {
					$container.fadeOut( "slow", function() {
						try {
							$( $container ).remove();
						} catch (err) {}
					});
				});

				var ivwImage = new Image();
				ivwImage.src = "http://ntv.ivwbox.de/cgi-bin/ivw/CP/"+ivw_code+";"+ntv_location+"/"+ntv_navipath+"?r="+escape(document.referrer)+"&d="+(Math.random()*100000);
			};

			image.src = this.href;




		});
	};

	// navigation for the fb ticker
	$.fn.ntv_fb_ticker_navigation = function() {
		$container = $( this );
		$( this ).find( "ul.navi li a" ).each( function( index, item ) {
			$( item ).click( function() {
				var activeLi = $container.find( "ul.navi li.active" ).get( 0 );
				var activateLi = $container.find( "ul.navi li" ).get( index );

				var activeTb = $container.children( "div.active" ).get( 0 );
				var activateTb = $container.children( "div" ).get( index );

				$( activeLi ).removeClass( "active" );
				$( activateLi ).addClass( "active" );

				$( activeTb ).removeClass( "active" );
				$( activateTb ).addClass( "active" );

				return false;
			});
		});
	};

	$.fn.ntv_format_articleH1 = function() {
		var headline = $(this).html().split(": ");
		$(this).html( "<span>" + headline[0] + "</span>" + headline[1]);
	}



	$.fn.ntv_hpnews_search = function() {
		return this.each( function() {
			var g_cleared = false;
			var g_interval = null;
			var inputField = $(this);

			if ($(this).attr("value").length >= 3) {
				window.clearInterval(g_interval);
				$('#hpnews_loading').show();
				g_interval = window.setInterval(function () {

					$("#hpnews_city").empty();

					$.get( "http://www.n-tv.de/ext.jsp?s=wetter&f=ntvsearchdeutschland/search_" + encodeURI($(inputField).val()) + ".xml",
					function( xml ){
						$( "item", xml ).each(
								function( i, item ){
									$("#hpnews_city").append("<option value=\"" + $( item ).attr( "wmo" ) + ";" + $( item ).attr( "city" ) + "\">" + $( item ).attr( "city" ) + "(" + $( item ).attr( "bl" ) + ")</option>");
								}
						);

						$('#hpnews_loading').hide();
					});

				/*
					//$.getJSON("http://www.n-tv.de/tools/wetter2007/dispatcher?tpl=content&decode=1&plz_ort_fragment="+encodeURI($(inputField).val())+"&jsoncallback=?", function (data) {
					$.getJSON("hpnews_json.html", function (data) {

						if (data) {
							$("#hpnews_city").empty();
							$.each(data.data, function (index, d) {
								$("#hpnews_city").append("<option value=\"" + d.key + "\">" + d.value + "</option>");
							});
						}
						$('#hpnews_loading').hide();
					});
				*/


					window.clearInterval(g_interval);
				}, 500);
			}
		});
	};

	$.fn.ntv_hpnews_generate = function() {
		return this.each( function() {


				$('#hpnews_code').hide();
				$("#hpnews_code textarea").empty();



				var html = "<iframe src=\"http://www.n-tv.de/myntv";
				html += "?";
				var elements = $("#hpnews_form input:checked");
				if (elements.length > 1) {
					$("#hpnews_error").hide();

					$.each(elements, function (index, item) {
						html += item.name + "=" + item.value;
						if (index < elements.length - 1) {
							html += "&";
						}
					});
					if ($("#hpnews_form input[@name=\"size\"]:checked").val() == "maxi") {
						if ($("#hpnews_form #hpnews_city").val()) {
							var params = $("#hpnews_form #hpnews_city").val().split(";");
							html += "&city=" + encodeURI(params[1]) + "&wmo=" + params[0];
						} else {
							html += "&city=Berlin&wmo=10384";
						}
					}
					html += "\" name=\"n-tv.de\" scrolling=\"no\" frameborder=\"0\" ";
					if ($("#hpnews_form input[@name=\"size\"]:checked").val() == "mini") {
						html += "width=\"200px\" height=\"250px\">";
					} else {
						if ($("#hpnews_form input[@name=\"size\"]:checked").val() == "midi") {
							html += "width=\"300px\" height=\"300px\">";
						} else {
							if ($("#hpnews_form input[@name=\"size\"]:checked").val() == "maxi") {
								html += "width=\"400px\" height=\"350px\">";
							}
						}
					}
					html += "</iframe>";

					$("#hpnews_form #hpnews_code textarea").val(html);
					$('#hpnews_code').toggle(500);

				} else {
					$("#hpnews_error").show();
				}
		});

	};

	$.fn.ntv_hpnews_show = function() {
		return this.each( function() {
			if($(this).attr("id")=="hpnews_showmini"){
				$('#iframe_mini').toggle(500);
				$('#hpnews_mini').attr('checked','checked');
				//$('#hpnews_weather').hide();
			}
			if($(this).attr("id")=="hpnews_showmidi"){
				$('#iframe_midi').toggle(500);
				$('#hpnews_midi').attr('checked','checked');
				//$('#hpnews_weather').hide();
			}
			if($(this).attr("id")=="hpnews_showmaxi"){
				$('#iframe_maxi').toggle(500);
				$('#hpnews_maxi').attr('checked','checked');
				//$('#hpnews_weather').show();
			}
		});
	};


	// make text clickable
	$.fn.ntv_js_link = function() {
		return this.each( function() {
			var link = $( this ).find( "a" ).get( 0 );

			if( link != undefined ) {
				var href = $( link ).attr( "href" );
				var target = $( link ).attr( "target" ) || "_self";

				$( this ).css( "cursor", "pointer" );
				$( this ).click( function() {
					window.open( href, target );
				});
			}
		});
	};


	$.fn.ntv_media_tab_teaser = function(options) {
		return this.each(function(){
			var tabList = $(options.tabList, this);
			var content = $(options.content, this);

			$("a", tabList).click(function(){
				$("li", tabList).removeClass("active");
				$(this).closest("li").addClass("active");

				var index = $("a", tabList).index(this);
				$(content).removeClass("active");
				$(content).eq(index).addClass("active");

				return false;
			});


		});
	};


	$.fn.ntv_media_teaser = function( options ) {
		var settings = $.extend({
			interval: 5000,
			speed: 350,
			wrapper: ".wrapper_nav"
		}, options);

		return this.each( function() {
			var teaser = this;

			// navigation functionality
			/*
			var $navigation = $( this ).find( "ul#mediathek_teaser_header" );
			var $links = $( this ).find( "a.videos, a.programm" );

			$links.each(function( index, link ){
				$( this ).click(function(){
					$navigation.find( "li.active" ).removeClass( "active" );
					$( this ).parent( "li" ).addClass( "active" );
					var container = $( this ).attr( "href" );

					$( teaser ).find( "#mediathek_teaser_body div.active" ).removeClass( "active" );
					$( container ).addClass( "active" );

					return false;
				});
			});
			*/

			// fader functioniality
			var $items = $( this ).find( "ul.fade li" );
			var $wrapper = $( this ).find( settings.wrapper );

			var index = 0;
			var count = $items.size();
			var interval = null;
			var intervalStart = null;
			var timeRemaining = null;

			// pause and resume fading
			$items.hover(
				function() {
					timeRemaining = settings.interval - ( new Date().getTime() - intervalStart );
					window.clearTimeout( interval );
				},
				function(){
					setFadeTimeout( timeRemaining );
				}
			);

			function slide( active, next, clear ) {


				$wrapper.html( $( ".wrapper_text", next ).html() );
				$( active ).removeClass( "active" );
				$( next ).addClass( "active" );

				/*

				// text change
				$wrapper.fadeOut( settings.speed, function() {
					$wrapper.html( $( ".wrapper_text", next ).html() );
					$wrapper.fadeIn( settings.speed );
				});

				// image change
				$( active ).fadeOut( settings.speed, function() {
					$( active ).removeClass( "active" );
					$( next ).fadeIn( settings.speed, function(){
						$( next ).addClass( "active" );
					});

				});

				*/

				clear ? window.clearTimeout( interval ) : setFadeTimeout( settings.interval );
			}

			function setFadeTimeout( timeout ){
				var timout = timout || settings.interval;

				interval = window.setTimeout( function() {
					var active = $items[index];
					index < count-1 ? index++ : index = 0;
					var next = $items[index];
					slide( active, next, false );
				}, timeout );

				intervalStart = new Date().getTime();
			}

			if(count > 0) {
				setFadeTimeout( settings.interval );
			}

		});
	};


	$.fn.ntv_medrect = function() {
		if( $(this).height() >  30 && $("#medrect_ref").length>0 ){
			$("#medrect_ref").before('<div class="medrect_header">Anzeige</div>');
			$(this).css({'top' : $("#medrect_ref").offset().top,  'left' : $("#medrect_ref").offset().left, 'display' : 'block'});
			$("#medrect_ref").css({'width' : $("#medrect").width(), 'height' : $("#medrect").height()});
			$("#medrect_ref").after('<div class="medrect_footer"></div>');
		}
	}

	$.fn.ntv_medrectprem = function() {
		if( $(this).height() >  30 && $("#medrectprem_ref").length>0 ){
			$(".mediathek_teaser hr").hide();
			$(this).css({'top' : $("#medrectprem_ref").offset().top,  'left' : $("#medrectprem_ref").offset().left, 'display' : 'block'});
			$("#medrectprem_ref").css({'width' : $("#medrectprem").width(), 'height' : $("#medrectprem").height()});
		}
	}

	$.fn.ntv_navigation = function( settings ) {
		// set icon for quicknavi
		$( "#quickNavigation" ).ntv_bookmarking_home();

		// settings
		var s = $.extend({
			activeClass: "hover",
			last_link: null,
			pageWidth: 996,
			time: 250,
			timeout: null,
			speed: 'fast'
		}, settings);

		// events
		return this.each( function() {

			// layer events + positioning
			var $layer = $( this ).next();

			if( $layer.length !== 0 ) {
				// if the layer is to far to the right.
				if( $( this ).offset().left + $layer.width() > s.pageWidth ) {
					var overhang = ( $( this ).offset().left + $layer.width() ) - s.pageWidth;
					$layer.css( "left", $( this ).offset().left - overhang );
				}

				$layer.bind( "mouseover", function(e) {
					window.clearTimeout( s.timeout );
				});
				$layer.bind( "mouseout", function(e) {
					s.timeout = window.setTimeout( function() {
						navigator.userAgent.toLowerCase().indexOf('ie') != -1 ?
							$layer.hide() : $layer.fadeOut( s.speed );
					}, s.time );
				});

				// secondary links events
				$( this ).bind( "mouseover", function(e) {
					if( s.last_link != this ) {
						navigator.userAgent.toLowerCase().indexOf('ie') != -1 ?
							$( s.last_link ).next().hide() : $( s.last_link ).next().fadeOut( s.speed );
						s.last_link = this;
					} else {
						window.clearTimeout( s.timeout );
					}
					navigator.userAgent.toLowerCase().indexOf('ie') != -1 ?
						$layer.show() : $layer.fadeIn( s.speed );
				});
				// mouseout
				$( this ).bind( "mouseout", function(e) {
					s.timeout = window.setTimeout( function() {
						navigator.userAgent.toLowerCase().indexOf('ie') != -1 ?
							$layer.hide() : $layer.fadeOut( s.speed );
					}, s.time );
				});

				// layer links events
				var $links = $layer.find( "a" );
				// generate tree for coloring
				$links.each( function( index, anchor ) {
					$( anchor ).data( "tree", new Array() );
					(function( a ) {
						$( anchor ).data( "tree" ).push( a );
						var parent = $( a ).closest( "ul" ).prev( "a" );
						if( parent.length !== 0 ) {
							arguments.callee( parent );
						}
					})( anchor );
				});
				$links.hover(
					// mouseover
					function(e) {
						var tree =  $( e.target ).data( "tree" );
						$.each( tree, function() {
							$( this ).addClass( s.activeClass );
						});
					},
					// mouseout
					function(e) {
						var tree =  $( e.target ).data( "tree" );
						$.each( tree, function() {
							$( this ).removeClass( s.activeClass );
						});
					}
				);
			}
		});
	};


	$.fn.ntv_player = function(settings) {
		var options = $.extend(
				{
					w3c: true,
					bgcolor: "#333333",
					advertising: true,
					modus: "vod",
					theme: "video"
				}, settings
		);

		ntv.videotag = options.theme;

		var src = relat_prefix + "flash/NTV_Player_AS3.swf?f="+options.video+"&pm="+options.modus;
		if(options.advertising == true){
			src = src + "&preroll=http://ad.de.doubleclick.net/adx/www.nntv.de/" + ivw_code + ";pack=;theme="+options.theme+";"+ip_additional+"playersize=" + options.width +  "x" + options.height + ";sz=320x240;tile=10;pos=pre;dcmt=text/xml;ord="+ip_random;
		}
		if( options.image ){
			src = src + "&ppic=" + options.image;
		}

		return this.each(function(){
			$(this).flashembed(
					{
						src: src,
						width: options.width,
						height: options.height,
						w3c: options.w3c,
						bgcolor: options.bgcolor
					});
		});
	};

	$.fn.ntv_poll = function( url ) {
		return this.each(function(){
			var container = this;

			$( this ).find( "form" ).submit(function() {
				var choice = $( this ).find( "input:checked" );
				$( container ).load( url, choice);
				return false;
			});
		});
	};

	/*
	$.fn.ntv_poll = function() {

		return this.each( function() {
			var poll = this;
			var poll_container = $(this).find( ".poll_container" );
			var result_link = $(this).find( "a.result" );

			$( this ).find( "form" ).submit(function() {
				var choice = $( this ).find( "input:checked" );
				var url = this.action;

				$.ajax({
					type: "POST",
					url: url,
					data: choice,
					dataType: "xml",
					success: function( xml ) {
						var result = $( "<table cellspacing='0' />" );
						result.append( "<caption>"+ $( "question", xml ).text() +"</caption>" );

						$( "answer", xml ).each(function(index, answer) {

							result.append( "<tr><th>" + $(answer).text() + "</th></tr>" );
							var position = $(answer).attr("percent") > 85 ? "poll_left" : "poll_right";
							result.append(
								"<tr><td><div>" +
								"<p style='display: none; width:" + $(answer).attr("percent") + "%;'>" +
								"<span class='"+ position +"'>" + $(answer).attr("percent") + "%</span>" +
								"</p></div></td></tr>"
							);
						});

						$(poll_container).html( result );
						$(poll).css( "backgroundImage", "none" );
						$(result).find( "p" ).fadeIn();
						$(result_link).fadeOut();
					},
					error: function (XMLHttpRequest, textStatus, errorThrown) {
						alert( textStatus );
					}
				 });

				return false;
			});
		});
	};
	*/

	$.fn.ntv_search = function() {

		return this.each(
				function() {
					var activeID;
					var a = $(this).find( ".select a" ).each(
						function() {

							if( $(this).attr( "class" )=='active' ) {
								activeID = $(this);
							}

							$(this).click(
									function(){
										$(activeID).removeClass( 'active' );
										$(this).addClass( 'active' );
										activeID = $(this);

										//$( "#search_form #searchabout" ).attr( "value",$(this).attr( "id" ) );

										$( "#search_form" ).attr( { "action": "", "target": "_self" } );

										if ( $(this).attr("id")=="ntv" ){
											$( "#search_form input[name='at']" ).attr( "value","all" );
										}
										if ( $(this).attr("id")=="news" ){
											$( "#search_form input[name='at']" ).attr( "value","m" );
										}
										if ( $(this).attr("id")=="gallery" ){
											$( "#search_form input[name='at']" ).attr( "value","b" );
										}
										if ( $(this).attr("id")=="video" ){
											$( "#search_form input[name='at']" ).attr( "value","v" );
										}

										if ( $(this).attr("id")=="quote" ){
											//$( "#search_form" ).attr("action","http://kurse.teleboerse.de/DE/showpage.aspx");
											//$( "#search_form" ).attr("target","_blank");
											window.open("http://kurse.teleboerse.de/DE/showpage.aspx?keyword="+$( "#search_form input[name='q']" ).attr( "value"), "tb");
											return false;

										}

										var issearchstring = false;
										var inp = $( "#search_form" ).find( "input" ).each(
												function() {
													if( $(this).attr( "type" ) == "text" && $(this).attr( "value" )){
														issearchstring = true;
													}
												}
										);
										if (issearchstring==true){
											$( "#search_form" ).submit();
										}
										return false;
									}
							);

						}
					);

					var isdetailsearch = false;
					var detailinp = $( "#search_form #detailsearch" ).find( "input" ).each(
							function() {
								if( $(this).attr( "type" ) == "text" && $(this).attr( "value" )){
									isdetailsearch = true;
								}
							}
					);
					if (isdetailsearch==true){
						$('#detailsearch').show();
						var a = $(this).find( "a.more_light" ).each(
								function() {
									$(this).html("Detailsuche schlie&szlig;en");
								}
						);
					}
				}
		);
	};



	$.fn.ntv_search_detail = function() {
		return this.each( function() {
			if ( $('#detailsearch').css("display") == "none" ){
				$('#detailsearch').show();
				$(this).html("Detailsuche schlie&szlig;en");
			} else {
				$('#detailsearch').hide();
				$(this).html("Detailsuche");
			}
		});
	};


	$.fn.ntv_search_head = function() {
		return this.each(function () {
			$( this ).submit(function(){
				var id = $( "input:checked", this ).attr( "id" );
				switch( id ) {
					case "shares":
						var url = "http://kurse.teleboerse.de/DE/showpage.aspx?keyword=" + $( "input#search", this ).val();
						var teleb = window.open(url, "teleboerse");
						teleb.focus();
						return false;
						break;
					case "yahoo":
						var url = "http://de.yhs.search.yahoo.com/yhs/search?ei=ISO-8859-1&fr=yhs-ntv&lyt=st&partnerid=yhs-ntv&query=&m=o&p=" + $( "input#search", this ).val();
						var yahoo = window.open(url, "yahoo");
						yahoo.focus();
						return false;
						break;
					default:
						return true;
						break;
				}
			});
		});
	};


	$.fn.ntv_slideshow = function( images, settings ) {
		var s = $.extend({
			/* defaults */
			buttonNextClass: 'next',
			buttonPrevClass: 'previous',
			fadeTime: 200,
			imgContainerClass: 'imgContainer',
			loadingAnimClass: 'loading',
			onClick: function(){},
			textContainerClass: 'textContainer',
			preloadImages: true
		}, settings );

		if( s.preloadImages ) {
			(function(index) {
				var tempImg = new Image();
				var callee = arguments.callee;
				tempImg.src = images[index];
				tempImg.onload = function() {
					images[index + 1] && callee(index + 1);
				};
			})(0);
		}

		return this;
	};


	$.fn.ntv_social_bookmarking = function() {
		return this.each( function() {
			var list = $( this ).find( "ul.jq_social_bookmarks_list" );
			var target = $( this ).find( "span.bm_service" );

			// Rollover
			$( list ).find( "a" ).each( function( index, li ) {
				$( li ).hover(
					function() {
						var text = $( this ).text();
						$( target ).text( text );
					},
					function() {
						$( target ).text( "" );
					}
				);
			});

			// neues Fenster bei click
			$( list ).find( "a" ).each( function() {
				$( this ).click( function() {
					window.open( $(this).attr( "href" ) );
					return false;
				});
			});

		});

	};

	$.fn.ntv_video_play = function() {
		return this.each( function() {
			try {
				var a = $(this).find( "a" ).get( 0 );
				var href = a.href;
				$( a ).append( "<span class='play'></span>" ).css( "cursor", "pointer" );
				$( this ).bind( "click", function( e ) {
					ntv.log( "open: " + href );
					return false;
				});
			} catch ( e ) {}
		});
	};



	// Mediathek

	$.fn.ntv_media_detail = function( options ) {
		var settings = $.extend({
			backgroundColor: "#383838",
			linkColor: "#FFFFFF"
		}, options);

		return this.each( function() {
			var $container = $( this );
			var $link = $( this ).find( "a" );
			var $detail = $( this ).find( ".detail" );
			var backgroundColor = $( this ).css( "backgroundColor" );
			var timeout = null;

			$link.hover(
					// over
					function() {

						timeout = window.setTimeout(function(){
							//$container.css( "backgroundColor", settings.backgroundColor );
							$detail.css( "backgroundColor", settings.backgroundColor );
							$detail.show();
						}, 200);
					},
					// out
					function() {
						window.clearTimeout( timeout );
						$detail.hide();
						//$container.css( "backgroundColor", backgroundColor );
						$detail.css( "backgroundColor", backgroundColor );
					}
			);
		});

	};

	$.fn.ntv_slideTeaser = function() {

		var slider = $(this);
		var duration = 1000;
		var left = 0;
		var teaserCount = slider.find("ul").children("li").length - slider.find("ul li ul").children("li").length;
		var slideWidth = slider.find( "ul li" ).width() + parseInt( slider.find( "ul li" ).css( "padding-right") );
		var slideEnd = teaserCount * slideWidth - slider.width() - parseInt( slider.find( "ul li" ).css( "padding-right") );
		slider.find( ".slide" ).css( "height", slider.find( "ul li" ).height() );

		if ( teaserCount * slideWidth > 690 ){
			slider.find( ".forward a" ).css( "display", "block" );
		}

		slider.find( ".forward a" ).click(
			function(){
				slider.find( "ul" ).animate( { left: left - slideWidth }, duration );
				slider.find( ".backward a" ).css( "display", "block" );
				left = left - slideWidth;
				if (left <= -slideEnd ){
					slider.find( ".forward a" ).css( "display", "none" );
				}
				return false;
			}
		);

		slider.find( ".backward a" ).click(
			function(){
				slider.find( "ul" ).animate( { left: left + slideWidth }, duration );
				slider.find( ".forward a" ).css( "display", "block" );
				left = left + slideWidth;
				if (left >= 0 ){
					slider.find( ".backward a" ).css( "display", "none" );
				}
				return false;
			}
		);


		slider.find(".teaser_mod" ).ntv_modDetail();


	};

	$.fn.ntv_prevBox = function() {

		var newest_link = $(this).find( "a.newest" );
		var most_viewed_link = $(this).find( "a.most_viewed" );
		var newest_box = $(this).find( "div.newest" );
		var most_viewed_box = $(this).find( "div.most_viewed" );

		$(newest_link).click(
			function(){
				$( most_viewed_link ).parent().removeClass( "active" );
				$( newest_link ).parent().addClass( "active" );

				$(newest_box).show();
				$(most_viewed_box).hide();
				return false;
			}
		);
		$(most_viewed_link).click(
			function(){
				$( newest_link ).parent().removeClass( "active" );
				$( most_viewed_link ).parent().addClass( "active" );

				$(most_viewed_box).show();
				$(newest_box).hide();
				return false;
			}
		);

		$(this).find( ".ajax_container" ).ntv_scrollAjax();
	};

	$.fn.ntv_scrollAjax = function() {

		var container = $(this);
		var html_cache = new Object();

		var init = function(){

			var backward = $(container).find( ".backward a" );
			var forward = $(container).find( ".forward a" );

			$(backward).css( "display", "none" );
			$(forward).css( "display", "none" );

			if($(backward).attr("href")){
				preload($(backward));
			}
			if($(forward).attr("href")){
				preload($(forward));
			}

		}

		var preload = function(button){
			var url = $(button).attr("href");

			if(!html_cache[url]){
				$.get( url, function(html) {
					html_cache[url] = html;
					setClick(button);
				});
			}
			else{
				setClick(button);
			}
		}

		var setClick = function(button){

			$(button).click(
				function(){
					$(container).html(html_cache[$(this).attr("href")]);
					init();
					return false;
				}
			);
			$(button).css( "display", "block" );
		}

		init();

	};


	$.fn.ntv_modDetail = function() {

		var ref_html;

		$( this ).find( "> li" ).each( function() {

			$( this ).find( ".teaser img" ).click( function() {

				ref_html = $( this ).closest("li").find(".detail").html();

				$('#mod_detail').toggle( 1000, function() {
					$("#mod_detail .wrapper").html( ref_html );
				});
				$("#mod_detail").toggle(1000);
			});
		});
	};



	$.fn.ntv_bilder_slideshow = function( options ) {
		var settings = $.extend({
			backward: "#wrapper_img a.backward",
			forward: "#wrapper_img a.forward",
			images: null,
			imageContainer: "#wrapper_img",
			loadImageSrc: relat_prefix + "bilderserie/img/loader.gif",
			speed: "slow",
			startIndex: 0,
			textContainer: "#wrapper_txt p"
		}, options);

		var $backward = $( settings.backward );
		var $forward = $( settings.forward );
		var $imageContainer = $( settings.imageContainer );
		var imageContainerHeight = $imageContainer.height();
		var $textContainer = $( settings.textContainer );

		var $loadingImg = $( "<img />" ).load( function () {
			$( this ).css( "marginTop", (imageContainerHeight - this.height)/2 );
			$imageContainer.append( this );
		}).attr({
			alt: "Bild wird geladen",
			src: settings.loadImageSrc
		});


		var imgCount = settings.images.length;
		var index = 0;
		index = settings.startIndex>0 && settings.startIndex<=imgCount ? settings.startIndex : index;

		var switchImage = function( i, preload, getIVW ) {

			var $nextImg = $( "<img />" ).load(

					function() {
						var marginTop = ( imageContainerHeight - this.height ) / 2;
						$( this ).
							css({
								//cursor: "pointer",
								display: "none",
								marginTop: marginTop
							})
							.addClass( "slide_img" );
						$loadingImg.hide();
						$imageContainer.find( "img.slide_img" ).replaceWith( this );
						$( this ).fadeIn( settings.speed, function(){
						});
						$textContainer.html( $("#wrapper_captions p:nth-child(" + (index+1) + ")").html() );


						if( getIVW ){
							var ivwImage = $( "<img />" );
							var src = "http://ntv.ivwbox.de/cgi-bin/ivw/CP/"+ivw_code+";"+ntv_location+"/"+ntv_navipath+"?r="+escape(document.referrer)+"&d="+(Math.random()*100000);
							ivwImage.attr({
								src: src
							});
						}
					}
			).attr( {
				src: settings.images[i].src,
				alt: "",
				title: settings.images[i].credit != "" ? "(Foto: " + settings.images[i].credit + ")" : ""
				}
			);

			if( preload && i < imgCount-1 ) {
				var $preloadImage = $( "<img />" );
				$preloadImage.attr( "src", settings.images[i+1].src );
			}

			if( index == 0){
				$(".slideshow h1").show();
				$(".slideshow h2").show();
				$(".slideshow h3").show();
			}
			else{
				$(".slideshow h1").hide();
				$(".slideshow h2").hide();
				$(".slideshow h3").hide();
			}

		};

		// get the first image and show it
		switchImage( index, true, false );

		// register click events
		return this.each( function() {

			$forward.click(function() {
				index == imgCount-1 ? index = 0 : index++;
				switchImage( index );
				return false;
			});

			$backward.click(function() {
				index == 0 ? index = imgCount-1 : index--;
				switchImage( index );
				return false;
			});
		});
	};



	$( document ).ready( function() {

		// Hide toggle elements if user has javascript enabled.
		$( "#comment" ).hide();
		$( "#email_form" ).hide();
		$( "#bookmarking" ).hide();
		$( "#detailsearch" ).hide();
		$( ".jq_close" ).show();

		// suche head
		$( "#header_top form" ).ntv_search_head();

		// Make p clickable on index pages.
		$( ".jq_link" ).ntv_js_link();

		// Add rollover, etc to the social bookmark links
		$( ".jq_socialbookmarks" ).ntv_social_bookmarking();

		// add bookmarking code for ie and mozilla
		$( ".jq_bookmarking" ).ntv_bookmarking();

		// video play button
		$( ".jq_videoteaser" ).ntv_video_play();

		// fb_ticker_naviagtion
		$( "#jq_fb_ticker" ).ntv_fb_ticker_navigation();

		// Add rollover, etc to the fastsearch navi
		$( ".jq_search" ).ntv_search();

		// video_teaser
		$( ".mediathek_teaser" ).ntv_media_teaser();

		// umfragen
		$( ".poll" ).ntv_poll();

		// weather
		$("#weather_head_ort").focus( function() {
			$("#weather_head_ort").val("");
			$("#weather_head_plz").val("-1");
			$("#weather_head_ort").unbind("focus");
		});

		//placement rectangle
		$("#medrect").ntv_medrect();
		$("#medrectprem").ntv_medrectprem();

		//Reset HP News
		$("#hpnews_search").val("z.B. Berlin o. 10119");

		//Mediathek
		//$( ".program ul.prog li" ).ntv_media_detail( { "backgroundColor": "#535353" } );
		//$( ".sendungen ul li" ).ntv_media_detail( { "backgroundColor": "#535353" } );

	});
})(jQuery);
