/* global variables start */

var actualPageId = -1;
var initialStartupId = -1;
var ajaxContentCall = new Ajax('null', {method: 'get', autoCancel:'true', onSuccess: ajaxContentSuccess});
var ajaxTagcloudCall = new Ajax('null', {method: 'get', autoCancel:'true', onSuccess: ajaxTagcloudSuccess});
var navFoldInDelay;
var navContentDelay;
var navFoldOutDelay;
var langSwitchPaths;
var accordionContentDetails;
var accordionPressOverview;
var accordionJobsOverview;
var historyKeeper;
var contentProjectDetailsSlide;
var contentProjectDetailsSlideIn;
var projectDetails;
var currentJobApplicationId = 0;
var navigatonSlideState;
var pressScrollOldPosition = 0;
var currentPageIsRecommendationForm = false;
var flashAppLoader;
var tagcloudLoaded = false;
//var durationSlideOut = 0;
//var transitionSlideOut = Fx.Transitions.Cubic.easeOut;
var transitionSlideOut = Fx.Transitions.linear;
var transitionSlideIn = Fx.Transitions.linear;

var durationSlideOut = 400;
var durationSlideOutDelay = 600;
//var durationSlideIn = 250;
var durationSlideIn = 400;
var durationSlideInDelay = 600;
//var durationSlideIn = 0;
/* global variables end */

var cDelay1;
var cDelay2;
var _keepTagcloud	= false;

var subnavTweens	= new Array( false, false, false, false, false, false, false, false );

var isIE	= navigator.appName.indexOf("Internet Explorer") > -1;
var isMac		= (navigator.appVersion.indexOf("Mac")!=-1);

// window.domready Events
window.addEvent('domready', function()
{
	if( isIE && window.ie7 )
	{
		isIE	= false;
	}
	windowResized();
	window.onresize = function() {
		windowResized();
	}

	/* global variables start */
	navSlide = new Fx.Style('navContent', 'left', {duration: durationSlideOut, wait:false, transition: transitionSlideOut});
	navSlideIn = new Fx.Style('navContent', 'left', {duration: durationSlideIn, wait:false, transition: transitionSlideIn});
	contentSlide = new Fx.Style('ajaxContent', 'margin-left', {duration: durationSlideOut, wait:false, transition: transitionSlideOut, onComplete: function() { scaleTagcloud();}});
	contentSlideIn = new Fx.Style('ajaxContent', 'margin-left', {duration: durationSlideIn, wait:false, transition: transitionSlideIn, onComplete: function() { scaleTagcloud();}});

	if( $('projectDetailsMedia') != null )
	{
		$('projectDetailsMedia').setStyle( 'left', 416 );
	}
	$('ajaxContent').setStyle( 'margin-left', 416 );

	navMove = new Fx.Style('nav', 'height', {duration: 200, wait:false});
	$('nav').setStyle('height',80);

	formSpecApp = new FormSpeculativeApplication();
	formLiveCommNews = new FormLiveCommunicationNews();
	formContact = new FormContact();
	formRecommendation = new FormRecommendation();
	formNewsletter = new FormNewsletter();

	/* global variables end */


	//$('ajaxContent').setStyle('margin-left',"40px");
	$('navContent').setStyle('z-index',10);


	$('navContent').addEvent('mouseenter', function()
	{
		$clear(navContentDelay);
		navContentDelay = (function(){ slide('navOut')}).delay(durationSlideOutDelay);
	});
	$('navContent').addEvent('mouseleave', function( evt )
	{
		if( evt.client.x < 100 )
		{
			return;
		}
		if ( actualPageId != '' )
		{
			$clear(navContentDelay);
			navContentDelay = (function(){ slide('navIn')}).delay(durationSlideInDelay);
		}
	});

	/* register navigation links for ajax-calls */
	$('nav').getElements('a').each(function(link)
	{
		link.onclick = function()
		{
			unloadExtendedContent();
			$('nav').getElements('.current').each( function(activeLink)
			{
				activeLink.removeClass('current');
			});
			navMove.start.bind(navMove).pass(16).delay(0);
			$('nav').getElements('.secondNavigation').each( function (subnav)
			{
				//subnav.effect('opacity', {duration: 0}).start(0);
				setSubnavHeight( subnav, 1, true );
			});

			openPage(link.getProperty('rel'));
			return false;
		}
	});

	/* register secNav dynamic behaviour */
	$('nav').getElements('.secondNavigation').each( function (subnav)
	{
		var primenav = subnav.getParent();
		var subnavHeight = subnav.getSize().size.y + 20;

		subnav.setStyle('opacity', 1);
		subnav.setStyle( 'height', 1 );

		if( isMac )
		{
			subnav.getElements('li.secondNavigationElement').each( function(ele)
			{
				ele.setStyle( 'margin-top', 4 );
			});
		}

		primenav.addEvent('mouseenter', function()
		{
			instantFlashAction( "pause", 500 );
			$clear(navFoldInDelay);
			$clear(navFoldOutDelay);
			//subnav.effect('height',{duration:500}).start(100);


			/*
			$('nav').getElements('.secondNavigation').each( function (subnav_other)
			{
				if( subnav_other != subnav )
				{
					//setSubnavHeight( subnav_other, 5, true );
				}

				//var primenav_other = subnav_other.getParent();
				//if (this != primenav_other)
				{
					//subnav_other.setStyle('opacity', 0);
				}

			});*/

			navFoldOutDelay = (function ()
			{
				//subnav.effect('opacity', {duration: 400}).start(0,1);
				//subnav.setStyle( 'opacity', 1 );
				setSubnavHeight( subnav, subnavHeight, false );
			}).delay(0);
		});

		primenav.addEvent('mouseleave', function ()
		{
			$clear(navFoldInDelay);
			$clear(navFoldOutDelay);
			//navFoldOutDelay = (function(){ subnav.effect('opacity', {duration: 0}).start(0);}).delay(0);
			setSubnavHeight( subnav, 1, false );
			//navFoldInDelay = navMove.start.bind(navMove).pass(16).delay(0);
		});
	});

    // different font-family-stylesheet for operation system
    if(isWin()) $('body').addClass('bodyWin');
    else $('body').addClass('bodyRest');
});


