


// ----- GENERAL STUFF -----


// Handle Formular Over-Label
$top('label.over-input').labelOver();

// Image Preloading
jQuery.preloadImages = function() {
	for(var i = 0; i<arguments.length; i++) {
		jQuery("<img>").attr("src", arguments[i]);
	}
};

// Loading-Animation
top.showLoader = function(parent) {
	// _DOC - Please use #pagecontainer as parent if inside popups
	var parentPos = $top(parent).css("position");
	$top(parent).css("position", "relative").append('<div class="loading">Vorgang wird geladen, bitte warten &hellip;</div>');
	var loader = $top(".loading");

	loader.bind("ajaxStart", function() {
		$top(this).show();
		$top(this).animate({"opacity": "0.8"}, "fast");
	});

	loader.bind("ajaxStop", function() {
		$top(this).animate({"opacity": "0.0"}, "fast");
		$top(this).remove();
		$top(parent).css("position", parentPos);
	});
}



// ----- Slideshow -----


top.slideshow = {
	init: function(slideshowId, jsonData) {
		// create some variables
		this.slideshowId = slideshowId;
		this.imagesSrc = [];
		this.altTags = [];
		this.descriptions = [];
		this.copyrights = [];
		this.adTags = [];

		this.totalPictures = jsonData.meta.totalPictures;
		this.callbackURL = jsonData.meta.callbackUrl;
		this.totalAds = jsonData.ads.length;
		this.adCount = parseInt(jsonData.meta.adCount) + 1;
		this.actualImage = 0;
		this.click = 0;
		this.shownAd = 0;
		this.lastAdShown = false;
		this.hash = window.location.hash;
		this.hash = parseInt(this.hash.substring(1,(this.hash.length)));

		this.image = $top("#" + this.slideshowId + " .ss-img");
		this.info = $top("#" + this.slideshowId + " .ss-info");
		this.description = $top("#" + this.slideshowId + " .ss-desc");
		this.copyright = $top("#" + this.slideshowId + " .ss-copy");
		this.prevImgContainer = $top("#" + this.slideshowId + " .ss-nav-prev");
		this.nextImgContainer = $top("#" + this.slideshowId + " .ss-nav-next");

		for(var i=0; i<this.totalPictures; i++) { // push data in arrays
			this.imagesSrc.push(jsonData.content[i].details.url);
			this.altTags.push(jsonData.content[i].details.altText);
			this.descriptions.push(jsonData.content[i].details.description);
			this.copyrights.push(jsonData.content[i].details.copyright);
		}

		for(i=0; i<this.totalAds; i++) { // push ads in array
			this.adTags.push(jsonData.ads[i].url);
		}

		$top("#" + slideshowId + " .ss-nav-next").bind("click", function() { // bind next picture function
			top.slideshow.nextPic(top.slideshow.actualImage);
		}).removeClass("inactive");

		$top("#" + slideshowId + " .ss-nav-prev").bind("click", function() { // bind prev picture function
			top.slideshow.prevPic(top.slideshow.actualImage);
		}).removeClass("inactive");

		this.copyright.empty();
		if(this.hash < this.totalPictures) { // we got a hash, we have to show the specific picture and its info
			this.actualImage = this.hash;
			this.nextImage = this.hash + 1;
			$top.preloadImages(this.imagesSrc[this.nextImage]);
			this.image.attr("src", this.imagesSrc[this.hash]).attr("alt", this.altTags[this.hash]);
			this.description.html(this.descriptions[this.hash]);
			if(this.copyrights[this.hash] != "") { this.copyright.html("&copy; " + this.copyrights[this.hash]); }
			this.info.html(this.hash+1 + ' / ' + parseInt(this.totalPictures+1));
		} else { // show first picture
			this.image.attr("src", this.imagesSrc[0]).attr("alt", this.altTags[0]);
			this.description.html(this.descriptions[0]);
			if(this.copyrights[0] != "") { this.copyright.html("&copy; " + this.copyrights[0]); }
			this.info.html('1 / ' +  parseInt(this.totalPictures+1));
		}

		top.slideshow.createNavDivs();
		$top.preloadImages(this.imagesSrc[1]);
	},

	createNavDivs: function() {

		// calculate the nav divs: divide the imagewidth / 2
		var width = parseInt($top("#" + this.slideshowId + " .ss-img-cnt").css("width"))/2;
		var height = parseInt($top("#" + this.slideshowId + " .ss-img-cnt").height());

		// write invisible nav container...
		this.image.after('<div class="ss-nav-prev-img" style="width: ' + width + 'px; height: ' + height + 'px;"></div><div class="ss-nav-next-img" style="width: ' + width + 'px; height: ' + height + 'px; left: ' + width + 'px;"></div>');

		// ...and bind the functions on it
		$top("#" + this.slideshowId + " .ss-nav-next-img").bind("click", function() {
			top.slideshow.nextPic(top.slideshow.actualImage);
		}).bind("mouseenter", function() {
			$top(this).addClass("hover-next");
		}).bind("mouseleave", function() {
			$top(this).removeClass("hover-next");
		});

		$top("#" + this.slideshowId + " .ss-nav-prev-img").bind("click", function() {
			top.slideshow.prevPic(top.slideshow.actualImage);
		}).bind("mouseenter", function() {
			$top(this).addClass("hover-prev");
		}).bind("mouseleave", function() {
			$top(this).removeClass("hover-prev");
		});

		// if the first image is shown, deactivate and hide "back" button
		if(this.actualImage == 0) {
			$top("#" + this.slideshowId + " .ss-nav-prev").addClass("inactive");
			$top("#" + this.slideshowId + " .ss-nav-prev-img").hide();
		}
	},

	changeNavDivs: function() {

		// change the height of the invisible navdivs
		var height = $top("#" + this.slideshowId + " .ss-img").height();
		$top(".ss-nav-prev-img").css("height", height);
		$top(".ss-nav-next-img").css("height", height);
	},

	nextPic: function(image) { // show next picture
		image++;
		this.nextImage = image + 1;
		countPI(image + 1); // Count an PI
		//ns_onclick(this, '', '&wa_p_pg=' + this.nextImage + 1, 'hidden');
		$top.preloadImages(this.imagesSrc[this.nextImage]); // preload next image
		if(this.actualImage >= 0) { // show back button
			$top("#" + this.slideshowId + " .ss-nav-prev").removeClass("inactive");
			$top("#" + this.slideshowId + " .ss-nav-prev-img").show();
		}
		if(image < this.totalPictures) {
			this.click++;
			if(this.click % this.adCount == 0 && this.adCount > 0) { // do we have to show an ad?
				top.slideshow.showAd();
			} else { // no
				if(this.lastAdShown) { // the last element was an ad
					// remove ad, show nav divs, build image markup, show description, bind click on image
					this.lastAdShown = false;
					$top("#slideshowAd").remove();
					$top("#" + this.slideshowId + " .ss-nav-prev-img").show();
					$top("#" + this.slideshowId + " .ss-nav-next-img").show();
					$top("#" + this.slideshowId + " .ss-img-cnt").append('<img class="ss-img" src="' + this.imagesSrc[image] + '" alt="' + this.altTags[image] + '" />').fadeIn("slow");
					this.description.show();
					this.image = $top("#" + this.slideshowId + " .ss-img");
					this.image.bind("click", function() {
						top.slideshow.nextPic(top.slideshow.actualImage);
					});
				} else {
					// just switch the image and its alttext
					this.image.hide().attr("src", this.imagesSrc[image]).attr("alt", this.altTags[image]).fadeIn("slow");
				}
				// change description, copyright, navdivs, hash and info
				this.description.html(this.descriptions[image]);
				this.copyright.empty();
				if(this.copyrights[image] != "") { this.copyright.html("&copy; " + this.copyrights[image]); }

				top.slideshow.changeNavDivs();
				document.location.hash = image;
				top.slideshow.actualImage = image;
				this.info.html(this.nextImage + ' / ' +  parseInt(this.totalPictures+1));
			}
		} else { // this was the "last" image, jump to callback url
			location.href = this.callbackURL;
		}
	},

	prevPic: function(image) { // show prev picture
		image--;
		this.nextImage = image - 1;
		countPI(image + 1); // Count an PI
		//ns_onclick(this, '', '&wa_p_pg=' + this.nextImage + 1, 'hidden');
		$top.preloadImages(this.imagesSrc[this.nextImage]); // preload next image
		if(image >= 0) {
			this.click++;
			if(this.click % this.adCount == 0 && this.adCount > 0) { // do we have to show an ad?
				top.slideshow.showAd();
			} else { // no
				if(this.lastAdShown) { // the last element was an ad
					// remove ad, show nav divs, build image markup, show description, bind click on image
					this.lastAdShown = false;
					$top("#slideshowAd").remove();
					$top("#" + this.slideshowId + " .ss-nav-prev-img").show();
					$top("#" + this.slideshowId + " .ss-nav-next-img").show();
					$top("#" + this.slideshowId + " .ss-img-cnt").append('<img class="ss-img" src="' + this.imagesSrc[image] + '" alt="' + this.altTags[image] + '" />').fadeIn("slow");
					this.description.show();
					this.image = $top("#" + this.slideshowId + " .ss-img");
					this.image.bind("click", function() {
						top.slideshow.nextPic(top.slideshow.actualImage);
					});
				} else {
					// just switch the image and its alttext
					this.image.hide().attr("src", this.imagesSrc[image]).attr("alt", this.altTags[image]).fadeIn("slow");
				}
				// change description, copyright, navdivs, hash and info
				this.description.html(this.descriptions[image]);
				this.copyright.empty();
				if(this.copyrights[image] != "") { this.copyright.html("&copy; " + this.copyrights[image]); }
				var temp = image+1
				this.info.html(temp + ' / ' +  parseInt(this.totalPictures+1));
				top.slideshow.changeNavDivs();
				document.location.hash = image;
				top.slideshow.actualImage = image;
			}
			if(this.nextImage < 0 ) { // hide back button
				$top("#" + this.slideshowId + " .ss-nav-prev").addClass("inactive");
				$top("#" + this.slideshowId + " .ss-nav-prev-img").hide();
			}
		}
	},

	showAd: function() {
		if(useAdserver) { // do we use an adserver?
			// new tile var
			ad_ts=(Math.random()+"012345678910abc").toString().substr(2,30);
			// count up shown ads until now, start from 0 if the last is shown
			this.shownAd++;
			if(this.shownAd == this.totalAds) {
				this.shownAd = 0;
			}
			// "build" temporarily ad
			var tempAd = eval("'" + this.adTags[this.shownAd] + "'");
			// insert frame after image, remove image, hide navdivs and description
			this.image.after('<iframe id="slideshowAd" frameborder="0"></iframe>').remove();
			$top("#" + this.slideshowId + " .ss-nav-prev-img").hide();
			$top("#" + this.slideshowId + " .ss-nav-next-img").hide();
			this.description.hide();
			// add attributes to adframe, set variable
			//alert(tempAd)
			$top("#slideshowAd").attr("src", tempAd);
			$top("#slideshowAd").attr("width", "608");
			$top("#slideshowAd").attr("height", "400");
			$top("#slideshowAd").css("background-color", "#111111");
			this.lastAdShown = true;
		}
	},

	changePicFromHash: function(hash) {
		// this is a function which will be called, if the hash is changed (back/next button of browser)
		// it just changes the image and its information from the array to the hash value
		this.hash = hash;
		this.actualImage = this.hash;
		this.nextImage = this.hash + 1;
		$top.preloadImages(this.imagesSrc[this.nextImage]);
		this.image.attr("src", this.imagesSrc[this.hash]).attr("alt", this.altTags[this.hash]);
		this.description.html(this.descriptions[this.hash]);
		if(this.copyrights[this.hash] != "") { this.copyright.html("&copy; " + this.copyrights[this.hash]); }
		this.info.html(this.hash+1 + ' / ' + parseInt(this.totalPictures+1));
	}
};


