var PromoSlideshow = function(elementid, fxId, duration, directNav) {
	this.duration = duration;
	this.directNav = directNav; 
	this.container = $(elementid).select(".slideShowContainer")[0];
	this.fxId = fxId;
	this.slides = this.container.select("li");
	this.slideCount = this.slides.size();
	this.current = this.slides.length-1;
	if (this.slideCount<=1) return; // no slide show if only one image
	var controlHTML = "<div class='control' style='display:none'>";
	if (!directNav) {
		controlHTML += "<a href='#zur&uuml;ck' rel='back' class='back'>&nbsp;</a><a href='#vor' rel='next' class='next'>&nbsp;</a>";
	}
	else {
		this.slides.each(function(slide,index) {
			controlHTML += "<a href='#"+slide.title+"' class='item' rel='"+index+"'>"+slide.title+"</a>";
		});
	}
	controlHTML += "</div>";
	this.container.insert(controlHTML ,{position: "bottom"});
	this.control = this.container.select('div.control')[0];
	Event.observe(this.container, "mouseover", this.over.bindAsEventListener(this));
	Event.observe(this.container, "mouseout", this.out.bindAsEventListener(this));
	Event.observe(this.container, "click", this.clickContent.bindAsEventListener(this));
	this.control.select('a').each(
		function(link) {  Event.observe(link, "click", this.clickNav.bindAsEventListener(this))  },
		this);
	this.start();
};

PromoSlideshow.prototype = {

	start: function() {
		this.timer = new PeriodicalExecuter(this.tick.bind(this), this.duration);	
	},
	
	pause: function() {
		this.timer.stop();
	},

	tick: function() {
		this.showNext();
	},
	
	currentSlide: function() {
		return this.slides[this.current];
	},
	
	nextSlide: function() {
		var index = 0;
		if (this.current==0) {
			index = this.slideCount - 1;
		}
		else {
			index = this.current - 1;
		}
		return this.slides[index];
	},
	
	prevSlide: function() {
		var index = 0;
		if (this.current==this.slideCount-1) {
			index = 0;
		}
		else {
			index = this.current + 1;
		}
		return this.slides[index];
	},
	
	showNext: function(instantly) {
		var currentSlide = this.currentSlide();
		
		if(this.directNav)
			this.control.select('a')[this.current].className = 'item';
		
		var nextSlide = this.nextSlide();
		if (!instantly) {
			currentSlide.style.zIndex = 1;
			nextSlide.style.zIndex = 0;
			nextSlide.style.left = "0";
			nextSlide.show();
			if (this.fxId==1) {
				new Effect.DropOut(currentSlide);
			}
			else {
				new Effect.Move(currentSlide,{ x: -800, y: 0, mode: 'absolute', duration:1});
			}
		}
		else {
			nextSlide.style.left = "0";			
			currentSlide.hide();
			currentSlide.style.zIndex = 0;			
			nextSlide.style.zIndex = 1;
			nextSlide.show();			
		}
		this.current--;
		if (this.current<0) this.current = this.slideCount-1;
		
		if(this.directNav)
			this.control.select('a')[this.current].className = 'item on';
	},
	
	showPrev: function() {
		var currentSlide = this.currentSlide();
		var prevSlide = this.prevSlide();
		currentSlide.hide();
		currentSlide.style.zIndex = 0;
		prevSlide.style.zIndex = 1;
		prevSlide.style.left = "0";
		prevSlide.show();
		this.current++;
		if (this.current==this.slideCount) this.current = 0;
	},
	
	showSlide: function(index) {
		var currentSlide = this.currentSlide();
		var newSlide = this.slides[index];

		currentSlide.hide();
		currentSlide.style.zIndex = 0;
		newSlide.style.zIndex = 1;
		newSlide.style.left = "0";
		newSlide.show();
		this.current = index;
	},
	
	over: function() {
		this.control.show();
		this.pause();
	},
	
	out: function() {
		this.control.hide();
		this.start();
	},
	
	clickContent: function() {
		var currentSlide = this.currentSlide();
		var link = currentSlide.getElementsByTagName("a")[0];
		if (link) {
			window.location.href = link.href;
		}
	},
	
	clickNav: function(e) {
		var direction = e.element().rel;
		if (direction=="next") {
			this.showNext(true);
		}
		else if (direction=="back") {
			this.showPrev();
		}
		else {
			this.control.select('a')[this.current].className = 'item';
			this.showSlide(direction);
			this.control.select('a')[this.current].className = 'item on';			
		}
		e.stop();
		e.element().blur();
	}
};