function setSubnavHeight( obj, h, instant )
{
	var id	= getSubnavId( obj );
	var t	= 600;

	if( instant )
	{
		t	= 0;
	} else if( h == 1 ) {
		t	= 200;
	}

	if( !subnavTweens[id] )
	{
		subnavTweens[id]	= new Fx.Style( obj, 'height', {duration: t, wait:false} );
	}
	subnavTweens[id].options.duration	= t;

	subnavTweens[id].stop();
	subnavTweens[id].start(h);
}


function getSubnavId( obj )
{
	var s	= $('nav').getElement(".firstNavigation").getElements("ul");
	for( var i = 0; i < s.length; i++ )
	{
		if( s[i] == obj )
		{
			return i;
		}
	}

	return -1;
}


// window.load Events
window.addEvent('load', function ()
{
	initialStartupId = initialPageId;
    historyKeeper = new HistoryKeeperFunc();
});




/**
 * Inhalte an die Fenstergroesse anpassen
 */
function windowResized()
{
    scaleTagcloud();
}


/**
 * get position + margins + screenheight and calculate the tagcloud height
 */
function scaleTagcloud(offset)
{
	var offsetParam = offset != undefined ? offset : 0;

	var windowInnerHeight = 0;
	if(window.ie) windowInnerHeight = document.body.clientHeight;
	else windowInnerHeight = window.innerHeight;

	var divMargins = 15 + 38 + 18 + 10;
	var tagCloudPositionOffset = $('tagcloud').getPosition().y;
	var metaOffset = 10;
	var enoughOffet = 0;
	var flashHeight = windowInnerHeight - (tagCloudPositionOffset + divMargins + metaOffset + offsetParam + enoughOffet);

	$('tagcloud').setStyle('height', flashHeight);
}


/**
 *
 */
function isWin()
{
	return navigator.platform.toLowerCase().contains('win');
}

/**
 *
 */
function resetNavigationCurrents()
{
	$('nav').getElements('.current').each( function(activeLink)
	{
		activeLink.removeClass('current');
	});
	$('meta').getElements('.current').each( function(activeLink)
	{
		activeLink.removeClass('current');
	});
}


/**
 * externalInterface communication: as -> js when tagElement was clicked
 */
function tagClick(pageId,keepTagcloud)
{
	if( keepTagcloud == undefined )
	{
		keepTagcloud	= false;
	}

	openPage(pageId, undefined, keepTagcloud);
}


/**
 * externalInterface callback: as -> js, when flash movie is loaded
 */
function flashLoaded()
{
	tagcloudLoaded = true;
	return false;
}


/**
 * externalInterface communication: js -> as
 * @param func {String} this function is called in Flash
 * @param arg {}
 * @param acid {String} Active-Content-Id
 */
function flashAction(func, arg, acid)
{
	flashAppLoader = flashActionLoader.periodical(200, this, [func, arg, acid]);
}


/**
 *
 */
function flashActionLoader(func, arg, acid)
{
	var cloud = document.getElementById("flashNavigation");
	if( cloud && tagcloudLoaded )
	{
		if(cloud.PercentLoaded() == '100')
		{
			//kill
			$clear(flashAppLoader);
			if(!acid)
			{
				cloud[func](arg);
			}
			else
			{
				cloud[func](arg, acid);
			}
		}
	}
}

function instantFlashAction(func, arg)
{
	var video = document.getElementById("flashVideoPlayer");
	if( video )
	{
		video[func](arg);
	}

	var gallery = document.getElementById("flashGallery");
	if( gallery )
	{
		gallery[func](arg);
	}
}


/**
 * open complete new page
 * @param pageId {Number} pageId to open
 * @param meta {Boolean} metaNavigationElement
 */
function openPage(pageId, meta, keepTagcloud)
{
	if( keepTagcloud == undefined )
	{
		keepTagcloud	= false;
	}

	_keepTagcloud	= keepTagcloud;

	scaleTagcloud();
	currentPageIsRecommendationForm = false;
	historyKeeper.addHistory(pageId);
	return false;
}


/**
 * open complete new page
 * @param pageId {Number} pageId to open
 * @param meta {Boolean} metaNavigationElement
 */
function openPageAlias(pageId, meta, keepTagcloud)
{
	if (pageId == '')
	{
		pageId = '/' + currentLanguage + '/';
	}
	if( keepTagcloud == undefined )
	{
		keepTagcloud	= false;
	}

	scaleTagcloud();
	resetNavigationCurrents();
	if(meta != undefined && meta != null && meta == 'meta')
	{
		$(pageId).addClass('current');
	}
	loadTagcloud(pageId,keepTagcloud);
	loadContent(pageId);
	return false;
}


/**
 * make ajax-call for left content
 * @param pageId {Number} pageId to open
 */

function loadTagcloud(pageId,keepTagcloud)
{
	if( keepTagcloud == undefined )
	{
		keepTagcloud	= false;
	}

	if (pageId == actualPageId)
	{
		return;
	}

	_keepTagcloud	= keepTagcloud;

	//var urlTagcloud = pageBaseUrl + '/tagcloud/' + currentLanguage +  '/' + pageId;
	var urlTagcloud = pageBaseUrl + pageId + '/sidebar.txt';
	ajaxTagcloudCall.url = urlTagcloud;
	ajaxTagcloudCall.request();
}


/**
 * handle the ajax response for the left content
 * @param response {Object} ajax
 */

