function initMediathek(){
	myMediaplayer = new Mediaplayer(BASE_URL + '/incl/mediaplayer.swf', '480', '362', L10N_tags, BASE_URL + '/media_files/', '0xececec', BASE_URL);							
	myMediaplayer.changeMedia('','','','','init_mediaplayer.gif','photo',true,false);
	
	serviceUrl = BASE_URL + '/incl/mediathek/mediathek.service.php?language=' + LANGUAGE;
	//currentPlaylist;
	objectIndex = 0;
	
	languageSwitchLinkElement = $('languageswitch');

	myLytebox = new LyteBox(BASE_URL); 
	myLytebox.setLanguage(LANGUAGE);
	
	new Ajax.Request(serviceUrl + '&command=allPlaylists', 
		{
			method: 'get',
			onSuccess: function(response) {
				var result = response.responseXML;
				var playlistNodes = result.getElementsByTagName("document")[0].childNodes;
				fillPlaylists(playlistNodes);
				if (INITIAL_SEARCH_TERM || INITIAL_SEARCH_FORMAT || INITIAL_SEARCH_INTERVAL){
					performSearch(INITIAL_OBJECT_INDEX);
				} else {
					loadPlaylist(INITIAL_PLAYLIST_ID, INITIAL_OBJECT_INDEX, false);
				}
			}
		}
	);
}

function performSearch(displayObjectIndex){
	var form = $('sucheMediathek');
	
	var sortValue = "";
	if (encodeURIComponent($F(form['formSortierungDate'])) != "null") {
		sortValue = encodeURIComponent($F(form['formSortierungDate']));
	} else if (encodeURIComponent($F(form['formSortierungUsage'])) != "null") {
		sortValue = encodeURIComponent($F(form['formSortierungUsage']));
	}	
	var formatValue = encodeURIComponent($F(form['format']));				// Format
	var intervalValue = encodeURIComponent($F(form['interval']));			// Zeitraum
	var termValue = encodeURIComponent($F(form['term']));					// Suchbegriff
	var searchParameter = '&sortorder='+sortValue+'&format='+formatValue+'&interval='+intervalValue+'&term=' + termValue;

	new Ajax.Request(serviceUrl + '&command=search' + searchParameter, 
		{
			method: 'get',
			onSuccess: function(response) {
				var result = response.responseXML;
				var objectsNode = result.getElementsByTagName("document")[0].firstChild;
				if(objectsNode.childNodes.length > 0){
					currentPlaylist = new Playlist(objectsNode, true);
					currentPlaylist.setSearchParameter(searchParameter);
					removeHighlightFromChildren($('playlists'));
					updateDiashow();
					updateObjectList();
					playObject(displayObjectIndex, false);
				} else {
					var notice = $('notice');
					notice.update('<h2>' + L10N_keine_suchergebnisse + '</h2>');
					notice.show();
				}
			}
		}
	);
}