top.relatedSlideshow = {

	init: function(slideshowId, jsonData) {
		// set some variables
		this.slideshowId = slideshowId;
		this.headlines = [];
		this.imageSrcs = [];
		this.imageWidth = 260;
		this.imageHeight = 308;
		this.imageCounts = [];
		this.links = [];
		this.actualGallery = 1;

		// fill arrays
		this.totalRelSlideshows = jsonData.related.length;
		for(var i=0; i<this.totalRelSlideshows; i++) {
			this.headlines.push(jsonData.related[i].details.headline);
			this.imageSrcs.push(jsonData.related[i].details.previewImage);
			this.imageCounts.push(jsonData.related[i].details.imageCount);
			this.links.push(jsonData.related[i].details.link);
		}

		// removed fallback markup and build up new list
		$top("#ss-rel-carousel").empty();
		$top(".unit.slideshow .ss-img-cnt.rel").css("visibility", "visible");
		$top("#ss-rel-carousel").append('<ul id="ss-rel-list" style="overflow: hidden; position: absolute; width: 3000px; top: 20px; left: 0;"></ul>').css({
			"overflow":"hidden",
			"position":"relative"
		});

		// fill list
		var active = "", imageCount;
		for(var i=0; i<this.totalRelSlideshows; i++) {
			active = i == 1 ? ' class="active"' : "";
			imageCount = parseInt(this.imageCounts[i]) + 1;
			$top("#ss-rel-list").append('<li' + active + ' style="float: left;"><a href="' + this.links[i] + '" rel="nofollow"><img title="' + this.headlines[i] + '" src="' + this.imageSrcs[i] + '" alt="' + this.headlines[i] + '" /></a><p><a href="' + this.links[i] + '">' + this.headlines[i] + '</a> <span>' + imageCount + '</span></p></li>');
		}

        // append nav buttons
		$top("#ss-rel-carousel").append('<div class="ss-rel-nav-prev"></div><div class="ss-rel-nav-next"></div>')

		// bind functions
		$top("#ss-rel-carousel .ss-rel-nav-prev").bind("click", function() {
			top.relatedSlideshow.prev();
		}).bind("mouseenter", function() {
			 $top(this).addClass("hover-prev");
		}).bind("mouseleave", function() {
			 $top(this).removeClass("hover-prev");
		});

		$top("#ss-rel-carousel .ss-rel-nav-next").bind("click", function() {
			top.relatedSlideshow.next();
		}).bind("mouseenter", function() {
			 $top(this).addClass("hover-next");
		}).bind("mouseleave", function() {
			 $top(this).removeClass("hover-next");
		});

	},

	prev: function() {
		if(this.actualGallery > 0) { // if this is not the first gallery
			this.actualGallery--;
			$top("#ss-rel-carousel ul").animate({
				"left": "+=170px"
			});
			$top("#ss-rel-carousel li.active img").animate({
                "margin": "80px 0 0 20px",
				"width": "148px"
			});
			top.relatedSlideshow.changeActiveLi(top.relatedSlideshow.actualGallery);
			$top("#ss-rel-carousel li.active img").animate({
                "margin": "10px 0 0 20px",
				"width": this.imageWidth + "px"
			});
		}
	},

	next: function() {
		if(this.actualGallery < (this.totalRelSlideshows-1)) { // if this is not the last gallery
			this.actualGallery++;
			$top("#ss-rel-carousel ul").animate({
					"left": "-=170px"
			});
			$top("#ss-rel-carousel li.active img").animate({
				"margin": "80px 0 0 20px",
				"width": "148px"
			});
			top.relatedSlideshow.changeActiveLi(top.relatedSlideshow.actualGallery);
			$top("#ss-rel-carousel li.active img").animate({
				"margin": "10px 0 0 20px",
				"width": this.imageWidth + "px"
			});
		}
	},

	changeActiveLi: function(id) {
		$top('.ss-rel-nav-prev').css("display", "block");
		$top('.ss-rel-nav-next').css("display", "block");
		if(id == 0) {
			$top('.ss-rel-nav-prev').css("display", "none");
		}
		if(id == (this.totalRelSlideshows-1)) {
			$top('.ss-rel-nav-next').css("display", "none");
		}
		$top("#ss-rel-carousel li").removeClass("active");
		$top($top("#ss-rel-carousel li")[id]).addClass("active");
	}

}



// ----- UNITs -----


$top(".unit.teaser, .unit.bm, .unit.list li").each(function() {
	// this.hover
	$top(this).bind("mouseover", function() {
		$top(this).addClass("hover");
	});
	$top(this).bind("mouseout", function() {
		$top(this).removeClass("hover");
	});

	// this.click
	$top(this).bind("click", function() {
		var href = $top(this).find("a").attr("href");
		click(href, $top(this).find("a"));
		return false;
	});
	$top(this).find(".cta-forum a").bind("click", function() {
		var href = $top(this).attr("href");
		click(href, $top(this));
		return false;
	});
	$top(this).find(".cta-rate a").bind("click", function() {
		var href = $top(this).attr("href");
		click(href, $top(this));
		return false;
	});

	// click-function
	function click(href, a) {
		if (!a.attr("target")) {
			window.location.href = href;
		} else {
			window.open(href);
		}
		return false;
	}
});