function ajaxTagcloudSuccess(response)
{
    response = Json.evaluate(response);
    var tagcloud = response.tagcloud.elements;
    var breadcrumb = response.breadcrumb;
    var navigationFirstHighlight = response.firstNavigationHighlight;
    var navigationSecondHighlight = response.secondNavigationHighlight;
    var sortingHead = response.sortingHead;
    var sorting = response.sorting.elements;

    langSwitchPaths = response.langswitch;
    var activeContentId = response.tagcloud.active;
    //changeBreadcrumb(breadcrumb);
    changeNavigation(navigationFirstHighlight, navigationSecondHighlight);
	// IE DEBUG: (function(){changeTagCloud(tagcloud, activeContentId);}).delay(3000);
    changeFilter(sortingHead);


	/*
	var cloudChange = function() {
		var cloud = document.getElementById("flashNavigation");
		alert(cloud);
		if( cloud )
		{
			cloud.showSorting( sortingHead, sorting );
			cloud.assignBread( breadcrumb );
		}
	};

	cloudChange.delay(1000);
	*/

	var initDelay = 200;
	if (isIE)
	{
		var initDelay = 1000;
	}
	(function(){cloudChange(sortingHead, sorting, breadcrumb, tagcloud, activeContentId);}).delay(initDelay);

}

function cloudChange(sortingHead, sorting, breadcrumb, tagcloud, activeContentId)
{
	var cloud = document.getElementById("flashNavigation");
	if( cloud && tagcloudLoaded )
	{
		cloud.showSorting( sortingHead, sorting );
		cloud.assignBread( breadcrumb );
		changeTagCloud(tagcloud, activeContentId);
	}
	else
	{
		(function(){cloudChange(sortingHead, sorting, breadcrumb, tagcloud, activeContentId);}).delay(100);
	}
}


/**
 * externalInterface communication: js -> as
 * @param paramObj {Array} tagcloud-elements
 * @param activeContentId {Array} active contentId
 */
function changeTagCloud(paramObj, activeContentId)
{
    if( _keepTagcloud )
    {
    	_keepTagcloud	= false;
	return;
    }
    flashAction('assignTags', paramObj, activeContentId);
}


/**
 * change breadcrumb
 * @param {String}
 */
function changeBreadcrumb(breadcrumb)
{
	//$('bread').setHTML(breadcrumb);
}


/**
 * change navigation
 * @param {String}
 * @param {String}
 */
function changeNavigation(first, second)
{
	$('nav').getElements('a').each(function(link)
    {
		if(first != undefined && first != '' && link.getProperty('cid') == first)
		{
			link.addClass('current');
		}
		if(second != undefined && second != '' && link.getProperty('cid') == second)
		{
			link.addClass('current');
		}
	});
	$('meta').getElements('a').each(function(link)
    {
		if(second != undefined && second != '' && link.getProperty('cid') == second)
		{
			link.addClass('current');
		}
	});
}


/**
 * change navigation
 * @param {String}
 * @param {String}
 */
function changeFilter(filter)
{
	if(filter != undefined && filter != '')
	{
		$('sortAfter').setHTML(filter);
	}
	else
	{
		$('sortAfter').setHTML('');
	}
}


function performLangswitch(language)
{
	this.location.href= pageBaseUrl + langSwitchPaths[language];
	writeSiteLangCookie(language);
}

function writeSiteLangCookie(lang)
{
	var a = new Date();
	a = new Date(a.getTime() + (60*60*24*14*1000));
	document.cookie = 'siteLang=' + lang + '; expires='+a.toGMTString()+'; path=/;';
}

/**
 * make ajax-call for main-content
 * @param pageId {Number} pageId to open
 */
function loadContent(pageId)
{
	if (pageId == actualPageId) {
		return;
	}
    actualPageId = pageId;
	//var urlContent = pageBaseUrl + '/content/' + currentLanguage +  '/' + pageId;
	var urlContent = pageBaseUrl + pageId + '/content.html';
    ajaxContentCall.url = urlContent;
    ajaxContentCall.request();
}

function loadRecommendation()
{
	currentPageIsRecommendationForm = true;
	var urlContent = pageBaseUrl + '/' + currentLanguage +  '/recommend/content.php?content=' + actualPageId;
	ajaxContentCall.url = urlContent;
	ajaxContentCall.request();
}


/**
 *
 */
function loadExtendedContent()
{
	pageId = '-';

	if ( $('extendedContent') )
	{
		pageId = $('extendedContent').innerHTML;
	}

	if (currentPageIsRecommendationForm) return;

	switch (pageId)
	{
		//Kontakt
		case 'meta/contact':
			accordionContact();
			break;
		//PressOverview
		case 'press/releases':
		case 'aktuelles/news':
			accordionPressOverviewFunc();
			break;
		//JobsOverview
		case 'jobs/vacancies':
			accordionJobsOverviewFunc();
			break;
		case 'home':

			var flashvars = {
				xmlData: escape(pageBaseUrl + actualPageId + '/gallery.xml')
			};

			var params = {
			    quality: 'best',
			    allowscriptaccess: 'always',
			    wmode: "transparent"
			};

			var attributes = {
			    name: 'flashGallery',
			    id: 'flashGallery'
			    //xmlData: pageBaseUrl + '/homegallery.php?lang=' + currentLanguage
			};

			if (swfobject.hasFlashPlayerVersion('8.0.0'))
			{
				(function(){swfobject.embedSWF(pageBaseUrl + "/assets/media/swf/gallery.swf", "homeFlash", "550", "350", "8.0.0", null, flashvars, params, attributes);}).delay(200);
			}
			else
			{
				$('homeFlash').addClass('flashReplacement');
			}
			homeTeasers();
			break;

		case 'projects/details':

			accordionProjectDetailsFunc();

			var flashvars = {
				xml: pageBaseUrl + actualPageId + '/gallery.xml'
			};


			if( isIE )
			{
				var params = {
				    quality: 'best',
				    allowscriptaccess: 'always',
				    allowfullscreen: true,
				    wmode: "transparent"
				};
			} else {
				var params = {
				    quality: 'best',
				    allowscriptaccess: 'always',
				    allowfullscreen: true
				};
			}

			var attributes = {
			    name: 'flashVideoPlayer',
			    id: 'flashVideoPlayer'
			};

			if (swfobject.hasFlashPlayerVersion('8.0.0'))
			{
				var swfHeight = 322;

				if($('videoHeight') !== null) {
					swfHeight = Number($('videoHeight').innerHTML);
					if(swfHeight >= 390)
						swfHeight = 447;
				}

				(function(){swfobject.embedSWF(pageBaseUrl + "/assets/media/swf/videoplayer.swf", "projectDetailsMediaFlash", "574", (swfHeight)+19, "8.0.0", null, flashvars, params, attributes);}).delay(200);
			}
			else
			{
				$('projectDetailsMediaFlash').addClass('flashReplacement');
			}


			break;

		case '_textimage/slideshow':
			accordionProjectDetailsFunc();

			var flashvars = {
				xml: pageBaseUrl + actualPageId + '/gallery.xml'
			};


			if( isIE )
			{
				var params = {
				    quality: 'best',
				    allowscriptaccess: 'always',
				    allowfullscreen: true,
				    wmode: "transparent"
				};
			} else {
				var params = {
				    quality: 'best',
				    allowscriptaccess: 'always',
				    allowfullscreen: true
				};
			}

			var attributes = {
			    name: 'flashVideoPlayer',
			    id: 'flashVideoPlayer'
			};

			if (swfobject.hasFlashPlayerVersion('8.0.0'))
			{
				(function(){swfobject.embedSWF(pageBaseUrl + "/assets/media/swf/videoplayer.swf", "projectDetailsMediaFlash", "574", "343", "8.0.0", null, flashvars, params, attributes);}).delay(200);
			}
			else
			{
				$('projectDetailsMediaFlash').addClass('flashReplacement');
			}


			break;
	}
}