function createPagination(paginationContainer){
	if(currentPlaylist.hasMultiplePages()){
		removeChildren(paginationContainer);
		
		
		var pagesElement = new Element('p').addClassName('pages');
		pagesElement.update(
			L10N_pagination_page + ' ' + 
			currentPlaylist.currentPage + 
			' ' + L10N_pagination_of + ' ' + 
			currentPlaylist.pages.length);
		paginationContainer.appendChild(pagesElement);
		
		var pageNavElement = new Element('div').addClassName('pagenav');

		if(currentPlaylist.hasPreviousPage()){
			pageNavElement.insert('<a href="javascript:currentPlaylist.firstPage();updateObjectList();"><img src="' + BASE_URL + '/images/arrow_grey_to_first.gif" border="0" width="14" height="15" alt="' + L10N_button_first + '"></a>');								
			pageNavElement.insert('<a href="javascript:currentPlaylist.previousPage();updateObjectList();"><img src="' + BASE_URL + '/images/arrow_grey_left.gif" border="0" width="14" height="15" alt="' + L10N_button_previous + '"></a>');								
		} else {
			pageNavElement.insert('<span><img src="' + BASE_URL + '/images/arrow_grey_to_first_inactive.gif" border="0" width="14" height="15" alt="' + L10N_button_first + '"></span>');								
			pageNavElement.insert('<span><img src="' + BASE_URL + '/images/arrow_grey_left_inactive.gif" border="0" width="14" height="15" alt="' + L10N_button_previous + '"></span>');								
		}

		
		var pageNavCount = 7; 
		var pagesStart = currentPlaylist.currentPage - Math.floor(pageNavCount / 2);
		var pagesEnd = currentPlaylist.currentPage + Math.floor(pageNavCount / 2);
		
		if(pagesStart < 1){
			pagesStart = 1;
			pagesEnd = Math.min(pageNavCount, currentPlaylist.pages.length);
		}
		
		if(pagesEnd > currentPlaylist.pages.length){
			pagesStart = Math.max(currentPlaylist.pages.length - pageNavCount + 1, 1); //
			pagesEnd = currentPlaylist.pages.length;
		}
		
		if (pagesStart > 1){
			pageNavElement.insert('<span>&hellip;</span>');
		}
		for(idx = pagesStart; idx <= pagesEnd; idx++){
			var pageLink = new Element('a').addClassName('page').update(idx);
			pageLink.setAttribute('href', 'javascript:switchToPage('+idx+');');
			if (idx == currentPlaylist.currentPage){
				pageLink.addClassName('active');
			}
			pageNavElement.appendChild(pageLink);
		}
		
		if (pagesEnd < currentPlaylist.pages.length){
			pageNavElement.insert('<span>&hellip;</span>');
		}


		if(currentPlaylist.hasNextPage()){
			pageNavElement.insert('<a href="javascript:currentPlaylist.nextPage();updateObjectList();"><img src="' + BASE_URL + '/images/arrow_grey.gif" border="0" width="14" height="15" alt="' + L10N_button_next + '"></a>');								
			pageNavElement.insert('<a href="javascript:currentPlaylist.lastPage();updateObjectList();"><img src="' + BASE_URL + '/images/arrow_grey_to_last.gif" border="0" width="14" height="15" alt="' + L10N_button_last + '"></a>');								
		} else {
			pageNavElement.insert('<span><img src="' + BASE_URL + '/images/arrow_grey_inactive.gif" border="0" width="14" height="15" alt="' + L10N_button_next + '"></span>');								
			pageNavElement.insert('<span><img src="' + BASE_URL + '/images/arrow_grey_to_last_inactive.gif" border="0" width="14" height="15" alt="' + L10N_button_last + '"></span>');								
		}
									
		paginationContainer.appendChild(pageNavElement);
		paginationContainer.show();
	} else {
		paginationContainer.hide();
	}
}

function updatePagination(){
	$('notice').hide();
	createPagination($('paginationUpper'));
	createPagination($('paginationLower'));
}

function updateObjectList(){
	updatePagination();
	var objectlistContainer = $('objectlist');
	removeChildren(objectlistContainer);

	var objects = currentPlaylist.getObjectsOfCurrentPage();
	var playlistOffset = OBJECTS_PER_PAGE * (currentPlaylist.currentPage - 1);

	for (idx = 0; idx < objects.length; idx++){
		var indexAndPlaylistOffset = idx + playlistOffset;
	
		var divZeile = new Element('div').addClassName('zeile');
		divZeile.setAttribute('id', 'object' + indexAndPlaylistOffset);
		
		var onClickAction = "javascript:playObjectFromList(null, " + indexAndPlaylistOffset + ", true)"; 										
		divZeile.observe('click', playObjectFromList.bindAsEventListener(this, indexAndPlaylistOffset, true));
		//divZeile.setAttribute('onClick', onClickAction);
		
		var divIcon = new Element('div').addClassName('icon');
		
		switch (objects[idx].getAttribute('type')) {
			case "photo":
			case "video":
				
				if (objects[idx].getAttribute('preview')){
					videoPreviewIcon = BASE_URL + '/media_files/' + objects[idx].getAttribute('preview');
				} else {
					videoPreviewIcon = BASE_URL + '/images/icon_flv.gif';
				}

				divIcon.update('<a href="'+onClickAction+'"><img style="background-image:url(' + videoPreviewIcon 
						+ '); background-repeat:no-repeat;z-index:99;"'
						+ ' src="' + BASE_URL + '/images/blank.gif" width="' + IMG_PREVIEW_WIDTH + '" height="75" alt="Vorschau"></a>');
				
				break;
			case "audio":
				divIcon.update('<a href="'+onClickAction+'"><img src="' + BASE_URL + '/images/icon_mp3.gif" width="32" height="32" alt="mp3"></a>');
				break;
			default:
				divIcon.update('');
				break;
		}
		divZeile.appendChild(divIcon);
		
		var divFile = new Element('div').addClassName('file');
		var fileFormat;
		switch (objects[idx].getAttribute('type')) {
			case "photo":
				fileFormat = L10N_format_photo;
				break;
			case "video":
				fileFormat = L10N_format_video;
				break;
			case "audio":
				fileFormat = L10N_format_audio;
				break;
			default:
				fileFormat = '';
				break;
		}
		divFile.update('<a href="'+onClickAction+'">' + fileFormat + '<br>' + objects[idx].getAttribute('size')+ '</a>');
		divZeile.appendChild(divFile);
		
		var divDate = new Element('div').addClassName('date');
		divDate.update('<a href="'+onClickAction+'">' + objects[idx].getAttribute('date') + '</a>');
		divZeile.appendChild(divDate);
		var divDescription = new Element('div').addClassName('description');
		divDescription.update('<h1><a href="'+onClickAction+'">' 
			+ getTextValueFromSubelement(objects[idx], 'teaserTitle') 
			+ '</a></h1><p><a href="'+onClickAction+'">' 
			+ getTextValueFromSubelement(objects[idx], 'teaserDescription') 
			+ '</a></p>');
		divZeile.appendChild(divDescription);
									
		var divAction = new Element('div').addClassName('action');
		divAction.update('<a href="'+onClickAction+'" class="details">' + L10N_objectlist_display_object + '</a>');
		divZeile.appendChild(divAction);
		
		var pClear = new Element('p').addClassName('clear');
		pClear.update('&nbsp;');
		divZeile.appendChild(pClear);
		objectlistContainer.appendChild(divZeile);
		
	}
	//highlight
	if (objectIndex >= playlistOffset && objectIndex < playlistOffset + objects.length){
		highlight($('object' + objectIndex));
	}
}