// ----- Login Divs -----
$top(".lb-popup .login").bind("mouseenter", function() {
    $top(".lb-popup .login").css({'opacity': '1'});
	$top(".lb-popup .registration").css({'opacity': '0.2'});
	$top(".lb-popup .fb-login").css({'opacity': '0.2'});
}).bind("mouseleave", function() {
	$top(".lb-popup .registration").css({'opacity': '1'});
	$top(".lb-popup .fb-login").css({'opacity': '1'});
});

$top(".lb-popup .registration").bind("mouseenter", function() {
    $top(".lb-popup .login").css({'opacity': '0.2'});
	$top(".lb-popup .registration").css({'opacity': '1'});
	$top(".lb-popup .fb-login").css({'opacity': '0.2'});
}).bind("mouseleave", function() {
	$top(".lb-popup .login").css({'opacity': '1'});
	$top(".lb-popup .fb-login").css({'opacity': '1'});
});

$top(".lb-popup .fb-login").bind("mouseenter", function() {
    $top(".lb-popup .login").css({'opacity': '0.2'});
	$top(".lb-popup .registration").css({'opacity': '0.2'});
	$top(".lb-popup .fb-login").css({'opacity': '1'});
}).bind("mouseleave", function() {
	$top(".lb-popup .registration").css({'opacity': '1'});
	$top(".lb-popup .login").css({'opacity': '1'});
});



// ----- Accordion -----


if ($top(".accordion").length > 0) {
	$top(".accordion").each(function() {
		var acHead = $top(this).children(".ac-head");
		var acBody = $top(this).children(".ac-body");
		var elBefore = 0;

		if (acHead.length <= 1) return;

		acHead.each(function(current) {
			$top(this).bind("mouseenter", function() {
				if (current == elBefore) return;
				$top(acBody[current]).slideDown();
				$top(acBody[elBefore]).slideUp();
				elBefore = current;
			});
		});
	});
}



// ----- Comments -----


top.comments = {
	handleComments: function(reinit) {
		if ($top("#comments #cmt-write").length > 0) {
			var textarea = $top("#comments #comments-write");
			var initTxt = "Du hast noch <span>2000</span> Zeichen zur Verf&uuml;gung.";
			var hint = $top("#comments #cmt-write-hint-txt");
			hint.html(initTxt);
			hint.show();
			var hintSpan = hint.children("span");
			var maxlength = 2000;
			var focusColor = ($top(".article").length > 0) ? "#000" : "#FFF";
			var button = $top('#cmt-write a.deco span');
			button.css('color', '#AAA');

			// call elastic-plugin
			textarea.elastic(reinit);

			if (textarea.val() != "Kommentar schreiben") {
				textarea.val("")
				hintSpan.text(maxlength - parseInt(textarea.val().length));
				textarea.val("Kommentar schreiben")
				button.css('color', '#FFF');
			}

			textarea.bind("mouseup keyup", function() {
				var field = $top(this);
				var value = field.val();

				hintSpan.text(maxlength - parseInt(value.length));

				if (parseInt(value.length) >= maxlength) {
					field.val(value.substring(0, maxlength));
					hintSpan.text("0");
				}
			}).bind("focus", function() {
				hint.animate({"color": focusColor});
				button.animate({'color': '#FFF'});
			}).bind("blur", function() {
				hint.animate({"color": "#999"});
				if (textarea.val() == "Kommentar schreiben") {
					button.animate({'color': '#AAA'});
				}
			});
		}
	},

	postComment: function(callback) {
		// prevent that ajax isn't active and the button will be still clickable on action
		if(!top.comments.ajaxActive) {
			top.comments.ajaxActive = true; // set ajax var to active
			top.showLoader($top('#cmt-read')); // init loader
			var formUrl = $top("#cmt-write form").attr("action");
			var formData = $top("#cmt-write form").serialize();
			var formId = $top("#cmt-write form").attr('id');
			if ($top('#comments-write').val() == "" || $top('#comments-write').val() == "Kommentar schreiben") {
				return false; // return false, if there is no comment entered
			}
			var button = $top('#cmt-write a');
			button.animate({'color': '#AAA'});

			$top.ajax({ // start ajax
				type: "POST",
				url: formUrl,
				data: formData,
				dataType: "json",
				timeout: 3000,
				error: function(msg){ // error, remove loader, open hint and change button color
					$top('#cmt-load').remove();
					top.hint.openHintLayer('Fehler', 'Es ist ein unbekannter Fehler aufgetreten. Bitte versuchen Sie es zu einem späteren Zeitpunkt nochmal.', 'Okay');
					button.animate({'color': '#FFF'});
				},
				success: function(jsonData){ // success
					if (typeof callback == "function") {  // if there is a callback function
						callback.call(this);
						return;
					}
					if (jsonData.isLoginRequired) { // login is required, open loginlayer
						top.login.handleAuthentication(jsonData, formId, top.comments.getComments)
						top.comments.ajaxActive = false;
					} else { // comment was posted, got json data, show new comments
						top.comments.getComments(jsonData)
					}
					button.animate({'color': '#FFF'});
				}
			});
		}
	},

	getComments: function(jsonData) {
		// show new comments, empty comments div, fill some variables with json data
		$top('#comments-write').val('');
		$top('#comments-write').next('div').html('');
		$top("#cmt-read .cmt-item").remove();
		$top("#cmt-read #cmt-footer").remove();
		var commentsCount = jsonData.commentsData.meta.commentCount;
		var moreCommentsLink = jsonData.commentsData.meta.moreCommentsPage;
		var commentsShown = jsonData.comments.length;
		commentsShown--;
		var actComment = commentsCount;
		var cssClass;

		for(var i=1; i<=commentsShown; i++) { // write and append markup comments 1 - 9
			avatar = top.comments.getAvatar(jsonData.comments[i].avatar.type, jsonData.comments[i].avatar.value);
			actComment--;
			$top("#cmt-read").append('<div class="cmt-item" id="post' + actComment + '">' +
				avatar +
				'<div>' +
					'<p><span><strong>' + jsonData.comments[i].username + '</strong> ' + jsonData.comments[i].time + '</span> <span class="cmt-item-id">#' + actComment + '</span><span class="cmt-squeal"><a title="Petzen" rel="lbpopup" href="' + jsonData.comments[i].sneak.url + '">' + jsonData.comments[i].sneak.linktext + '</a></span></p>' +
					'<p>' + jsonData.comments[i].comment + '</p>' +
				'</div>' +
				'<div class="cmt-item-btm"></div>' +
			'</div>');
		}

		if(moreCommentsLink != "") { // is there a more comments link?
			moreCommentsLink = '<a href="' + moreCommentsLink + '" class="deco"><span>Weitere Kommentare lesen</span></a>';
		} else {
			moreCommentsLink = '';
		}

		// write and append markup for footer (commentscount and more comments link)
		$top("#cmt-read").append('<div id="cmt-footer">' +
			'<span id="cmt-footer-hint">' + commentsCount + ' Kommentare</span>' +
			moreCommentsLink +
		'</div>');

		 // write and append markup for comment 0 (this one, which was written)
		avatar = top.comments.getAvatar(jsonData.comments[0].avatar.type, jsonData.comments[0].avatar.value);
		$top("#cmt-read").prepend('<div class="cmt-item" id="post' + commentsCount + '">' +
			avatar +
			'<div>' +
				'<p><span><strong>' + jsonData.comments[0].username + '</strong> ' + jsonData.comments[0].time + '</span> <span class="cmt-item-id">#' + commentsCount + '</span><span class="cmt-squeal"><a title="Petzen" rel="lbpopup" href="' + jsonData.comments[0].sneak.url + '">' + jsonData.comments[0].sneak.linktext + '</a></span></p>' +
				'<p>' + jsonData.comments[0].comment + '</p>' +
			'</div>' +
			'<div class="cmt-item-btm"></div>' +
		'</div>');
		$top("#post" + commentsCount).hide().slideDown("slow"); // animate my comment, yeehaaw!

		//set ajaxActive back
		top.comments.ajaxActive = false;

		// set textarea back
		top.comments.handleComments("reinit");

		// set button back
		var button = $top('#cmt-write a.deco span');
		button.css('color', '#AAA');

		// bind new "petzen" links with lightbox
		$top("#comments a[rel^='lbpopup']").prettyPhoto({
			padding: 16,
			allowresize: false,
			theme: 'light_square',
			modal: true
		});
	},

	getAvatar: function(type, value) {
		var avatar = "";
		switch(type) {
			case 'url': // facebook avatar
					avatar += '<span class="cmt-avatar" style="background-image: url(' + value + ')"></span>'
			break;
			case 'styleClass': // top.de avatar
					avatar += '<span class="cmt-avatar ' + value + '"></span>'
			break;
			default: // fallback: top.de avatar
					avatar += '<span class="cmt-avatar ' + value + '"></span>'
			break;
		}
		return avatar;
	}
};
top.comments.handleComments();
top.comments.ajaxActive = false; // init