// Layout specific functions

var KISSProfile = {
	selectVisibilityType: function(fieldid, val, link) {//alert(fieldid);
		if (fieldid.indexOf("_GROUP_")>-1) {
			var group = fieldid.replace(/.+_GROUP_/,"");
			var list = $$("input[type=hidden]");
			list.each(function(element){
				var eid = element.id;
				if (eid.indexOf("_GROUP_"+group)>-1) {
					element.value = val;
				}
			});
		}
		else {
			$(fieldid).value = val;
		}
		var l = $(link);
		l.siblings().each(
			function(item) {
				var s = item.className;
				item.className = s.replace(/selected/g,"");
			}
		);
		if (link.className.indexOf("selected")==-1) {
			link.className = link.className+"selected";
		}
		link.blur();
		return false;
	},
	openColorSelector: function(id) {
		var container = $("colcon"+id);
		if (container) {
			if (container.visible()) {
				container.hide();
			}
			else {
				container.show();
			}
		}
		return false;
	},
	selectColor: function(link, id) {
		var val = link.className;
		var container = $("colcon"+id);
		var selector = $("colsel"+id);
		var field = $("value"+id);
		field.value = val;
		selector.className = val+" selector";
		container.hide();
		return false;
	},
	openFriendshipRequest: function(username) {
		$("requestUserName").update(username);
		KISSPage.dimPage('requestFriend');
		return false;
	},
	requestFriendship: function() {
		$("friendshipMessage").value = $("uiFriendshipMessage").value;
		$("requestFriendshipForm").submit();
		return false;
	},
	searchUser: function(url) {
		$("uSearchResults").addClassName("searching");
		$("uSearchResults").update("");
		new Ajax.Updater("uSearchResults", url, {parameters: {term:$("uSearch").value}, onComplete: KISSProfile.searchResultDisplay});
	},
	searchResultDisplay: function() {
		$("uSearchResults").removeClassName("searching");
	}
};