function playFirstObject(){
	playObject(0, false);
}
function playPreviousObject(){
	playObject(objectIndex - 1, false);
}
function playNextObject(){
	playObject(objectIndex + 1, false);
}
function playLastObject(){
	playObject(currentPlaylist.objectCount - 1, false);
}

function switchToPage(pageNumber){
	currentPlaylist.setCurrentPage(pageNumber);
	updateObjectList();
}

function playObjectFromList(event, index, updateUsage){
	$('metanav').scrollTo();
	playObject(index, updateUsage);
}

function playObject(index, updateUsage){
	$('notice').hide();
	
	if (index < 0){
		objectIndex = 0;
	} else if (index > currentPlaylist.objectCount - 1){
		objectIndex = currentPlaylist.objectCount - 1;
	} else {
		objectIndex = index;
	}
	
	var expectedPage = currentPlaylist.getPageNumberForObjectIndex(objectIndex);
	if (currentPlaylist.currentPage != expectedPage){
		currentPlaylist.setCurrentPage(expectedPage);
		updateObjectList();
	}
	
	var playFirst = $('playFirst');
	var playPrevious = $('playPrevious');
	if(currentPlaylist.hasPreviousPage() || objectIndex > 0){
		Element.replace(playFirst, '<a id="playFirst" class="page left" href="javascript:playFirstObject();"><img src="' + BASE_URL + '/images/arrow_grey_to_first.gif" border="0" alt="' + L10N_button_first + '" width="14" height="15" ></a>');
		Element.replace(playPrevious, '<a id="playPrevious" class="page right" href="javascript:playPreviousObject();"><img src="' + BASE_URL + '/images/arrow_grey_left.gif" border="0" alt="' + L10N_button_previous + '" width="14" height="15" ></a>');
	} else {
		Element.replace(playFirst, '<span id="playFirst" class="page left"><img src="' + BASE_URL + '/images/arrow_grey_to_first_inactive.gif" border="0" alt="' + L10N_button_first + '" width="14" height="15" ></a>');
		Element.replace(playPrevious, '<span id="playPrevious" class="page right"><img src="' + BASE_URL + '/images/arrow_grey_left_inactive.gif" border="0" alt="' + L10N_button_previous + '" width="14" height="15" ></a>');
	}

	var playNext = $('playNext');
	var playLast = $('playLast');
	if(currentPlaylist.hasNextPage() || objectIndex < currentPlaylist.objectCount - 1){
		Element.replace(playNext, '<a id="playNext" class="page left" href="javascript:playNextObject();"><img src="' + BASE_URL + '/images/arrow_grey.gif" border="0" alt="' + L10N_button_next + '" width="14" height="15" ></a>');
		Element.replace(playLast, '<a id="playLast" class="page right" href="javascript:playLastObject();"><img src="' + BASE_URL + '/images/arrow_grey_to_last.gif" border="0" alt="' + L10N_button_last + '" width="14" height="15" ></a>');
	} else {
		Element.replace(playNext, '<span id="playNext" class="page left"><img src="' + BASE_URL + '/images/arrow_grey_inactive.gif" border="0" alt="' + L10N_button_next + '" width="14" height="15" ></a>');
		Element.replace(playLast, '<span id="playLast" class="page right"><img src="' + BASE_URL + '/images/arrow_grey_to_last_inactive.gif" border="0" alt="' + L10N_button_last + '" width="14" height="15" ></a>');
	}
	
	highlight($('object' + objectIndex));
	var object = currentPlaylist.getObject(objectIndex);
	var autoplay = object.getAttribute('type') == 'photo' || object.getAttribute('autoplay') == '1';
	myMediaplayer.changeMedia(
		getTextValueFromSubelement(object, 'title'),
		getTextValueFromSubelement(object, 'subTitle'),
		getTextValueFromSubelement(object, 'description'),
		object.getAttribute('path'),
		object.getAttribute('type'), 
		autoplay,
		updateUsage);
		
	updateDownloadButton(object)
	updateLanguageSwitch();
}