// ----- Opinions-/Meinungen-Link in Article -----


$top("#opinions").bind("click", function() {
	window.location.href='#comments';
	$top('#comments-write').focus();
	return false;
});



// ----- Starprofile -----


if ($top(".starprofile").length > 0) {
	// Initialize
	top.starProfile = new Object();
	top.starProfile.form = $top("#updateStarProfile");
	top.starProfile.img = $top("#starprofile-img");
	top.starProfile.imgDefault = top.starProfile.img.attr("src");
	top.starProfile.fd = $top(".starprofile .fandisser");
	top.starProfile.name = $top(".starprofile #sp-meta h1").html();
	top.starProfile.anchorFan = $top(".fd-cta-fan a");
	top.starProfile.anchorDisser = $top(".fd-cta-disser a");

	// Preload images
	if (top.starProfileImgArray) {
		$top.preloadImages(top.starProfileImgArray["imgFan"]);
		$top.preloadImages(top.starProfileImgArray["imgDisser"]);
	}

	/* ----- STEP 1 ----- */
	// Fan-events
	top.starProfile.anchorFan.bind("mouseover", function () {
		top.starProfile.updateImg(top.starProfileImgArray["imgFan"]);
	}).bind("mouseout", function () {
		top.starProfile.updateImg(top.starProfile.imgDefault);
	}).bind("click", function () {
		// CAUTION: this bind is getting bound after animate also !!!

		// set state
		top.starProfile.form.children("#state").val("fan");

		// Call backend-service
		top.starProfile.update();

		this.blur();
		return false;
	});

	// Disser-events
	top.starProfile.anchorDisser.bind("mouseover", function () {
		top.starProfile.updateImg(top.starProfileImgArray["imgDisser"]);
	}).bind("mouseout", function () {
		top.starProfile.updateImg(top.starProfile.imgDefault);
	}).bind("click", function () {
		// CAUTION: this bind is getting bound after animate also !!!

		// set state
		top.starProfile.form.children("#state").val("disser");

		// Call backend-service
		top.starProfile.update();

		this.blur();
		return false;
	});

	/* ----- STEP 2 ----- */
	// Update backend
	top.starProfile.update = function(callback) {
		// Debug
//		top.starProfile.callbackSuccess();
//		return;

		// Start loading-animation
		top.showLoader(top.starProfile.fd);

		var formId = top.starProfile.form.attr("id");
		var formData = top.starProfile.form.serialize();
		var formUrl = top.starProfile.form.attr("action");
		$top.ajax({
			type: "POST",
			url: formUrl,
			data: formData,
			dataType: "json",
			error: function(jsonData){
				var msg = (jsonData.validation) ? " (" + jsonData.validation.msg + ")" : "";
				top.hint.openHintLayer('Fehler', 'Es ist ein Fehler aufgetreten' + msg + '. Bitte versuchen Sie es zu einem sp&auml;teren Zeitpunkt nochmal.', 'Okay');
			},
			success: function(jsonData){
				if (typeof callback == "function") {
					callback.call(this);
					return;
				}
				top.login.handleAuthentication(jsonData, formId, top.starProfile.callbackSuccess);
				var status = jsonData.status;
				switch(status) {
					case "failed":
						var msg = (jsonData.validation) ? " (" + jsonData.validation.msg + ")" : "";
						top.hint.openHintLayer('Fehler', 'Es ist ein Fehler aufgetreten' + msg + '. Bitte versuchen Sie es zu einem sp&auml;teren Zeitpunkt nochmal.', 'Okay');
					break;
				}
			}
		});
	}

	/* ----- STEP 3 ----- */
	// Callback-function
	top.starProfile.callbackSuccess = function() {
		var state = top.starProfile.form.children("#state").val();
		if (state == "fan") {
			// Count up main-fan-view
			var fan = $top(".fd-info-fan span");
			var txt = top.starProfile.getTxtValue(fan);
			var txt2 = txt; // save the inital content
			txt = top.starProfile.count(txt, "up", fan);
			fan.html(txt);
			// Count up meta-fan-view
			var metaFan = $top("#sp-meta .fans .sp-m-info");
			var metaTxt = top.starProfile.getTxtValue(metaFan);
			metaTxt = top.starProfile.count(metaTxt, "up");
			metaFan.html(metaTxt);

			// Count down disser only if user hasn't voted yet
			if (top.starProfile.fd.hasClass("fd-df") || top.starProfile.fd.hasClass("fd-dd") ||
				top.starProfile.fd.hasClass("fd-ff") || top.starProfile.fd.hasClass("fd-fd") ||
				top.starProfile.fd.hasClass("fd-fq") || top.starProfile.fd.hasClass("fd-dq")) {
				// Count down main-disser-view
				var disserDown = $top(".fd-info-disser span");
				var txtDown = top.starProfile.getTxtValue(disserDown);
				txtDown = top.starProfile.count(txtDown, "down");
				disserDown.html(txtDown);
				// Count down meta-disser-view
				var metaDisserDown = $top("#sp-meta .disser .sp-m-info");
				var metaTxtDown = top.starProfile.getTxtValue(metaDisserDown);
				metaTxtDown = top.starProfile.count(metaTxtDown, "down");
				metaDisserDown.html(metaTxtDown);
			}

			// Change class
			var fanTxt = top.starProfile.getTxtValue($top(".fd-info-fan span"));
			var disserTxt = top.starProfile.getTxtValue($top(".fd-info-disser span"));
			var more = top.starProfile.getFDState(fanTxt.replace(".", ""), disserTxt.replace(".", ""));
			top.starProfile.updateClass("f", more);

			// Update text
			top.starProfile.updateText("Fan");

			// Update link
			top.starProfile.updateLink(top.starProfile.anchorFan, top.starProfile.anchorDisser);

			// Update img
			top.starProfile.updateImg(top.starProfileImgArray["imgFan"], true);

			// Unbind link
			top.starProfile.anchorFan.unbind("click");
			top.starProfile.anchorDisser.unbind("click");
		} else if (state == "disser") {
			// Count up main-disser-view
			var disser = $top(".fd-info-disser span");
			var txt = top.starProfile.getTxtValue(disser);
			var txt2 = txt; // save the inital content
			txt = top.starProfile.count(txt, "up", disser);
			disser.html(txt);
			// Count up meta-disser-view
			var metaDisser = $top("#sp-meta .disser .sp-m-info");
			var metaTxt = top.starProfile.getTxtValue(metaDisser);
			metaTxt = top.starProfile.count(metaTxt, "up");
			metaDisser.html(metaTxt);

			// Count down fan only if user hasn't voted yet
			if (top.starProfile.fd.hasClass("fd-df") || top.starProfile.fd.hasClass("fd-dd") ||
				top.starProfile.fd.hasClass("fd-ff") || top.starProfile.fd.hasClass("fd-fd") ||
				top.starProfile.fd.hasClass("fd-fq") || top.starProfile.fd.hasClass("fd-dq")) {
				// Count down main-fan-view
				var fanDown = $top(".fd-info-fan span");
				var txtDown = top.starProfile.getTxtValue(fanDown);
				txtDown = top.starProfile.count(txtDown, "down");
				fanDown.html(txtDown);
				// Count down meta-fan-view
				var metaFanDown = $top("#sp-meta .fans .sp-m-info");
				var metaTxtDown = top.starProfile.getTxtValue(metaFanDown);
				metaTxtDown = top.starProfile.count(metaTxtDown, "down");
				metaFanDown.html(metaTxtDown);
			}

			// Change class
			var fanTxt = top.starProfile.getTxtValue($top(".fd-info-fan span"));
			var disserTxt = top.starProfile.getTxtValue($top(".fd-info-disser span"));
			var more = top.starProfile.getFDState(fanTxt.replace(".", ""), disserTxt.replace(".", ""));
			top.starProfile.updateClass("d", more);

			// Update text
			top.starProfile.updateText("Feind");

			// Update link
			top.starProfile.updateLink(top.starProfile.anchorDisser, top.starProfile.anchorFan);

			// Update img
			top.starProfile.updateImg(top.starProfileImgArray["imgDisser"], true);

			// Unbind link
			top.starProfile.anchorDisser.unbind("click");
			top.starProfile.anchorFan.unbind("click");
		}
	}

	// Get text/value
	top.starProfile.getTxtValue = function(obj) {
		return (obj.length == 1) ? obj.text() : $top(obj[0]).text();
	}

	// Get Fan-Disser-state
	top.starProfile.getFDState = function(fanVal,disserVal) {
		fanVal = parseInt(fanVal);
		disserVal = parseInt(disserVal);
		var ret = "";
		if (fanVal > disserVal) {
			ret = "f";
		} else if (fanVal < disserVal) {
			ret = "d";
		} else if (fanVal == disserVal) {
			ret = "q";
		}
		return ret;
	}

	// Count up fan or disser
	top.starProfile.count = function(txt, count, animate) {
		txt = txt.replace(".", "");
		txt = parseInt(txt);
		var txtDef = txt;
		if (count == "down") {
			txt--;
			if (txt < 0) return; // can't have an minus-value
		} else {
			txt++;
		}
		txt = compare(txtDef, txt);
		return txt;

		function compare(txtDef, txt) {
			var tmpTxt = "", tmpTxtDef = "", diff = 0, txtNew = "";
			txtDef = txtDef.toString();
			txt = txt.toString();
			for (var i = 0; i < txt.length; i++) {
				tmpTxtDef = txtDef.substring(i, i + 1);
				tmpTxt = txt.substring(i, i + 1);
				if (tmpTxt != tmpTxtDef) {
					diff++;
				}
			}
			txt = divider(txt);

			if (animate) {
				txtNew = txt.substring(0, txt.length - diff) + '<span class="fd-info-count ani">' + txt.substring(txt.length - diff, txt.length) + '</span>';
				window.setTimeout(function() {
					$top(".fd-info-count.ani").animate({"color": "#FFF"}, "slow", function() {
						// Bind links again
						top.starProfile.anchorFan.bind("click", function () {
							// set state
							top.starProfile.form.children("#state").val("fan");

							// Call backend-service
							top.starProfile.update();

							this.blur();
							return false;
						});
						top.starProfile.anchorDisser.bind("click", function () {
							// set state
							top.starProfile.form.children("#state").val("disser");

							// Call backend-service
							top.starProfile.update();

							this.blur();
							return false;
						});

						// remove the fd-info-count-span again
						animate.html(txt);
					});
				}, 1000);
			} else {
				txtNew = txt.substring(0, txt.length - diff) + '' + txt.substring(txt.length - diff, txt.length);
			}

			return txtNew;
		}

		// Insert tausendertrennzeichen
		function divider(num) {
			num = '' + num;
			if (num.length > 3) {
				var mod = num.length % 3;
				var output = (mod > 0 ? (num.substring(0,mod)) : '');
				for (var i = 0; i < Math.floor(num.length / 3); i++) {
					if ((mod == 0) && (i == 0)) {
						output += num.substring(mod + 3 * i, mod + 3 * i + 3);
					} else {
						output += '.' + num.substring(mod + 3 * i, mod + 3 * i + 3);
					}
				}
				return (output);
			} else {
				return num;
			}
		}
	}

	// Update classes
	top.starProfile.updateClass = function(iam, more) {
		// this removeClass-action here is not very nice, but removeClass doesn't work with RegExp
		top.starProfile.fd.removeClass("fd-ff").removeClass("fd-fd").removeClass("fd-df").removeClass("fd-dd").removeClass("fd-fq").removeClass("fd-dq").removeClass("fd-nq").removeClass("fd-nf").removeClass("fd-nd");
		var cls = "fd-" + iam + "" + more;
		top.starProfile.fd.addClass(cls);
	}

	// Update text
	top.starProfile.updateText = function(state) {
		var txt = "Du bist ein";
		var name = top.starProfile.name;

		txt = txt + " " + name + " " + state;

		top.starProfile.fd.find("h2").html(txt);
	}

	// Update link
	top.starProfile.updateLink = function(objAct, obj) {
		// get inactive object
		if (obj) {
			var span = obj.prev(".fd-cta-act");
			span.addClass("off");
			obj.removeClass("off");
		}

		// get active object
		if (objAct) {
			var spanAct = objAct.prev(".fd-cta-act");
			objAct.addClass("off");
			spanAct.removeClass("off");
		}
	}

	// Update image
	top.starProfile.updateImg = function(img, unbind) {
		top.starProfile.img.attr("src", img);
		if (unbind) {
			top.starProfile.imgDefault = img;
		}
	}
}