/**
 *
 */
function unloadExtendedContent()
{
	pageId = '-';
	if ( $('extendedContent') )
	{
		pageId = $('extendedContent').innerHTML;
	}
	switch (pageId)
	{
		case 'jobs/vacancies':
			// if Application-Form is open, close before switch to another page
			if ( currentJobApplicationId != 0 )
			{
				formSpecApp.closeForm();
			}
			break;
		default:
			break;
	}
}


/**
 * handle the ajax response for the main content
 * @param response {Object} ajax
 */
function ajaxContentSuccess(response)
{
	$('ajaxContent').innerHTML = response;

	sendTagByPageTrackingTag.delay(200);

	loadExtendedContent.delay(200);
}

function sendTagByPageTrackingTag()
{
	if ( $('trackingTag') )
	{
		sendtag($('trackingTag').innerHTML);
	}
}


/**
 * handles the content sliding
 * @param toState {String} status to change ('navIn', 'navOut')
 */
function slide(toState)
{
	$clear( cDelay1 );
	$clear( cDelay2 );
	navigatonSlideState = toState;
	var finalValueNav = (toState == 'navIn') ?  -375 : 0;
	var finalValueTag = (toState == 'navIn') ?  41 : 416;
	var del			= (toState == 'navIn') ? 0 : durationSlideIn;
	if( $('projectDetailsMedia') )
	{
		var finalValueProjDet	= (toState == 'navIn') ?  40 : 416;
		if( isIE )
		{
			cDelay1 = (function ()
			{
				$('projectDetailsMedia').setStyle( 'left', finalValueProjDet );
			}).delay(del);
		} else {
			flashSlide = new Fx.Style('projectDetailsMedia', 'left', {duration: durationSlideOut, wait:false, transition: transitionSlideOut});
			flashSlideIn = new Fx.Style('projectDetailsMedia', 'left', {duration: durationSlideIn, wait:false, transition: transitionSlideIn});
			if( toState == 'navIn' )
			{
				flashSlideIn.start( finalValueProjDet );
			} else {
				flashSlide.start( finalValueProjDet );
			}
		}
	}
	var displayType = (toState == 'navIn') ? 'block' : 'none';
	$('navigationOpener').setStyle('display', displayType)

	if( toState == 'navIn' )
	{
		instantFlashAction( "pause", durationSlideIn );
		navSlideIn.start(finalValueNav);
		if( !isIE )
		{
			contentSlideIn.start( finalValueTag );
		}
	} else {
		instantFlashAction( "pause", durationSlideOut );
		navSlide.start(finalValueNav);
		if( !isIE )
		{
			contentSlide.start( finalValueTag );
		}
	}

	if( isIE )
	{
		cDelay2 = (function ()
		{
			$('ajaxContent').setStyle( 'margin-left', finalValueTag );
		}).delay(del);
	}
}


/**
 * HistoryKeeperFunction
 */
function HistoryKeeperFunc()
{
	var displayDiv = document.getElementById("historyContent");

	// the sole public method to manipulate this application
	this.addHistory = function(value)
	{
		unFocus.History.addHistory(value);
		return false;
	};

	// This is the method that will recieve notifications from the History Keeper,
	// which will then update the state of the app.
	// :NOTE: This will be called when a new entry is added.
	// :NOTE: This will be called if another app on the page sets a history,
	//        so you will need to watch out for this, if you have more than
	//        one script using the history keeper, by doing some kind of
	//        check to make sure that the new hash belongs to this app.
	//        I wouldn't expect this to be a problem all that frequently.
	this.historyListener = function (historyHash, init)
	{
		// hack for initial startup
		if(initialStartupId != -1 && historyHash == '' && init == 'init')
		{
			historyHash = initialStartupId;
			initialStartupId = -1;
		}
		// update display content
		displayDiv.innerHTML = historyHash + "<br />" + displayDiv.innerHTML;
		// update the page
		openPageAlias(historyHash,undefined,_keepTagcloud);
	};

	// subscribe to unFocus.History
	unFocus.History.addEventListener('historyChange', this.historyListener);

	// Check for an initial value (deep link).
	// In this demo app, the historyListener can handle the task.
	this.historyListener(unFocus.History.getCurrent(), 'init');
};


function homeTeasers()
{
	var teasersLeft = new Array();
	var teasersRight = new Array();

	$('groupHomeTeaser').getElements('.teaserLeft').each( function (teaser)
	{
		teasersLeft.push(teaser.innerHTML);
	});
	$('groupHomeTeaser').getElements('.teaserRight').each( function (teaser)
	{
		teasersRight.push(teaser.innerHTML);
	});

	$('groupHomeTeaser').innerHTML = '';

	if (teasersLeft.length > 0)
	{
		$('groupHomeTeaser').innerHTML += teasersLeft[Math.round(Math.random()*(teasersLeft.length-1))];
	}

	if (teasersRight.length > 0)
	{
		$('groupHomeTeaser').innerHTML += teasersRight[Math.round(Math.random()*(teasersRight.length-1))];
	}
}