var KISSPageClass = function() 
{
	var bFlashHidden = false;
	var KISSPage = this;
	
	this.init = function() {
		this.fitMonsterBanner();

		if(Prototype.Browser.IE 
			&& parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6
		){
			listHover('nav');
			listHover('specialNav');
			listHover('footerNav');
		}

		var goTop = $$('#footerNav li.goTop a');
	
		if(goTop[0] && goTop[0] != 'undefined') {
			goTop[0].onclick = function() { 
				new Effect.ScrollTo(document.body, {duration:0.5}); 
				this.blur(); 
				return false; 
			}
		}			

		// is there a login error?
				
		if (location.search.indexOf("message=")>-1) {
			this.dimPage("clubLogin");
		}
		
		var loginform = $("CommunityLoginForm");
		if (loginform) {
			Event.observe(loginform, "submit", KISSPage.checkLoginSubmit);
			var statefield = $("login_userstate");
			if (statefield) { 
				Event.observe(statefield, "focus", KISSPage.stateFieldFocus);
				Event.observe(statefield, "click", KISSPage.stateFieldFocus);
			}
		}
	}
	
	// list hover for ie6
	 function listHover(_listId) {
	  	var navRoot, node = null;
		if (document.getElementById(_listId)) 
		{
			navRoot = document.getElementById(_listId);
			for (i=0; i<navRoot.childNodes.length; i++) {
				node = navRoot.childNodes[i];
				if (node.nodeName=="LI" && node.firstChild.nodeName=="DIV") {
					node.firstChild.onmouseover=function() {
						this.className+=" over";
		  			}
		  			node.firstChild.onmouseout=function() {
		  				this.className=this.className.replace(" over", "");
		   			}
		   		}
			}
		}
	}
	
	// monsterbanner sizing
	this.fitMonsterBanner = function () {
		var banner = $("monsterbanner");
		if (banner) {
			var width = (document.viewport.getWidth() > 980) ? document.viewport.getWidth() : 980; // $(document.body).getWidth();
			banner.style.width = width+"px";
		}
	}
	
	// page dimmer
	this.dimmerLastHighlighted = null;
	
	this.dimPage = function(highlightElement) {
		return KISSPopup.show(highlightElement);
	}
	
	this.displayLoginForm = function(stayOnThisPage, profileOwner, anchor){
		if ($("CommunityLoginForm")['defaultTargetNode']){
			if (stayOnThisPage){
				$("CommunityLoginForm")['targetNode'].value=$("CommunityLoginForm")['thisNode'].value;
			}
			else{
				$("CommunityLoginForm")['targetNode'].value=$("CommunityLoginForm")['defaultTargetNode'].value;
			}
		}	
		if (profileOwner){
			var user = $("CommunityLoginForm")['user'];
			if (!user){
				var hiddenInput=document.createElement("input");
				hiddenInput.type="hidden";				
				hiddenInput.name="user";				
				user = $("CommunityLoginForm").appendChild(hiddenInput);
				
			}
			user.value=profileOwner;
		}
		else if ($("CommunityLoginForm")['user']){
				($("CommunityLoginForm")['user']).remove();			
		}
		//alert(anchor);
		if (anchor){
			if (!$("CommunityLoginForm")['anchor']){
				var hiddenInput=document.createElement("input");
				hiddenInput.type="hidden";				
				hiddenInput.name="anchor";				
				$("CommunityLoginForm").appendChild(hiddenInput);
			}
			$("CommunityLoginForm")['anchor'].value=anchor;
		}
		else if ($("CommunityLoginForm")['anchor']){
				($("CommunityLoginForm")['anchor']).remove();			
		}		
		
		return this.dimPage('clubLogin');		
	}
	
	this.displayPopupContent = function(_AElement, _targetName) {
		return KISSPopup.displayPopupContent(_AElement, _targetName);
	}
	
	this.centerPopup = function() {
		KISSPopup.center();
	}

// event handler	
	this.onResize = function() {
		this.fitMonsterBanner();
	}
	
	this.hideDimmer = function() {
		
		return KISSPopup.hide();
	}
	
	this.openToolWindow = function() {
		var win = window.open("about:blank","communitytool", "width=780, height=500, scrollbars=yes, resizable=yes, status=yes");
  		win.focus();
	}
	
	// login form
	this.checkLoginSubmit = function(event) {
		var statefield = $("login_userstate");
		if (statefield) {
			if (statefield.hasClassName("hint") || statefield.value == $("login_username").value + " ") {
				statefield.value = "";
			}
		} 
	}
	
	this.stateFieldFocus = function(event) {
		var e = Event.element(event);
		if (e.hasClassName("hint")) {
			KISSPage.loginHintState = e.value;
			e.removeClassName("hint");
			e.value = $("login_username").value + " ";
		}
	}
	
	this.resizeElement = function(_elementId, _newHeight) {
		var e = $(_elementId);
		if(!e || !_newHeight) {
			return false;
		}
		e.style.height = _newHeight + 'px';
		return true;
	}
	this.visibleElement = null;
	this.toggleElement = function(_elementId) {		
		var e = $(_elementId);		
		if(!e) {
			return false;
		}

		e.style.display = (e.style.display != 'block') ? 'block' : 'none';
		return true;
	}
	
	this.eegg = function() {
		var ticker = $('onair');
		
		if(!ticker)
		{ return; }
		
		var flashObject = ticker.select('Object')[0];
		var flashEmbed = ticker.select('EMBED')[0];
				
		ticker.style.overflow = 'visible';
		
		if(flashObject)
		{ 				
			flashObject.height = 180
			flashObject.width = 810
		}
		if(flashEmbed)
		{
			flashEmbed.height = 180;
			flashEmbed.width = 810;
		}

	}
}