// openHintLayer
top.hint = {
	openHintLayer: function(headline, text, linktext) {

		// get actual location to position the hint
		var scrollTop = $top(window).scrollTop();
		var positionTop = scrollTop + 200;
		var style = '';
		style = scrollTop > 0 ? ' style="top: ' + positionTop + 'px;"' : '';

		// build markup
		$top('#pagecontainer').append('<div id="errormsg"' + style + '>' +
			'<div>' +
			  '<h3>' + headline + '</h3>' +
			  '<p>' + text + '</p>' +
			  '<a href="#">' + linktext + '</a>' +
			'</div>' +
		  '</div>');
		$top('#errormsg').fadeIn('fast');

		// workaround for ie6
		if($top.browser.msie && $top.browser.version < 7) {
			$top('select').css('visibility', 'hidden');
		}

		// bind functions
		$top('#errormsg a').bind('click', function() {
			top.hint.closeHintLayer();
			if($top.browser.msie && $top.browser.version < 7) {
				$top('select').css('visibility', 'visible');
			}
		});
	},

	closeHintLayer: function() {
		// remove
		$top('#errormsg').remove();
	}
}



// My Starlist
top.mystarList = {
	init: function() {
		var j;

		this.shownElement = 0;
		this.elCount = $top('.my-starlist li').length;
		this.list = $top('.my-starlist ul');
		this.list.css('width', this.elCount*608 + 'px');
		this.pos = 0;
		this.aniEl = $top('.my-starlist #mystars-pos');
		this.navPrevEl = $top('.my-starlist .nav .nav-prev');
		this.navNextEl = $top('.my-starlist .nav .nav-next');
		this.navBubbles = $top('.my-starlist .nav-bubble');

		this.navPrevEl.attr('id', 'my-starlist-prev');
		this.navNextEl.attr('id', 'my-starlist-next');

		this.navPrevEl.bind('click', function() {
			top.mystarList.navPrev();
		}).attr('href', '#mystarList');

		this.navNextEl.bind('click', function() {
			top.mystarList.navNext();
		}).attr('href', '#mystarList');

		this.navBubbles.empty();
		for(var i=0; i<this.elCount; i++) {
			j = i+1;
			this.navBubbles.append('<div id="bubbles"></div>');
			if(i==0) {
				$top('#bubbles').append('<span>' + j + ' </span>');
			} else {
				$top('#bubbles').append('<a href="#mystarList" onclick="top.mystarList.directJump(' + i + ');">' + j + ' </a>')
			}
			$top('#bubbles').css({
				'width': this.elCount*20 + 'px',
				'margin': '0px auto'
			});
		}
	},

	navNext: function() {
		if(this.shownElement < (this.elCount-1)) {
			this.pos -= 608;
			parseInt(this.pos);
			this.aniEl.animate({
				"left": this.pos + "px"
			});
			this.shownElement++;
			this.navPrevEl.removeClass('inactive');
			top.mystarList.updateBubbles(this.shownElement);
			if(this.shownElement == (this.elCount-1)) {
				this.navNextEl.addClass('inactive');
			}
		}
	},

	navPrev: function() {
		if(this.shownElement > 0) {
			this.pos += 608;
			parseInt(this.pos);
			this.aniEl.animate({
				"left": this.pos + "px"
			});
			this.shownElement--;
			this.navNextEl.removeClass('inactive');
			top.mystarList.updateBubbles(this.shownElement);
			if(this.shownElement == 0) {
				this.navPrevEl.addClass('inactive');
			}
		}
	},

	updateBubbles: function(activeBubble) {
		this.navBubbles.empty();
		for(var i=0; i<this.elCount; i++) {
			j = i+1;
			this.navBubbles.append('<div id="bubbles"></div>');
			if(i==activeBubble) {
				$top('#bubbles').append('<span id="bubble-' + i + '">' + j + ' </span>');
			} else {
				$top('#bubbles').append('<a href="#mystarList" onclick="top.mystarList.directJump(' + i + ');">' + j + ' </a>')
			}
			$top('#bubbles').css({
				'width': this.elCount*20 + 'px',
				'margin': '0px auto'
			});
		}
	},

	directJump: function(elToShow) {
		this.shownElement = elToShow;
		this.pos = elToShow * 608;
		this.pos = this.pos > 0 ? -this.pos : this.pos;
		this.aniEl.animate({
			"left": this.pos + "px"
		});
		top.mystarList.updateBubbles(elToShow)
		if(this.shownElement == 0) {
			this.navPrevEl.addClass('inactive');
			this.navNextEl.removeClass('inactive');
		} else if(this.shownElement == (this.elCount-1)) {
			this.navPrevEl.removeClass('inactive')
			this.navNextEl.addClass('inactive');
		} else {
			this.navPrevEl.removeClass('inactive')
			this.navNextEl.removeClass('inactive');
		}
	}
}