/* swf embedding */
var tagCloudlang = currentLanguage;
if (tagCloudlang == 'zh' || tagCloudlang == 'tw')
{
	tagCloudlang = 'cn';
}
var flashvars = {
    lang: tagCloudlang
};
var params = {
    allowscriptaccess: 'always'
};
var attributes = {
    name: 'flashNavigation',
    id: 'flashNavigation',
    quality: 'best',
    bgcolor: '#ca0511'
};

if (swfobject.hasFlashPlayerVersion('8.0.0'))
{
	(function(){swfobject.embedSWF(pageBaseUrl + "/assets/media/swf/tagcloud.swf", "flashTagcloud", "350", "100%", "8.0.0", null, flashvars, params, attributes);}).delay(1000);
}
else
{
	//$('flashTagcloud').addClass('flashReplacement');
}



var Sorting = new Class
({
    initialize: function()
	{
		$('sort').setStyle('opacity', 0);
		$('sort').setStyle('visibility', 'hidden');
		this.sortSlide = new Fx.Style('sortList', 'height', {duration:200, wait:false, onComplete: function() { scaleTagcloud(); } });
		this.sortOpacity = new Fx.Style('sort', 'opacity', {duration:0, wait:false});
		this.sortHeight = $('sortList').getSize().size.y;
		$('sortList').setStyle('height', 0);
		this.state = 'in';

		$('sortAfter').onclick = this.handleToggle.bind(this);
		$('sortAfter').onmouseover = this.handleToggleOpen.bind(this);
		$('sortAfter').onmouseout = this.handleToggleClose.bind(this);
		$('sortAfterImg').onclick = this.handleToggle.bind(this);
		$('sortAfterImg').onmouseover = this.handleToggleOpen.bind(this);
		$('sortAfterImg').onmouseout = this.handleToggleClose.bind(this);

		$('sortList').onmouseover = this.handleToggleOpen.bind(this);
		$('sortList').onmouseout = this.handleToggleClose.bind(this);
		this.registerClicks();
    },
	registerClicks: function()
	{
		$('sortList').getElements('a').each(function(link)
		{
			link.onclick = function(scope)
			{
				this.handleToggle('in');
				var pageId = scope.getProperty('rel');
				$('sortList').getElements('.current').each( function(activeLink)
				{
					activeLink.removeClass('current');
				});
				scope.setProperty('class', 'current');
				if (pageId != actualPageId)
				{
					openPage(pageId);
				}
			}.bind(this).pass(link);
		}.bind(this));
	},
	handleToggle: function(newState)
	{
		if (newState == 'in' || this.state == 'out')
		{
			this.foldIn();

		}
		else
		{
			this.foldOut();
		}
	},
	handleToggleOpen: function(newState)
	{
		$clear(sortFoldInDelay);
		this.sortSlide.stop();
		this.foldOut();
	},
	handleToggleClose: function(newState)
	{
		sortFoldInDelay = (function(){this.foldIn()}).bind(this).delay(750);
	},
	setNewOptions: function(sorting)
	{
		this.state = 'in';
        this.sortSlide.stop();
        $('sortList').setStyle('height', 0);
		$('sortList').empty();
		sorting.each( function(tagCloudElement)
		{
			var listElement = new Element('li').injectInside('sortList');
			var link = new Element('a', {
				//'href': pageBaseUrl + tagCloudElement.sortId + '/index.html',
				'href': 'javascript:;',
				'rel': tagCloudElement.sortId,
				'class': ( tagCloudElement.active == true ) ? 'current' : 'empty'
			}).injectInside(listElement).setHTML(tagCloudElement.title);
		});
		//this.sortHeight = sorting.length * 26;
		this.sortHeight = sorting.length * 32; // fix for zh!
		this.registerClicks();
		this.sortOpacity.start(100);
	},
	foldIn: function()
	{
		this.state = 'in';
		this.sortSlide.start(0);
	},
	foldOut: function()
	{
		this.state = 'out';
		this.sortSlide.start(this.sortHeight);
	},
	reset: function()
	{
	   this.foldIn();
	   this.sortOpacity.start(0);
	}
});



/* --------------------------------------- */
/* FORM HANDLING */
/* --------------------------------------- */

/**
 * Speculative Application
 */