var PopupLayerClass = function(_dimmId, _popupId) {

	var Popup = this;
	var bVisible = false;

	var popup = null;
	var popupId = (_popupId) ? _popupId : null;
	var popupOrgDims = null;
	var activePopup = null;

	var dimmer = null
	var dimmId = (_dimmId) ? _dimmId : null;
	var dimmerOpacity = 0.75;
	
	var dimmerTFadeIn = 0.35;
	var dimmerTFadeOut = 0.25;
	
	var dimmerFx = null;
	
	var bInitialised = false;
	
	this.init = function() {
		createDimmer();
		
		if(popupId && $(popupId)) {
			popup = $(popupId);
		}
		else
			return;

		if(popup) { 
			popup.select('div.popupContent').invoke('hide');
			
			popupOrgDims = popup.getDimensions(); 

			new Draggable(popup, { 
				revert: true, zindex:20001, starteffect:null, endeffect:null, 
			 	reverteffect: 
			 
					function(element, top_offset, left_offset) {
        				var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
        					new Effect.Move(element, 
        					{ 
        						x: -left_offset, y: -top_offset, duration: dur,
          						queue: {scope:'popup', position:'front'},
          						transition: Effect.Transitions.spring
          					})
					}
			});
		}
		
		bInitialised = true;
	}
	
	function createDimmer() {
		if(dimmId && $(dimmId)) {
			dimmer = $(dimmId);
		}
		else {
			dimmer = new Element('DIV', { id: (dimmId) ? dimmId : 'Dimmer', style: 'display:none' });
			$$('body')[0].insert(dimmer);
		}
		
		dimmer.setOpacity(0.0);
		dimmer.onclick = Popup.hide;
	}
	
	function showDimmer() {
		dimmer.show();
		resizeDimmer();
		
		if(dimmerFx) { dimmerFx.cancel(); }
		dimmerFx = new Effect.Opacity(dimmer, { from: 0.0, to: dimmerOpacity, duration: dimmerTFadeIn, queue: {scope:'popup', position:'front'} });
	}
	
	function hideDimmer() {
		if(dimmerFx) { dimmerFx.cancel(); }
		dimmerFx = new Effect.Opacity(dimmer, { from: dimmerOpacity, to: 0.0, duration: dimmerTFadeOut, afterFinish: function(){ dimmer.hide(); }, queue: 'front'  });
	}
	
	this.displayPopupContent = function(_AElement, _targetName) {
		var popupContent = $('popupContent');
		var dims = null;
		var iFrame = null;
		
		if(!popupContent && !bInitialised)
		{ return true; }
		
		// dims = popup.getDimensions();

		iFrame = popupContent.select('IFRAME')[0];		
		
		iFrame.onload = function() {
			var iC = this.contentWindow.document;
			var c = iC.getElementById('content');
		
			iFrame.style.height = c.getHeight() + 10 + 'px';
			KISSPopup.center();
		};
		
		if(_targetName)
		{	iFrame.name = _targetName; }
			
		if(_AElement)
		{
			iFrame.src = _AElement.href;
		}
		
		popup.style.width = '770px';
		
		
		this.show('popupContent');
		
		_AElement.blur();
		
		return false;	
	}	
	
	this.show = function(highlightElement) {

		var showme = $(highlightElement);

		if(!popup || !showme) { return false; }
	
		if(!dimmer.visible()) {
			showDimmer();
		}
		
		if(activePopup)
		{
			activePopup.hide();
			popup.style.width = popupOrgDims.width + 'px';
		}
		
		activePopup = showme;
		
		showPopup();
		
		return false;
	}
	
	function showPopup()
	{
		if(!popup) return false;
		
		var pdims = popup.getDimensions();
		var scroll = document.viewport.getScrollOffsets();
		var vdims = document.viewport.getDimensions();

		var left = (((vdims.width < 980) ? 490 : vdims.width/2) - pdims.width/2 + scroll.left); // + "px";
		var top = (((vdims.height - pdims.height) < 0) ? 0 : (vdims.height - pdims.height)/2); // + "px";

		popup.style.top =  top + 'px';
		popup.style.left =  -pdims.width + 'px';

		popup.show();
		
		var iFrame = activePopup.getElementsByTagName('IFRAME')[0];
		if(iFrame) { 
			iFrame.hide();
		 }
		 
		activePopup.show();

		var forms = activePopup.select("form");
		if (forms[0]) { forms[0].focusFirstElement(); }
				
		var move = new Effect.Move(popup, { 
			x: left, y: top, duration: 0.35, mode: 'absolute',
			queue: {scope:'popup', position:'end'},
			afterFinish: function() { 		

			if(iFrame) { iFrame.show(); } }
		});
		
				
	}

	function hidePopup() {
		var iFrame = popup.select('IFRAME')[0];
		if(iFrame) { 
			iFrame.src = 'about:blank';
			iFrame.hide();
		 }
		 
		popup.style.width = popupOrgDims.width + 'px';
			
		
		var pdims = popup.getDimensions();
		var scroll = document.viewport.getScrollOffsets();
		var vdims = document.viewport.getDimensions();

		//popup.style.left, popup.style.top  
		var left = vdims.width + 10;
		var top = (((vdims.height - pdims.height) < 0) ? 0 : (vdims.height - pdims.height)/2); // + "px";

		//popup.style.position = 'absolute';
		//alert(popup.style.left);
		//var dur = Math.sqrt(Math.abs(top^2)+Math.abs(left^2))*0.02;
				
		var move = new Effect.Move(popup, { 
			x: left, y: top, duration: 0.25, mode: 'absolute',
			queue: {scope:'popup', position:'end'},
  			transition: Effect.Transitions.sinoidal,
  			afterFinish: function() {
  					activePopup.hide();	
					activePopup = null;
					popup.hide();
  			} 
		});					
					
		//Effect.SlideUp(KISSPage.dimmerLastHighlighted, { duration: 0.5, afterFinish: hidePopup });

	}
	
	this.hide = function() { 
		if(!popup) { return false; }
		
		if (dimmer.visible()) {
			hideDimmer();	
		}
			
		if (activePopup) {
			hidePopup();
		}	
		return false;			
	}
	
	this.center = function() { center(); }
	
	function center() {
		if(!popup || !popup.visible()) return false;

		var pdims = popup.getDimensions();
		var scroll = document.viewport.getScrollOffsets();
		var vdims = document.viewport.getDimensions();

		var left = (((vdims.width < 980) ? 490 : vdims.width/2) - pdims.width/2 + scroll.left); // + "px";
		var top = (((vdims.height - pdims.height) < 0) ? 0 : (vdims.height - pdims.height)/2); // + "px";
		var dur = Math.sqrt(Math.abs(top^2)+Math.abs(left^2))*0.02;
		
		var move = new Effect.Move(popup, { 
			x: left, y: top, duration: dur, mode: 'absolute'
		});	
	}
	
	function resizeDimmer() {
		var pageDim = $(document.body).getDimensions();
		var vdims = document.viewport.getDimensions();
		if (dimmer && dimmer.visible()) {
			dimmer.style.width = (document.viewport.getWidth() > 980) ? document.viewport.getWidth() + "px" : 980 + "px"; // pageDim.width + "px";
			dimmer.style.height = (pageDim.height < vdims.height)? vdims.height + "px": pageDim.height + "px";
		}
	}
	
	this.onResize = function() {
		center();
		resizeDimmer();
	}
	
	this.toString = function() {
		return popupId + '[PopupLayerClass].' + ((bInitialised) ? 'initialised' : 'disabled');
	}
}

/* init page, register event listeners */
var KISSPage = new KISSPageClass();
var KISSPopup = new PopupLayerClass('KissDimmer', 'popupWrapper');


if(Prototype.Browser.IE) {
	Event.observe(window, "load", function() { KISSPopup.init(); KISSPage.init(); }); 
}
else {
	Event.observe(document, "dom:loaded", function() { KISSPopup.init(); KISSPage.init(); }); 
}

Event.observe(window, "resize", function() { KISSPage.onResize(); KISSPopup.onResize(); });