if ($top(".my-starlist").length > 0) {
	top.mystarList.init();

	/*
	$top(".my-starlist td.fan, .my-starlist td.disser, .my-starlist td.fan-active, .my-starlist td.disser-active").mouseover(function(){
		var cssClass = $top(this).attr('class');
		cssClass = cssClass + '-hover';
		$top(this).attr('class', cssClass);
		//$top(this).addClass("hover");
	}).mouseout(function(){
		var cssClass = $top(this).attr('class');
		var pos = cssClass.indexOf('-hover');
		cssClass = cssClass.substr(0, pos);
		$top(this).attr('class', cssClass);
		//$top(this).removeClass("hover");
	});
	*/
}



// ----- Slideshow-Switch -----


if ($top(".ss-switch").length > 0) {
	// Preload images
	for (var i = 0; i < top.ssSwitchBigImg.length; i++) {
		$top.preloadImages(top.ssSwitchBigImg[i]);
	}
	// Iterate through each ss-switcher
	$top(".ss-switch").each(function() {
		var objMain = $top(this);
		var objMainA = objMain.find("span a");
		var objMainImg = objMain.find("span img");
		var href = "";

		$top(this).find("ul a").each(function(current) {
			$top(this).bind("mouseenter", function() {
				objMainA.attr("href", $top(this).attr("href"));
				objMainImg.attr("src", top.ssSwitchBigImg[current]);
				setStyles($top(this));
			});
		});

		function setStyles(act) {
			objMain.find("li").removeClass("focus");
			act.parent("li").addClass("focus");
		}
	});
}



// ----- TOPDE-LOGIN -----


top.login = {
	openLogin: function(url) {
		$top.prettyPhoto.open(url);
	},

	doLogin: function(formUrl, cdReloader) {
		var formData = $top("#loginform").serialize();
		top.showLoader($top('#pagecontainer')); // init loader
		$top.ajax({
			type: "POST",
			url: formUrl,
			data: formData,
			dataType: "json",
			error: function(msg){
				$top('#cmt-load').remove();
				top.hint.openHintLayer('Fehler', 'Es ist ein unbekannter Fehler aufgetreten. Bitte versuchen Sie es zu einem späteren Zeitpunkt nochmal.', 'Okay');
			},
			success: function(jsonData){
				var status = jsonData.status;
				$top('#loginform input').removeClass('error');
				$top('#loginform .hint').empty();
				switch(status) {
					case "success":
						$top('body').append('<iframe src="' + cdReloader + '" frameborder="0" style="left: -5000px; height: 1px; position: absolute; top: -5000px; width: 1px;">dont support frames</iframe>');
					break;
					case "failed":
						$top('#loginform #lgnHint').html('<span>Achtung:</span> ' + jsonData.validation.msg + '');
						$top('#loginform input').addClass('error');
					break;
					case "blocked":
						$top('#loginform #lgnHint').html('<span>Achtung:</span> ' + jsonData.validation.msg + '');
						$top('#loginform input').addClass('error');
					break;
					default:
						$top('#loginform #lgnHint').html('<span>Achtung:</span> ' + jsonData.validation.msg + '');
						$top('#loginform input').addClass('error');
					break;
				}
			}
		});
	},

	requestPassword: function(formUrl) {
		var formData = $top("#rqpwdform").serialize();
		top.showLoader($top('#pagecontainer')); // init loader
		$top.ajax({
			type: "POST",
			url: formUrl,
			data: formData,
			dataType: "json",
			error: function(msg){
				$top('#cmt-load').remove();
				top.hint.openHintLayer('Fehler', 'Es ist ein unbekannter Fehler aufgetreten. Bitte versuchen Sie es zu einem späteren Zeitpunkt nochmal.', 'Okay');
			},
			success: function(jsonData){
				var status = jsonData.status;
				$top('#rqpwdform div.hint').empty();
				switch(status) {
					case "success":
						$top('#rqpwdform input').attr('disabled','disabled');
						$top('#rqpwdform div.hint').html('<p><span>Achtung: </span>' + jsonData.validation.msg + '</p>')
						$top('#rqpwdform a').bind('click', function() {
							window.location.href = jsonData.additional.redirectUrl;
						}).attr('onclick','');
					break;
					case "failed":
						$top('#rqpwdform div.hint').html('<p><span>Achtung: </span>' + jsonData.validation.msg + '</p>')
					break;
					default:
						$top('#rqpwdform div.hint').html('<p><span>Achtung: </span>' + jsonData.validation.msg + '</p>')
					break;
				}
			}
		});
	},

	handleAuthentication: function(jsonData, formId, callback) {
		if (jsonData.isLoginRequired) {

			var loginUrl;
			var inIframe = false;
			if (typeof top.loginUrl == "undefined") {
				loginUrl = parent.top.loginUrl;
			} else {
				if (typeof top.loginUrl == "undefined") {
					throw "Login-URL not found";
				} else {
					loginUrl = top.loginUrl;
					inIframe = true;
				}
			}

			$top('#cmt-load').remove();
			var urlPart1 = loginUrl.substr(0,loginUrl.indexOf("?")+1);
			var urlPart2 = "formId=" + formId + '&';
			var urlPart3 = loginUrl.substr(loginUrl.indexOf("?")+1, loginUrl.length);
			var url = urlPart1 + urlPart2 + urlPart3;
			if (inIframe) {
				//start login-process in created IFrame
				top.login.openLogin(url);
			} else {
				//IFrame already exists, switch location to login-screen
				location.href = url;
			}
		} else {
			if (typeof callback == "function") {
				callback.call(this, jsonData);
			}
		}
	}
}

top.register = {

	registerUser: function(formUrl, cdReloader) {
		var formData = $top("#registerform").serialize();
		top.showLoader($top('#pagecontainer')); // init loader
		$top.ajax({
			type: "POST",
			url: formUrl,
			data: formData,
			dataType: "json",
			error: function(msg){
				$top('#cmt-load').remove();
				top.hint.openHintLayer('Fehler', 'Es ist ein unbekannter Fehler aufgetreten. Bitte versuchen Sie es zu einem späteren Zeitpunkt nochmal.', 'Okay');
			},
			success: function(jsonData){
				var status = jsonData.status;
				$top('#registerform .hint').empty();
				$top('#regNickname').removeClass('error');
				$top('#regPassword').removeClass('error');
				$top('#regPassword2').removeClass('error');
				switch(status) {
					case "success":
						window.location.href = jsonData.additional.redirectUrl;
					break;
					case "failed":
						if(jsonData.validation.msg) {
							$top('#registerform #regAgbHint').html('<span>Achtung:</span> ' + jsonData.validation.msg + '</p>');
						} else {
							if(jsonData.validation.regNickname) { $top('#registerform #regNicknameHint').html('<span>Achtung:</span> ' + jsonData.validation.regNickname + ''); $top('#regNickname').addClass('error'); }
							if(jsonData.validation.regPassword) { $top('#registerform #regPasswordHint').html('<span>Achtung:</span> ' + jsonData.validation.regPassword + ''); $top('#regPassword, #regPassword2').addClass('error'); }
							if(jsonData.validation.regAgb) { $top('#registerform #regAgbHint').html('<span>Achtung:</span> ' + jsonData.validation.regAgb + ''); }
						}
					break;
					case "error":
						$top('#registerform #regAgbHint').html('<span>Achtung:</span> ' + jsonData.validation.msg + '</p>');
					break;
					default:
						$top('#registerform #regAgbHint').html('<span>Achtung:</span> ' + jsonData.validation.msg + '</p>');
					break;
				}
			}
		});
	},

	insertEmail: function(formUrl, cdReloader) {
		var formData = $top("#registerform").serialize();
		top.showLoader($top('#pagecontainer')); // init loader
		$top.ajax({
			type: "POST",
			url: formUrl,
			data: formData,
			dataType: "json",
			error: function(msg){
				$top('#cmt-load').remove();
				top.hint.openHintLayer('Fehler', 'Es ist ein unbekannter Fehler aufgetreten. Bitte versuchen Sie es zu einem späteren Zeitpunkt nochmal.', 'Okay');
			},
			success: function(jsonData){
				var status = jsonData.status;
				$top('#registerform .hint').empty();
				$top('#regEmail').removeClass('error');
				switch(status) {
					case "success":
						window.location.href = jsonData.additional.redirectUrl;
					break;
					case "failed":
						if(jsonData.validation.msg) {
							$top('#registerform #regEmailHint').html('<span>Achtung:</span> ' + jsonData.validation.msg + '</p>');
						} else {
							if(jsonData.validation.regEmail) { $top('#registerform #regEmailHint').html('<span>Achtung:</span> ' + jsonData.validation.regEmail + ''); $top('#regEmail').addClass('error'); }
						}
					break;
					case "error":
						$top('#registerform #regEmailHint').html('<span>Achtung:</span> ' + jsonData.validation.msg + '</p>');
					break;
					default:
						$top('#registerform #regEmailHint').html('<span>Achtung:</span> ' + jsonData.validation.msg + '</p>');
					break;
				}
			}
		});
	},

	authenticate: function(formUrl, cdReloader) {
		var formData = $top("#registerform").serialize();
		top.showLoader($top('#pagecontainer')); // init loader
		$top.ajax({
			type: "POST",
			url: formUrl,
			data: formData,
			dataType: "json",
			error: function(msg){
				$top('#cmt-load').remove();
				top.hint.openHintLayer('Fehler', 'Es ist ein unbekannter Fehler aufgetreten. Bitte versuchen Sie es zu einem späteren Zeitpunkt nochmal.', 'Okay');
			},
			success: function(jsonData){
				var status = jsonData.status;
				$top('#registerform #regAuthcodeHint').empty();
				$top('#registerform input').removeClass('error');
				switch(status) {
					case "success":
						window.location.href = jsonData.additional.redirectUrl;
					break;
					case "failed":
						$top('#registerform #regAuthcodeHint').html('<span>Achtung:</span> ' + jsonData.validation.regAuthcode + '');
						$top('#registerform input').addClass('error');
					break;
					case "error":
						$top('#registerform #regAuthcodeHint').html('<span>Achtung:</span> ' + jsonData.validation.regAuthcode + '');
						$top('#registerform input').addClass('error');
					break;
					default:
						$top('#registerform #regAuthcodeHint').html('<span>Achtung:</span> ' + jsonData.validation.regAuthcode + '');
						$top('#registerform input').addClass('error');
					break;
				}
			}
		});
	}
}