var FormSpeculativeApplication = new Class
({
    initialize: function()
	{
		this.fields = Array(	'position', 'location', 'desiredsalary', 'dateday', 'datemonth', 'dateyear', 'curriculumvitae', 'coverletter',
								'salutation', 'title', 'firstname', 'lastname',
								'street', 'housenr', 'zip', 'city', 'region', 'country',
								'phoneprivate', 'phonemobile', 'email', 'emailrepeat',
								'commentary' );
	},
	openForm: function(position, location, dbId)
	{
		if(currentJobApplicationId != dbId)
		{
			this.resetFields();
			currentJobApplicationId = dbId;
			$('jobsContentSpeculativeApplicationFormSuccessMessage').setHTML('');
			$('jobsContentAccordionFormularContent_'+dbId).setHTML( $('jobsContentSpeculativeApplicationForm').innerHTML );
			$('jobsContentSpeculativeApplicationForm').setHTML('');
			$('position').value = position;
			$('location').value = location;
			$('jobsContentOpenForm_'+dbId).setStyle('display', 'none');
			$('jobsContentCloseForm_'+dbId).setStyle('display', 'block');
		}
	},
	closeForm: function(dbId)
	{
		if (dbId != undefined && dbId != null)
		{
			if ( (currentJobApplicationId != dbId) || (currentJobApplicationId != 0) )
			{
				$('jobsContentSpeculativeApplicationForm').setHTML( $('jobsContentAccordionFormularContent_'+dbId).innerHTML );
				$('jobsContentAccordionFormularContent_'+dbId).setHTML('');
				$('jobsContentOpenForm_'+dbId).setStyle('display', 'block');
				$('jobsContentCloseForm_'+dbId).setStyle('display', 'none');
			}
		}
		else if (currentJobApplicationId != 0)
		{
			$('jobsContentSpeculativeApplicationForm').setHTML( $('jobsContentAccordionFormularContent_'+currentJobApplicationId).innerHTML );
			$('jobsContentAccordionFormularContent_'+currentJobApplicationId).setHTML('');
			$('jobsContentOpenForm_'+currentJobApplicationId).setStyle('display', 'block');
			$('jobsContentCloseForm_'+currentJobApplicationId).setStyle('display', 'none');
		}
		currentJobApplicationId = 0;
	},
	toggleFormSpeculativeApplication: function(toggleState)
	{
		if(toggleState == true)
		{
			this.resetForm();
			$('jobsContentSpeculativeApplicationToggleTrue').setStyle('display', 'none');
			$('jobsContentSpeculativeApplicationForm').setStyle('display', 'block');
			$('jobsContentSpeculativeApplicationFormSuccess').setStyle('display', 'none');
			$('jobsContentSpeculativeApplicationFormSuccessMessage').setHTML('');
		}
		else
		{
			$('jobsContentSpeculativeApplicationToggleTrue').setStyle('display', 'block');
			$('jobsContentSpeculativeApplicationForm').setStyle('display', 'none');
		}
	},
	openDataprotection: function ()
	{
		if( $('formDataprotection') )
		{
			$('formDataprotection').setStyle('display', 'block');
		}
	},
	closeDataprotection: function ()
	{
		if( $('formDataprotection') )
		{
			$('formDataprotection').setStyle('display', 'none');
		}
	},
	submitForm: function(formCheckValues)
	{
		this.resetForm();
		var myFormCheckValues = Json.evaluate(formCheckValues);
		//error
		if(myFormCheckValues.errorState == 1)
		{
			$('formError').setHTML(myFormCheckValues.error);
			myFormCheckValues.fields.each(function(value)
			{
				if(value != 'datemonth' && value != 'dateyear')
				{
					$('label_'+value).setStyle('color', '#CA0511');
				}
				//$(value).setStyle('border', '1px solid #CA0511');
			});
			$('formError').setStyle('color', '#CA0511');
		}
		//success
		else
		{
			if($('jobsContentSpeculativeApplicationP')) 			$('jobsContentSpeculativeApplicationP').setStyle('display', 'none');
			if($('jobsContentSpeculativeApplication')) 				$('jobsContentSpeculativeApplication').setStyle('display', 'none');
			if($('jobsContentApplication')) 						$('jobsContentApplication').setStyle('display', 'none');

			if($('jobsContentSpeculativeApplicationForm'))			$('jobsContentSpeculativeApplicationForm').setStyle('display', 'none');
			if($('jobsContentSpeculativeApplicationFormSuccess'))	$('jobsContentSpeculativeApplicationFormSuccess').setStyle('display', 'inline');

			$('jobsContentSpeculativeApplicationFormSuccessMessage').setHTML(myFormCheckValues.error);
			this.resetFields();
		}
	},
	resetForm: function()
	{
		this.fields.each( function(value) {
			if(value != 'datemonth' && value != 'dateyear' && value != 'birthdaymonth' && value != 'birthdayyear' && $('label_'+value))
			{
				$('label_'+value).setStyle('color', '#000000');
			}
			//if($(value)) $(value).setStyle('border', '1px solid #535353');
			$('formError').setStyle('color', '#000000');
		});
	},
	resetFields: function()
	{
		if($('jobsContentSpeculativeApplicationFormForm'))
		{
			$('jobsContentSpeculativeApplicationFormForm').reset();
		}
	}
});



/**
 * Contact Form
 */
var FormContact = new Class
({
    initialize: function()
	{
		this.fields = Array(	'summary', 'livetrends', 'references',
								'salutation', 'title', 'firstname', 'lastname',
								'firm', 'function',
								'street', 'housenr', 'zip', 'city', 'country',
								'phoneprivate', 'email',
								'commentary' );
	},
	submitForm: function(formCheckValues)
	{
		this.resetForm();
		var myFormCheckValues = Json.evaluate(formCheckValues);
		//error
		if(myFormCheckValues.errorState == 1)
		{
			$('formError').setHTML(myFormCheckValues.error);
			myFormCheckValues.fields.each(function(value)
			{
				if(value=='salutation')
				{
					$('label_'+value+'_mr').setStyle('color', '#CA0511');
					$('label_'+value+'_mrs').setStyle('color', '#CA0511');
				}
				else
				{
					if($('label_'+value)) $('label_'+value).setStyle('color', '#CA0511');
				}
				//$(value).setStyle('border', '1px solid #CA0511');
			});
			$('formError').setStyle('color', '#CA0511');
		}
		//success
		else
		{
			$('metaContactContentAccordionContentWrapper').setStyle('display', 'none');
			$('pressContentLiveCommunicationNewsFormSuccess').setStyle('display', 'inline');
			$('pressContentLiveCommunicationNewsFormSuccessMessage').setHTML(myFormCheckValues.error);
			var elemH = $('pressContentLiveCommunicationNewsFormSuccessMessage').getSize().size.y;
			$('metaContactContentAccordionContentContact').setStyle('height', elemH+50);
			this.resetFields();
		}
	},
	resetForm: function()
	{
		this.fields.each( function(value)
		{
			if(value=='salutation')
			{
				$('label_'+value+'_mr').setStyle('color', '#000000');
				$('label_'+value+'_mrs').setStyle('color', '#000000');
			}
			else
			{
				if($('label_'+value)) $('label_'+value).setStyle('color', '#000000');
			}
			//$(value).setStyle('border', '1px solid #535353');
			//$(value).setStyle('border', '');
			$('formError').setStyle('color', '#000000');
		});
	},
	resetFields: function()
	{
		$('metaContactContentAccordionContentFormForm').reset();
	}
});