function updateDownloadButton(currentObject){
	var url = null;
	//alert("mid:" + currentObject.getAttribute("hires"));
	if(currentObject.getAttribute("hires") != ""){
		url = currentObject.getAttribute("hires");
	} else if(currentObject.getAttribute("midres") != ""){
		url = currentObject.getAttribute("midres");
	}
	if(url != null){
		$('buttonDownload').show();
		$('anchorDownload').setAttribute('href', url);
	} else {
		$('buttonDownload').hide();
		$('anchorDownload').setAttribute('href', '#');
		
	}
	
}

function updateLanguageSwitch(){
	if (languageSwitchLinkElement){
		var link = languageSwitchLinkElement.readAttribute('href');
		var parameterIndex = link.indexOf('?');
		if (parameterIndex > -1){
			link = link.substring(0, parameterIndex);
		}
		link += '?object=' + objectIndex;
		if(currentPlaylist.isSearchResult){
			link += currentPlaylist.searchParameter;
		} else {
			link += "&playlist=" + currentPlaylist.playlistId;
		} 
		languageSwitchLinkElement.setAttribute('href', link);
	
	}

}

function highlight(element){
	if(element){
		var siblings = element.siblings();
		for (idx = 0; idx < siblings.length; idx++){
			siblings[idx].removeClassName('active');
		}
		element.addClassName('active');
	}
}

function removeHighlightFromChildren(element){
	if(element){
		var children = element.childElements();
		for (idx = 0; idx < children.length; idx++){
			children[idx].removeClassName('active');
		}
	}
}

function getTextValueFromSubelement(element, subElementName){
	var textElement = element.getElementsByTagName(subElementName)[0].firstChild;
	if(textElement != null && textElement.nodeValue != null){
		return textElement.nodeValue;
	}
	return '';
}

function loadPlaylist(playlistId, objectNr, updateUsage){
	highlight($('playlist' + playlistId));
	
	new Ajax.Request(serviceUrl + '&command=playlist&id=' + playlistId, 
		{
			method: 'get',
			onSuccess: function(response) {
				var result = response.responseXML;
				var objectsNode = result.getElementsByTagName("document")[0].firstChild;
				currentPlaylist = new Playlist(objectsNode, false);
				currentPlaylist.setPlaylistId(playlistId);
				updateDiashow();
				updateObjectList();
				playObject(objectNr, false);
			}
		}
	);
}

function updateDiashow(){
	var elementsDiashow = $('elementsDiashow');
	removeChildren(elementsDiashow);
	var diashowLinks = '';
	var diaIndex = 0;
	for (idxPage = 0; idxPage < currentPlaylist.pages.length; idxPage++){
		for (idx = 0; idx < currentPlaylist.pages[idxPage].length; idx++){
			if(currentPlaylist.pages[idxPage][idx].getAttribute('type') == 'photo'){
				diashowLinks += '<a href="' + BASE_URL + '/media_files/'+
					currentPlaylist.pages[idxPage][idx].getAttribute('path')+
					'" id="dia'+diaIndex+
					'" title="'+
					escapeChemicalsHtml(getTextValueFromSubelement(currentPlaylist.pages[idxPage][idx], 'title'))+
					'" rel="lyteshow[playlist]"></a>';
			}
			diaIndex++;								
		}
	}
	elementsDiashow.update(diashowLinks);
	if (diashowLinks != ''){
		$('buttonDiashow').show();
	} else {
		$('buttonDiashow').hide();
	}
}