top.cdReload = function(cdReloader) {
	$top('body').append('<iframe src="' + cdReloader + '" frameborder="0" style="left: -5000px; height: 1px; position: absolute; top: -5000px; width: 1px;">dont support frames</iframe>');
}

top.account = {
	deleteAccount: function(link) {

		var scrollTop = $top(window).scrollTop();
		var positionTop = scrollTop + 200;
		var style = '';
		style = scrollTop > 0 ? ' style="top: ' + positionTop + 'px;"' : '';

		var headline = 'Account l&ouml;schen';
		var text = 'M&ouml;chtest du deinen Account wirklich unwiderruflich l&ouml;schen?';
		var okayLink = 'Okay.';
		var cancelLink = 'Nein.';

		$top('#pagecontainer').append('<div id="errormsg"' + style + '>' +
			'<div>' +
			  '<h3>' + headline + '</h3>' +
			  '<p>' + text + '</p>' +
			  '<a id="okaylink" style="left: 24px;" href="#">' + okayLink + '</a>' +
			  '<a id="cancellink" style="right: 24px;" href="#">' + cancelLink + '</a>' +
			'</div>' +
		  '</div>');
		$top('#errormsg').fadeIn('fast');
		$top('#errormsg a#okaylink').bind('click', function() {
			if (userstate==2) {
				if(usefbconnect) {
					FB.Connect.logoutAndRedirect(link);
					var timeout = window.setTimeout("document.location.href=logoutUrl;", 7000);
				} else {
					document.location.href=link;
				}
			} else if (userstate==3) {
				document.location.href=link;
			}
		});
		$top('#errormsg a#cancellink').bind('click', function() {
			top.hint.closeHintLayer();
		});
	}
}

if($top('#acc-delete').length > 0) {
	var link = $top('#acc-delete');
	link.bind('click', function() {
		top.account.deleteAccount(link.attr('href'));
		return false;
	});
}

// Newsticker
top.newsticker = {
	init: function(id) {
		$top(id).jCarouselLite({
			vertical: true,
			hoverPause:true,
			visible: 3,
			auto:4000,
			speed:500
		});
	}
}

// AdRefresh
/*
top.adRefresh = {
	init: function() {
		top.adRefeshInitialized = true;
		// iframe top: 778 x 90
		// iframe sky: 320 x 600
		this.topHolder = $top('.adv-top');
		this.skyLeftHolder = $top('#adv-sky-1');
		this.skyRightHolder = $top('#adv-sky-2');
	},

	refresh: function(advTop, advLeft, advRight) {
		if(!top.adRefeshInitialized) {
			top.adRefresh.init();
			top.adRefresh.refresh(true, false, false);
		} else {
			if(advTop) {
				this.topHolder.empty();
				this.topHolder.append('<iframe id="advtopframe" frameborder="0" scrolling="no">dont support frames</iframe>');
				this.topHolderFrame = $top('#advtopframe');
				this.topHolderFrame.attr('src', 'adrefresh-frame.html'); //todo
				this.topHolderFrame.attr('height', '90');
				this.topHolderFrame.attr('width', '778');
				this.topHolderFrame.attr('marginheight', '0');
				this.topHolderFrame.attr('marginwidth', '0');
				this.topHolderFrame.attr('style', 'margin: 0;');
			}
			if(advLeft) {
				this.skyLeftHolder.empty();
				this.skyLeftHolder.append('<iframe id="advleftframe" frameborder="0" scrolling="no">dont support frames</iframe>');
				this.skyLeftHolderFrame = $top('#advleftframe');
				this.skyLeftHolderFrame.attr('src', 'adrefresh-frame.html'); //todo
				this.skyLeftHolderFrame.attr('height', '600');
				this.skyLeftHolderFrame.attr('width', '320');
				this.skyLeftHolderFrame.attr('marginheight', '0');
				this.skyLeftHolderFrame.attr('marginwidth', '0');
				this.skyLeftHolderFrame.attr('style', 'margin: 0;');
			}
			if(advRight) {
				this.skyRightHolder.empty();
				this.skyRightHolder.append('<iframe id="advrightframe" frameborder="0" scrolling="no">dont support frames</iframe>');
				this.skyRightHolderFrame = $top('#advrightframe');
				this.skyRightHolderFrame.attr('src', 'adrefresh-frame.html'); //todo
				this.skyRightHolderFrame.attr('height', '600');
				this.skyRightHolderFrame.attr('width', '320');
				this.skyRightHolderFrame.attr('marginheight', '0');
				this.skyRightHolderFrame.attr('marginwidth', '0');
				this.skyRightHolderFrame.attr('style', 'margin: 0;');
			}
		}
	}
}
*/



// ----- TOPDE-LOGOUT -----


var logoutUrl = window.location.href;
if (logoutUrl.indexOf('#')>-1) {
	if (logoutUrl.indexOf('?')>-1) {
		logoutUrl = logoutUrl.substr(0, logoutUrl.indexOf('#')) + logoutUrl.substr(logoutUrl.indexOf('?'));
	} else {
		logoutUrl = logoutUrl.substr(0, logoutUrl.indexOf('#'));
	}
}

var originUrl = logoutUrl;
if (logoutUrl.indexOf('auth_logout')<0) {
	if (logoutUrl.indexOf('?')>-1) {
		logoutUrl = logoutUrl + '&';
	} else {
		logoutUrl = logoutUrl + '?';
	}
	if (originUrl.indexOf('changeaccount/') >= 0) {
		originUrl= originUrl.substr(0, originUrl.indexOf('changeaccount/'));
	}
	if (originUrl.indexOf('account/') >= 0) {
		originUrl= originUrl.substr(0, originUrl.indexOf('account/'));
	}
	logoutUrl = logoutUrl + 'auth_logout=true&originUrl=' + originUrl;
}

function logoutUser() {
	if($top.browser.msie) {
		if (userstate==2) {
			if(usefbconnect) {
				FB.Connect.logoutAndRedirect(logoutUrl);
				var timeout = window.setTimeout("document.location.href=logoutUrl;", 7000);
			} else {
				top.hint.openHintLayer('Logout', 'Du wirst jetzt ausgeloggt.', 'Schliessen');
				window.location.href = logoutUrl + '#success';
				var timeout = window.setTimeout("window.location.href = logoutUrl + '#success'; window.location.reload();", 1500);
			}
		} else if (userstate==3) {
			top.hint.openHintLayer('Logout', 'Du wirst jetzt ausgeloggt.', 'Schliessen');
			window.location.href = logoutUrl + '#success';
			var timeout = window.setTimeout("window.location.href = logoutUrl + '#success'; window.location.reload();", 1500);
		} else {
			top.hint.openHintLayer('Logout', 'Du wirst jetzt ausgeloggt.', 'Schliessen');
			window.location.href = logoutUrl + '#success';
			var timeout = window.setTimeout("window.location.href = logoutUrl + '#success'; window.location.reload();", 1500);
		}
	} else {
		if (userstate==2) {
			if(usefbconnect) {
				FB.Connect.logoutAndRedirect(logoutUrl);
				var timeout = window.setTimeout("document.location.href=logoutUrl;", 7000);
			} else {
				top.hint.openHintLayer('Logout', 'Du wirst jetzt ausgeloggt.', 'Schliessen');
				window.location.href = logoutUrl + '#success';
			}
		} else if (userstate==3) {
			top.hint.openHintLayer('Logout', 'Du wirst jetzt ausgeloggt.', 'Schliessen');
			window.location.href = logoutUrl + '#success';
		} else {
			top.hint.openHintLayer('Logout', 'Du wirst jetzt ausgeloggt.', 'Schliessen');
			window.location.href = logoutUrl + '#success';
		}
	}
}