/**
 * Recommendation form
 */
var FormRecommendation = new Class
({
    initialize: function()
	{
		this.fields = Array(	'name_sender', 'name_recipient', 'email_sender', 'email_recipient'    );
	},
	submitForm: function(formCheckValues)
	{
		this.resetForm();
		var myFormCheckValues = Json.evaluate(formCheckValues);
		//error
		if(myFormCheckValues.errorState == 1)
		{
			$('formError').setHTML(myFormCheckValues.error);
			myFormCheckValues.fields.each(function(value)
			{
				if($('label_'+value)) $('label_'+value).setStyle('color', '#CA0511');
				//$(value).setStyle('border', '1px solid #CA0511');
			});
			$('formError').setStyle('color', '#CA0511');
		}
		//success
		else
		{
			this.resetFields();
			$('metaRecommendationContentP').setStyle('display', 'none');
//			$('metaRecommendationForm').setStyle('display', 'none');
			$('metaRecommendationFormSuccess').setStyle('display', 'inline');
			$('metaRecommendationFormSuccessMessage').setHTML(myFormCheckValues.error);
		}
	},
	resetForm: function()
	{
		this.fields.each( function(value)
		{
			if($('label_'+value)) $('label_'+value).setStyle('color', '#000000');
			//$(value).setStyle('border', '1px solid #535353');
			$('formError').setStyle('color', '#000000');
		});
	},
	resetFields: function()
	{
		$('metaRecommendationFormForm').reset();
	}
});


/**
 * Live Communication News
 */
var FormLiveCommunicationNews = new Class
({
    initialize: function()
	{
		this.fields = Array(	'salutation', 'title', 'firstname', 'lastname',
								'position', 'verlag', 'medium',
								'street', 'housenr', 'zip', 'city', 'region', 'country',
								'phoneprivate', 'email',
								'commentary' );
	},
	toggleFormSpeculativeApplication: function(toggleState)
	{
		if(toggleState == true)
		{
			this.resetForm();
			$('pressContentLiveCommunicationNewsForm').setStyle('display', 'inline');
			$('pressContentLiveCommunicationNewsFormSuccess').setStyle('display', 'none');
			$('pressContentLiveCommunicationNewsFormSuccessMessage').setHTML('');
		}
		else
		{
			$('pressContentLiveCommunicationNewsForm').setStyle('display', 'none');
		}
	},
	submitForm: function(formCheckValues)
	{
		this.resetForm();
		var myFormCheckValues = Json.evaluate(formCheckValues);
		//error
		if(myFormCheckValues.errorState == 1)
		{
			$('formError').setHTML(myFormCheckValues.error);
			myFormCheckValues.fields.each(function(value) {
				if(value=='salutation')
				{
					$('label_'+value+'_mr').setStyle('color', '#CA0511');
					$('label_'+value+'_mrs').setStyle('color', '#CA0511');
				}
				else
				{
					if($('label_'+value)) $('label_'+value).setStyle('color', '#CA0511');
				}
				//if($(value)) $(value).setStyle('border', '1px solid #CA0511');
			});
			$('formError').setStyle('color', '#CA0511');
		}
		//success
		else
		{
			$('pressContentLiveCommunicationNewsP').setStyle('display', 'none');
			$('pressContentLiveCommunicationNewsForm').setStyle('display', 'none');
			$('pressContentLiveCommunicationNewsFormSuccess').setStyle('display', 'inline');
			$('pressContentLiveCommunicationNewsFormSuccessMessage').setHTML(myFormCheckValues.error);
			this.resetFields();
		}
	},
	resetForm: function()
	{
		this.fields.each( function(value) {
			if(value=='salutation')
			{
				$('label_'+value+'_mr').setStyle('color', '#000000');
				$('label_'+value+'_mrs').setStyle('color', '#000000');
			}
			else
			{
				if($('label_'+value)) $('label_'+value).setStyle('color', '#000000');
			}
			//if($(value)) $(value).setStyle('border', '1px solid #535353');
			$('formError').setStyle('color', '#000000');
		});
	},
	resetFields: function()
	{
		$('pressContentLiveCommunicationNewsFormForm').reset();
	}
});






/**
 * Live Communication News
 */
var FormNewsletter = new Class
({
    initialize: function()
	{
		this.fields = Array( 'salutation', 'title', 'firm', 'firstname', 'lastname', 'email' );
	},
	toggleFormSpeculativeApplication: function(toggleState)
	{
		if(toggleState == true)
		{
			this.resetForm();
			$('pressContentNewsletterForm').setStyle('display', 'inline');
			$('pressContentNewsletterFormSuccess').setStyle('display', 'none');
			$('pressContentNewsletterFormSuccessMessage').setHTML('');
		}
		else
		{
			$('pressContentNewsletterForm').setStyle('display', 'none');
		}
	},
	submitForm: function(formCheckValues)
	{
		this.resetForm();
		var myFormCheckValues = Json.evaluate(formCheckValues);
		//error
		if(myFormCheckValues.errorState == 1)
		{
			$('formError').setHTML(myFormCheckValues.error);
			myFormCheckValues.fields.each(function(value) {
				if(value=='salutation')
				{
					$('label_'+value+'_mr').setStyle('color', '#CA0511');
					$('label_'+value+'_mrs').setStyle('color', '#CA0511');
				}
				else
				{
					if($('label_'+value)) $('label_'+value).setStyle('color', '#CA0511');
				}
				//if($(value)) $(value).setStyle('border', '1px solid #CA0511');
			});
			$('formError').setStyle('color', '#CA0511');
		}
		//success
		else
		{
			$('pressContentNewsletterP').setStyle('display', 'none');
			//$('pressContentNewsletterForm').setStyle('display', 'none');
			$('pressContentNewsletterFormSuccess').setStyle('display', 'inline');
			$('pressContentNewsletterFormSuccessMessage').setHTML(myFormCheckValues.error);
			this.resetFields();
		}
	},
	resetForm: function()
	{
		this.fields.each( function(value) {
			if(value=='salutation')
			{
				$('label_'+value+'_mr').setStyle('color', '#000000');
				$('label_'+value+'_mrs').setStyle('color', '#000000');
			}
			else
			{
				if($('label_'+value)) $('label_'+value).setStyle('color', '#000000');
			}
			//if($(value)) $(value).setStyle('border', '1px solid #535353');
			$('formError').setStyle('color', '#000000');
		});
	},
	resetFields: function()
	{
		$('pressContentNewsletterFormForm').reset();
	}
});