function escapeChemicalsHtml(value){
	if (value){
		var result = value.replace(/</g,'&lt;');
		result = result.replace(/>/g,'&gt;');
		result = result.replace(/"/g,'&quot;');
		return result;
	}
	return value;
}

function fillPlaylists(playlistNodes){
	var playlistsContainer = $('playlists');
	removeChildren(playlistsContainer);
	for (idx = 0; idx < playlistNodes.length; idx++){
		var entry = new Element('li');
		var title = playlistNodes[idx].getAttribute('title');
		var playlistId = playlistNodes[idx].getAttribute('id');
		entry.setAttribute('id', 'playlist' + playlistId);
		entry.update('<a href="javascript:loadPlaylist('+playlistId+', 0, true);">' + title + '<span class="more">&nbsp;</span></a>');
		playlistsContainer.appendChild(entry);
	}
}

function startDiashow(){
	var diashowElement = getDiashowElement();
	if(diashowElement){
		myLytebox.start(diashowElement, true, false);
	} else {
		$('buttonDiashow').hide();
	}
}

function getDiashowElement(){
	//aktuelles element
	var diashowElement = $('dia' + objectIndex);
	if (diashowElement){
		return diashowElement;
	} else {
		//naechstes photo
		for (idx = objectIndex; idx < currentPlaylist.objectCount; idx++){
			diashowElement= $('dia' + idx);
			if (diashowElement){
				return diashowElement;
			}
		}
		//voriges photo
		for (idx = currentPlaylist.objectCount - 1; idx >= 0; idx--){
			diashowElement= $('dia' + idx);
			if (diashowElement){
				return diashowElement;
			}
		}
	}
	return null;
}

function removeChildren(element){
	$A(element.childElements()).each(Element.remove);
}

function Playlist(objectsNode, isSearchResult){
	this.title = objectsNode.getAttribute('title');
	this.isSearchResult = isSearchResult;
	this.currentPage = 1;
	this.objectCount = objectsNode.childNodes.length;
	this.pages = $A(objectsNode.childNodes).eachSlice(OBJECTS_PER_PAGE);
	
	this.playlistId = -1;
	this.searchParameter = null;
	
	if (isSearchResult){
		$('playlistTitle').update(L10N_playlist_title_prefix_searchresult);
		$('player_headline').update(L10N_current_playlist_searchresult);
	} else {
		$('playlistTitle').update(L10N_playlist_title_prefix + ' "' + this.title + '"');
		$('player_headline').update(L10N_current_playlist + ': ' + this.title);
	}
}

Playlist.prototype.setPlaylistId = function(id){
	this.playlistId = id;
	this.searchParameter = null;
}

Playlist.prototype.setSearchParameter = function(parameter){
	this.playlistId = -1;
	this.searchParameter = parameter;
}



Playlist.prototype.setCurrentPage = function(pageNumber) {
	if (pageNumber > this.pages.length){
		this.currentPage = this.pages.length;
	} else if (pageNumber < 1){
		this.currentPage = 1;
	} else {
		this.currentPage = pageNumber;
	}
}

Playlist.prototype.getObjectsOfCurrentPage = function() {
	return this.pages[this.currentPage-1];
}

Playlist.prototype.nextPage = function() {
	this.setCurrentPage(this.currentPage + 1);
}

Playlist.prototype.previousPage = function() {
	this.setCurrentPage(this.currentPage - 1);
}

Playlist.prototype.firstPage = function() {
	this.currentPage = 1;
}

Playlist.prototype.lastPage = function() {
	this.currentPage = this.pages.length;
}
					
Playlist.prototype.hasPreviousPage = function() {
	return this.currentPage > 1;
}

Playlist.prototype.hasNextPage = function() {
	return this.currentPage < this.pages.length;
}

Playlist.prototype.hasMultiplePages = function() {
	return this.pages.length > 1;
}

Playlist.prototype.getPageNumberForObjectIndex = function(index){
	return Math.floor(index/OBJECTS_PER_PAGE) + 1;
}

Playlist.prototype.getObject = function(index){
	return this.pages[this.getPageNumberForObjectIndex(index) - 1][index % OBJECTS_PER_PAGE];
}