// ----- Footer -----


$top(".agb-popup").bind("click", function() {
    window.open($top(".agb-popup").attr("href"), 'popup', 'height=400,resizable=yes,scrollbars=yes,width=617').focus();
	return false;
});



// ----- Voting -----


if ($top(".voting").length > 0 || $top("#voting").length > 0) {
	// Initialize
	top.voting = new Object();
	top.voting.form = parent.$top("#updateVoting");
	top.voting.pageDiv = $top("#pagecontainer");
	top.voting.mainDiv = $top(".voting");
	top.voting.srcMainDiv = parent.$top("#voting");
	top.voting.hrefStep2 = "";
	top.voting.hrefStep3 = "";

	// Bind eventlistener
	$top(".vote-top-a a").bind("click", function() {
		top.voting.hrefStep2 = $top(this).attr("href");
		top.voting.hrefStep3 = top.voting.form.children("#vote-confirm-url-a").val();
		top.voting.form.children("#vote-opt").val("a");
		top.voting.update();
		return false;
	});
	$top(".vote-top-b a").bind("click", function() {
		top.voting.hrefStep2 = $top(this).attr("href");
		top.voting.hrefStep3 = top.voting.form.children("#vote-confirm-url-b").val();
		top.voting.form.children("#vote-opt").val("b");
		top.voting.update();
		return false;
	});
	// Step2-event
	$top(".voting.step2").bind("click", function() {
		top.login.handleAuthentication({"isLoginRequired":true}, "updateVoting");
		return false;
	}).bind("mouseover", function() {
		$top(this).addClass("vt-hover");
	}).bind("mouseout", function() {
		$top(this).removeClass("vt-hover");
	}).css("cursor", "pointer");
	// Step3-event
	if ($top(".voting.step3").length > 0) {
		$top(".voting.step3 .deco").bind("click", function() {
			window.parent.$top.prettyPhoto.close();
			return false;
		})
		$top(window).unload(function() {
			window.parent.location.hash = "success"; // empty hashes will scroll to the top of the page
		});
	}

	// Ajax-call
	top.voting.update = function(callback) {
		// Start loading-animation
		top.showLoader(top.voting.pageDiv);

		// Start ajax
		var voteOpt = top.voting.form.children("#vote-opt").val();
		var formId = top.voting.form.attr("id");
		var formData = top.voting.form.serialize();
		var formUrl = top.voting.form.attr("action");
		$top.ajax({
			type: "POST",
			url: formUrl,
			data: formData,
			dataType: "json",
			error: function(jsonData){
				var msg = (jsonData.validation) ? " (" + jsonData.validation.msg + ")" : "";
				top.hint.openHintLayer('Fehler', 'Es ist ein Fehler aufgetreten' + msg + '. Bitte versuchen Sie es zu einem sp&auml;teren Zeitpunkt nochmal.', 'Okay');
			},
			success: function(jsonData){
				if (typeof callback == "function") {
					callback.call(this, "votingCallbackSuccessAfterLoginOpt"+voteOpt.toUpperCase());
					return;
				}
				if (jsonData.isLoginRequired) {
					window.location.href = top.voting.hrefStep2;
				} else {
					var status = jsonData.status;
					switch(status) {
						case "success":
							window.location.href = top.voting.hrefStep3;
							// Update percentage and text of source page
							if (jsonData.additional.votingScore != "" && jsonData.additional.votingText != "") {
								top.voting.srcMainDiv.children(".result").html('<span>' + jsonData.additional.votingScore + '%</span>' + jsonData.additional.votingText);
							}
						break;
						case "failed":
							var msg = (jsonData.validation) ? " (" + jsonData.validation.msg + ")" : "";
							top.hint.openHintLayer('Fehler', 'Es ist ein Fehler aufgetreten' + msg + '. Bitte versuchen Sie es zu einem sp&auml;teren Zeitpunkt nochmal.', 'Okay');
						break;
					}
				}
			}
		});
	}
}


// IE6 Compatibility Hint!
/*
if($top.browser.msie && $top.browser.version < 7) {
	$top('#content').before('<div id="noscript">' +
								'<p><span>Hinweis:</span> Sie benutzen einen veralteten Browser. Es werden nicht alle Funktionen von TOP.DE unterstützt.<br /><a href="http://service.gmx.net/de/cgi/g.fcgi/products/browser?mc=gmx@hp@home@qrect_login.gmx_produkte@browser" target="_blank">Sie k&ouml;nnen kostenlos und einfach Ihren Browser aktualisieren.</a></p>' +
							'</div>');
}
*/



/* ---------------------------------------------------------------------------- */
/* ----- JS FOR ALL THE ELEMENTS COMING _AFTER_ THE INCLUSION OF THIS LIB ----- */
/* ---------------------------------------------------------------------------- */


$top(document).ready(function() {
	// top.de Login URL
	top.loginUrl = $top('.login-link').attr('href');
	//$top('#toolbar').show(); // show toolbar

	if($top("a[rel^='prettyphoto']").length > 0) {

		$top("a[rel^='prettyphoto']").each(function() {
			var href = $top(this).attr('href');
			var rel = $top(this).attr('rel');
			var title = $top(this).attr('title');
			$top(this).next('img').wrap('<a href="' + href + '" rel="' + rel + '" title="' + title + '"></a>');
			$top(this).remove();
		});

		$top("a[rel^='prettyphoto']").prettyPhoto({
			animationSpeed: 'normal',
			padding: 16,
			allowresize: false,
			theme: 'light_square',
			modal: false
		});
	}
	if($top("a[rel^='lbpopup']").length > 0) {

		$top("a[rel^='lbpopup']").each(function() {
			var tmp = $top(this).next().html();
			$top(this).next().remove();
			$top(this).html(tmp).wrap($top(this));
		});

		$top("a[rel^='lbpopup']").each(function() {
			$top(this).removeClass('off')
		});

		$top("a[rel^='lbpopup']").prettyPhoto({
			padding: 16,
			allowresize: false,
			theme: 'light_square',
			modal: true
		});
	}

	if($top('form.my-account .hint').length > 0) {
		$top('form.my-account .hint').slideDown('slow');
	}

	if($top('.slideshow').length > 0) {
		$top(window).bind('hashchange', function() {
			var hash = window.location.hash
			hash = parseInt(hash.substring(1,(hash.length)));
			top.slideshow.changePicFromHash(hash);
		});
	}

	/*if(adRefresh) {
		top.adRefresh.init();
	}*/

	// Voting-callback
	if (window.location.href.indexOf("votingCallbackSuccessAfterLoginOpt") != -1) {
		var url = "";
		if (window.location.href.indexOf("votingCallbackSuccessAfterLoginOptA") != -1) {
			url = $top("#vote-confirm-url-a").val();
		} else if (window.location.href.indexOf("votingCallbackSuccessAfterLoginOptB") != -1) {
			url = $top("#vote-confirm-url-b").val();
		}
		if (url == "") return;
		url = (url.indexOf("?") != -1) ? url += "&" : url += "?";
		var a = $top("#voting .vote a");
		var param = a.attr("href").split("?")[1];
		var title = a.attr("title");
		$top.prettyPhoto.open(url + param, title);
	}

	if(typeof(top.openRegConfirm) != "undefined" && top.openRegConfirm != "" && window.location.hash.indexOf('openRegConfirm') != -1) {
		if(typeof($top.prettyPhoto.open) != "undefined") {
			$top.prettyPhoto.open(top.openRegConfirm, "Anmelden");
		} else {
			top.hint.openHintLayer('Herzlich Willkommen bei top.de', 'Dein Account wurde aktiviert.', 'Okay');
		}
	}

	if(window.location.hash.indexOf('openAccDelConfirm') != -1) {
		top.hint.openHintLayer('Okay', 'Dein Account wurde gel&ouml;scht.', 'Schlie&szlig;en');
	}
});