/**
 * Press Accordion
 */
var accordionPressOverviewElement = new Class
({
    initialize: function ()
	{
	},

	expandPressContentCopyItem: function (elementId)
	{
		pressScrollOldPosition = elementId;

		this.collapsePressContentCopyItem(false);
		$('pressContentCopyItemExpand_'+elementId).setStyle('display', 'block');
		$('pressContentCopyItemMore_'+elementId).setStyle('display', 'none');

		var scrollFX = new Fx.Scroll('content', {
			wait: false,
			duration: 100
		});
		scrollFX.toElement(pressScrollOldPosition);
	},

	collapsePressContentCopyItem: function (scroll)
	{
		if (scroll == true || typeof scroll == 'undefined')
		{
			var scrollFX = new Fx.Scroll('content', {
				wait: false,
				duration: 100
			});
			scrollFX.toElement(pressScrollOldPosition);
		}
		$$('.pressContentCopyItemMore').each( function (elem) {
			elem.setStyle('display', 'inline');
		});
		$$('.pressContentCopyItemExpand').each( function (elem) {
			elem.setStyle('display', 'none');
		});
	}
});


/**
 * ProjectDetails Accordion
 */
var accordionProjectDetailsElement = new Class
({
    initialize: function ()
	{
	},
	expandItem: function ()
	{
		$('projectDetailsCopyItemMore').setStyle('display', 'none');
		$('projectDetailsCopyItemExpand').setStyle('display', 'block');
	},
	collapseItem: function ()
	{
		$('projectDetailsCopyItemMore').setStyle('display', 'block');
		$('projectDetailsCopyItemExpand').setStyle('display', 'none');
	}
});


/**
 * JobsOverview Accordion
 */
var accordionJobsOverviewElement = new Class
({
    initialize: function ()
	{
	},
	expandItem: function (elementId)
	{
		this.collapseItem();
		$('jobsContentAccordionHeadContent_'+elementId).setStyle('display', 'none');
		$('jobsContentAccordionHeadCloser_'+elementId).setStyle('display', 'block');
		$('jobsContentAccordionContent_'+elementId).setStyle('display', 'block');
	},
	collapseItem: function ()
	{
		$$('.jobsContentAccordionHeadContent').each( function (elem) {
			elem.setStyle('display', 'block');
		});
		$$('.jobsContentAccordionHeadCloser').each( function (elem) {
			elem.setStyle('display', 'none');
		});
		$$('.jobsContentAccordionContent').each( function (elem) {
			elem.setStyle('display', 'none');
		});
		formSpecApp.closeForm();
	}
});



/* --------------------------------------- */
/* ACCORDION FUNCTIONS */
/* --------------------------------------- */

/**
 *
 */
function accordionContact()
{
	var accordion = new Accordion (
		'div.metaContactContentAccordionHead',
		'div.metaContactContentAccordionContent',
		{
			display: -1,
			alwaysHide: true,
			opacity: true,
			duration: 0,
			onActive: function (toggler, element)
			{
				var childs = toggler.getChildren();
				childs[1].setStyle('display', 'none');
				childs[2].setStyle('display', 'inline');
			},
			onBackground: function (toggler, element)
			{
				var childs = toggler.getChildren();
				childs[1].setStyle('display', 'inline');
				childs[2].setStyle('display', 'none');
			}
		},
		$('metaContactContentAccordion')
	);
	$('metaContactContentAccordionContentWrapper').setStyle('visibility', 'visible');
}


/**
 *
 */
function accordionPressOverviewFunc()
{
	accordionPressOverview = new accordionPressOverviewElement();
}


/**
 *
 */
function accordionJobsOverviewFunc()
{
	accordionJobsOverview = new accordionJobsOverviewElement();
}


/**
 *
 */
function accordionProjectDetailsFunc()
{
    //contentProjectDetailsSlide = new Fx.Style('projectDetailsMedia', 'left', {duration:durationSlideOut, wait:false, transition: transitionSlideOut});
    //contentProjectDetailsSlideIn = new Fx.Style('projectDetailsMedia', 'left', {duration:durationSlideIn, wait:false, transition: transitionSlideIn});
    if(navigatonSlideState == 'navIn')
    {
    	$('projectDetailsMedia').setStyle('left', 40);
    }
    else if(navigatonSlideState == 'navOut' || navigatonSlideState == undefined)
    {
    	$('projectDetailsMedia').setStyle('left', 416);
    }
    projectDetails = new projectDetailsClass();
	accordionContentDetails = new accordionProjectDetailsElement();
}


/**
 *
 */
function openPrinter(url)
{
	var printWindow = window.open(url, "UNIPLAN Print", "width=800,height=500,scrollbars=yes");
	printWindow.focus();

	if (!printWindow)
	{
		return true;
	}
	return false;
}


function focusHTML()
{
	self.focus();
}


/* --------------------------------------- */
/* COMMON FUNCTIONS */
/* --------------------------------------- */

/**
 * projectDetails
 */
var projectDetailsClass = new Class
({
    initialize: function ()
	{
	},
	setFullscreenMode: function ()
	{
		if(window.ie6 == true) { alert("This function is not supported in Internet Explorer 6."); }
		else
		{
			$('projectDetailsMedia').setStyles({
				width: window.getSize().size.x,
				height: window.getSize().size.y,
				top: 0,
				left: 0
			});
		}
	},
	setStandardMode: function ()
	{
		if(window.ie6 == true) { alert("This function is not supported in Internet Explorer 6."); }
		else
		{
			$('projectDetailsMedia').setStyles({
				width: 573,
				height: 491,
				top: 100,
				left: 40
			});
		}
	}
});
