var sourceHandler = new Array();
var liveTicker = null;
var isRequest = false;

/* Allgemeine Helfer */

/**
 *  Toggle
 */
function toggle(elementID) {
	if (dojo.byId(elementID) != null) {
		if (dojo.style(elementID, 'display') == 'none') {
			dojo.style(elementID, 'display', 'block');
		}
		else {
			dojo.style(elementID, 'display', 'none');
		}
	}
}

function toggleWithoutBlock(elementID) {
	if (dojo.byId(elementID) != null) {
		if (dojo.style(elementID, 'display') == 'none') {
			dojo.style(elementID, 'display', '');
		}
		else {
			dojo.style(elementID, 'display', 'none');
		}
	}
}

/* Toggle Table Columns */

function toggleTableColumns(columnElement) {
	// Detect the table
	var cell = columnElement;

	while (true) {
		if (cell.nodeName.toLowerCase() == 'th') {
			break;
		}
		else if (cell.nodeName.toLowerCase() == 'td') {
			break;
		}

		cell = cell.parentNode;
	}

	if (cell != null) {
		// Detect the pos of cell to hide
		var pos = 0;

		if (cell.parentNode != null) {
			var temp = cell.parentNode.getElementsByTagName(cell.nodeName);

			for (i = 0; i < temp.length; i++) {
				if (temp[i] == cell) {
					pos = i;
				}
			}
		}

		// Detect the table
		var table = cell.parentNode;

		while (table.nodeName.toLowerCase() != 'table') {
			table = table.parentNode;
		}

		// Hide Cells in the same row
		while ((cell = cell.nextSibling) != null) {
			if (cell.nodeType == 1) {
				if (dojo.style(cell, 'display') == 'none') {
					dojo.style(cell, 'display', '');
				}
				else {
					dojo.style(cell, 'display', 'none');
				}
			}
		}

		// Get all rows of table
		var rows = table.getElementsByTagName('tr');

		for(i = 0; i < rows.length; i++) {
			var tds = rows[i].getElementsByTagName('td');

			// Hide all tds on pos
			for (j = pos + 1; j < tds.length; j++) {
				if (dojo.style(tds[j], 'display') == 'none') {
					dojo.style(tds[j], 'display', '');
				}
				else {
					dojo.style(tds[j], 'display', 'none');
				}
			}
		}
	}
}

/* Toggle Table Rows */

function toggleTableRows(rowElement) {
	// Detect the row
	var row = rowElement;

	while (row.nodeName.toLowerCase() != 'tr') {
		row = row.parentNode;
	}

	if (row != null) {
		// Detect the table
		var table = row.parentNode;

		while (table.nodeName.toLowerCase() != 'table') {
			table = table.parentNode;
		}

		// Get all rows of table
		var rows = table.getElementsByTagName('tr');

		var hide = false;

		// Hide rows
		for (i = 0; i < rows.length; i++) {
			if (hide) {
				if (dojo.style(rows[i], 'display') == 'none') {
					dojo.style(rows[i], 'display', '');
				}
				else {
					dojo.style(rows[i], 'display', 'none');
				}
			}

			if (rows[i] == row) {
				hide = true;
			}
		}
	}
}

function toggleClassByName(elementName, classOne, classTwo) {
	var elements = dojo.doc.getElementsByTagName(elementName);

	for (i = 0; i < elements.length; i++) {
		toggleClass(elements[i], classOne, classTwo);
	}
}

function toggleClassByID(elementID, classOne, classTwo) {
	var element = dojo.byId(elementID);

	if (element != null) {
		toggleClass(element, classOne, classTwo);
	}
}

function toggleClass(element, classOne, classTwo) {
	if (element && dojo.hasClass(element, classOne)) {
		dojo.removeClass(element, classOne);
		dojo.addClass(element, classTwo);
	} else if (element) {
		dojo.removeClass(element, classTwo);
		dojo.addClass(element, classOne);
	}
}

/* Spezielle Helfer */

/**
 * Entfernt den JavaScript-Hinweis
 */
function removeNeedJavaScriptHint() {
	var needJavaScriptHint = dojo.byId('NeedJavaScript');

	if (needJavaScriptHint != null) {
		needJavaScriptHint.parentNode.removeChild(needJavaScriptHint);
	}
}

function findPosition(nodeElement) {
	var curTop = 0;
	var curLeft = 0;

	if (nodeElement.offsetParent) {
		do {
			curTop += nodeElement.offsetTop;
			curLeft += nodeElement.offsetLeft;
		} while (nodeElement = nodeElement.offsetParent);

		return [curTop,curLeft];
	}

	return null;
}

function handleResponse(result) {
	var timesButton = dojo.byId('TimesButton');

	if (timesButton != null) {
		//dojo.removeAttr(timesButton, 'disable', '');
	}

	/*
     * ReturnType = success, error, systemerror
     * Message = Meldung die angezeigt wird.
     *           Falls gesetzt für DurationToCallFunction
     * Function = Funktionsname, welche Aufgerufen werden soll
     * DurationToCallFunction = Zeigtangabe in Sekunden,
     *                          wann Function aufgerufen werden soll
     */
	var data = eval('(' + result + ')');

	if (typeof data['ReturnType'] == 'undefined' || typeof data['Message'] == 'undefined') {
		return;
	}

	var returnType = data['ReturnType'].toLowerCase();

	switch (returnType) {
		case 'success':
			isRequest = true;
		case 'error':
			var message = showMessage(data['Message']);

			if (message != null) {
				dojo.removeClass(message, 'errortext');
				dojo.removeClass(message, 'successtext');

				dojo.addClass(message, returnType + 'text');
			}

			if (typeof data['Function'] != 'undefined' && typeof data['DurationToCallFunction'] != 'undefined') {
				var functionCall = data['Function'] + '(';

				if (typeof data['Parameter'] != 'undefined') {
					functionCall += data['Parameter'];
				}

				functionCall += ')';

				var timeout = data['DurationToCallFunction'] * 1000;

				window.setTimeout(functionCall, timeout);
			}
			break;
		case 'systemerror':
			showInternalSystemErrorPopup(data['Message']);
			break;
	}
}

function reload() {
	var url = window.location.pathname;

	if (window.location.search.length > 0) {
		url += window.location.search;
	}

	window.location.href = url;
}

/* Change Class */

function changeExpandCollapse(elementID) {
	if (dojo.hasClass(elementID, 'expand')) {
		dojo.removeClass(elementID, 'expand');
		dojo.addClass(elementID, 'collapse');
	}
	else if (dojo.hasClass(elementID, 'collapse')) {
		dojo.removeClass(elementID, 'collapse');
		dojo.addClass(elementID, 'expand');
	}
}

/* Allgemein */

function ajaxSubmit(url, action, formID, contentToAppend, loadFunction) {
	var contentAction = new Array();
	contentAction['ajax'] = 1;
	contentAction['action[' + action + ']'] = action;

	for (var temp in contentToAppend) {
		contentAction[temp] = contentToAppend[temp];
	}

	var timesButton = dojo.byId('TimesButton');

	if (timesButton != null) {
		dojo.attr(timesButton, 'disabled', 'disabled');
	}

	if (formID != null && formID.length > 0) {
		var formElement = dojo.byId(formID);

		dojo.xhrPost({
			url: url,
			content: contentAction,
			form: formElement,
			load: loadFunction
		});
	}
	else {
		dojo.xhrPost({
			url: url,
			content: contentAction,
			load: loadFunction
		});
	}
}

/**
 * Erzeugt ein Assoziatives Array
 * 
 * @param key (string, number, array (aber kein assoziatives))
 * @param value (string, number, array (aber kein assoziatives))
 * @return array
 */
function getArray(key, value) {
	var temp = new Array();

	if (typeof key != 'array') {
		temp[key] = value;
	} else {
		for (var i = 0; i < key.length; i++) {
			temp[key[i]] = value[i];
		}
	}

	return temp;
}

/* News */

function toggleNews(clickElement) {
	var hParent = clickElement.parentNode.parentNode;
	
	var newsContent = dojo.byId('newscontent-'+hParent.id);
	toggle(newsContent);
	changeExpandCollapse(clickElement);
}

/* Menu */

function toggleSubmenu(clickElement) {
	var parent = clickElement.parentNode;

	if (parent != null) {
		var submenu = parent.getElementsByTagName('ul');

		if (submenu[0] != null) {
			toggle(submenu[0]);

			changeExpandCollapse(clickElement);
		}
	}
}

function checkMenuCollapseExpand(elementID) {
	var menuElement = dojo.byId(elementID);

	if (menuElement != null) {
		var lis = menuElement.getElementsByTagName('li');

		for (i = 0; i < lis.length; i++) {
			var uls = lis[i].getElementsByTagName('ul');

			for (j = 0; j < uls.length; j++) {
				if (dojo.style(uls[j], 'display') == 'block') {
					var as = lis[i].getElementsByTagName('a');

					for (k = 0; k < as.length; k++) {
						changeExpandCollapse(as[k]);
					}
				}
			}
		}
	}
}

function getPageSize() {
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	}
	else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	}
	else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		}
		else {
			windowWidth = self.innerWidth;
		}
		
		windowHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	}
	else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	}
	else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	}
	else {
		pageWidth = windowWidth;
	}

	return [pageWidth,pageHeight];
}

/* InternalPopup */

function showOverlay() {
	var pageSize = getPageSize();

	dojo.style('Overlay', {
		'height': pageSize[1] + 'px',
		'width': pageSize[0] + 'px',
		'display': 'block'
		}
	);
}

function hideOverlay() {
	dojo.style('Overlay', 'display', 'none');
}

function positionInternalPopup() {
	var oldStyle = dojo.style('InternalPopup', 'display');
		
	if (!oldStyle || (oldStyle && oldStyle == 'none')) {
		dojo.style('InternalPopup', 'display', 'block');

		var pageSize = getPageSize();

		var iPWWidth = dojo.style('InternalPopupWindow', 'width');

		var left = (pageSize[0] - iPWWidth) / 2;

		var iPWTop = dojo.style('InternalPopupWindow', 'top');

		var top = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

		dojo.style('InternalPopupWindow', {
			'top': 20 + 'px',
			/*'top': (top + iPWTop) + 'px',*/
			'left': left + 'px'
			}
		);
	}
}

function showInternalPopup(url, callbackFunction) {
	showOverlay();

	positionInternalPopup();

	loadSiteInInternalPopup(url, callbackFunction);
}

function hideInternalPopup(event) {
	if (event == null || event.target.getAttribute('id') == 'InternalPopup') {
		var timesButton = dojo.byId('TimesButton');

		if (timesButton != null) {
			dojo.removeAttr(timesButton, 'disabled');
		}

		dojo.style('InternalPopup', 'display', 'none');

		hideOverlay();
	}

	if (isRequest == true) {
		reload();
	}
}

function loadSiteInInternalPopup(url, callbackFunction) {
	var temp = dojo.byId('InternalPopupContent');

	if (temp != null && url != null && url.length > 0) {
		dojo.style('InternalPopupLoading', 'display', 'block');
		dojo.style(temp, 'display', 'none');

		var widgets = dijit.findWidgets(temp);
		dojo.forEach(widgets, function(item) {
			item.destroyRecursive();
		});

		dojo.xhrGet({
			url: url,
			content: {
				'ajaxcheck': 'true'
			},
			load: function(data) {
				if (data.search(/^http.*\.php$/i) > -1) {
					window.location.href = data;
					return;
				}

				dojo.require('dojo.html');

				dojo.html.set(temp, data);

				dojo.style('InternalPopupLoading', 'display', 'none');
				dojo.style(temp, 'display', 'block');

				showOverlay();

				dojo.parser.parse(temp);

				if(callbackFunction != null && (typeof window[callbackFunction] == 'function')) {
					window[callbackFunction]();
				}
			}
		});
	}
}

var mouseIsDNDOnInternalPopup = false;
var dndData = null;

function prepareInternalPopupToMove(event) {
	mouseIsDNDOnInternalPopup = true;

	var pageSize = getPageSize();

	dndData = new Array();
	dndData['defaultWidth'] = (pageSize[0] - dojo.style('InternalPopupWindow', 'width')) / 2;
	dndData['beginnWidth'] = event.pageX;
	dndData['height'] = event.pageY - dojo.style('InternalPopupWindow', 'top');
}

function moveInternalPopup(event) {
    if (mouseIsDNDOnInternalPopup == true && dndData != null) {
        var left = dndData['defaultWidth'] + (event.pageX - dndData['beginnWidth']);

    	dojo.style('InternalPopupWindow', {
            'top': (event.pageY - dndData['height']) + 'px',
            'left': left + 'px'
        });
    }
}

function finishInternalPopupFromMove(event) {
	mouseIsDNDOnInternalPopup = false;
	dndData = null;
}

function showInternalSystemErrorPopup(message) {
	hideInternalPopup();

	showOverlay();

	positionInternalPopup();

	var temp = dojo.byId('InternalPopupContent');

	if (temp != null && message != null) {
		dojo.style('InternalPopupLoading', 'display', 'none');
		dojo.style(temp, 'display', 'block');

		dojo.require('dojo.html');

		dojo.html.set(temp, '<div id="Systemerror">' + message + '</div>');

		showOverlay();
	}
}

function showTimes(buildID) {
	if (buildID != null) {
		showInternalPopup('timespopup.php?id=' + buildID + '&popup=1', null);
	}
}

function showHeal(playerID) {
	if (playerID != null) {
		showInternalPopup('timeshealpopup.php?id=' + playerID + '&popup=1', null);
	}
}

function showAge(playerID) {
	if (playerID != null) {
		showInternalPopup('timesagepopup.php?id=' + playerID + '&popup=1', null);
	}
}

function abortBuild(buildID) {
	var buildElement = dojo.byId('BuildQueueID');

	if (buildElement != null) {
		buildElement.value = buildID;
	}
}

function showTicker(url) {
	if (!url || (url && url.length == 0)) {
		url = 'liveticker.php';
	}
	// dependent?
	var params = 'height=706,width=1000,top=150,left=150,location=no,menubar=no,scrollbars=yes,status=yes,toolbar=no';
	if (!liveTicker || (liveTicker && liveTicker.closed)) {
		liveTicker = window.open(url, '', params);
	}
	liveTicker.location.href = url;
	liveTicker.focus();
}

/* Register */

function switchBackgroundFromManager(elementID1, elementID2, value) {
	var registerElement1 = dojo.byId(elementID1);
	var registerElement2 = dojo.byId(elementID2);

	if (registerElement1 != null && registerElement2 != null) {
		if (value == 'player') {
			dojo.style(registerElement1, 'display', '');
			registerElement2.value = 1;
		}
		else {
			dojo.style(registerElement1, 'display', 'none');
			registerElement2.value = 0;
		}
	}
}

function updateOptionalHint() {
	var optionalElement = dojo.byId('Optional');

	if (optionalElement != null) {
		if (optionalElement.value == 0) {
			optionalElement.value = 1;
		}
		else {
			optionalElement.value = 0;
		}
	}
}

/* Activationteam */

var choosedStadiumImage = null;

function showStadiumOverview(stadiumname) {
	var stadiumImageElement = dojo.byId('StadiumImage');

	if (stadiumImageElement != null) {
		if (stadiumname != null && stadiumname.length > 0) {
			dojo.style(stadiumImageElement, 'background', 'transparent url(../images/stadiums/' + stadiumname.toLowerCase() + '/overview.jpg) scroll no-repeat top left');
		}
		else if (choosedStadiumImage == null) {
			dojo.style(stadiumImageElement, 'background', '');
		}
		else {
			dojo.style(stadiumImageElement, 'background', choosedStadiumImage);
		}
	}
}

function chooseStadiumImage() {
	var stadiumImageElement = dojo.byId('StadiumImage');

	if (stadiumImageElement != null) {
		choosedStadiumImage = dojo.style(stadiumImageElement, 'background');
	}
}

/* GameInformation */

function showGameInformation(site) {
	showInternalPopup('gameinformation.php?site=' + site + '&popup=1', null);
}

// ??? - Glaube das es veraltet ist
function showTabContent(tabElementID) {
	var tabElement = dojo.byId(tabElementID);

	if (tabElement != null) {
		var parent = tabElement.parentNode;

		var tab = parent.firstChild.nextSibling;

		while ((tab = tab.nextSibling) != null) {
			if (tab.nodeType == 1) {
				dojo.style(tab, 'display', 'none');
			}
		}

		toggle(tabElement);
	}
}

//??? - Glaube das es veraltet ist
function showGlossaryLetter(value) {
	var glossaryElement = dojo.byId('GlossaryA');

    if (glossaryElement != null) {
    	do {
    		if (glossaryElement.nodeType == 1) {
    			dojo.style(glossaryElement, 'display', 'none');
    		}
    	}
    	while((glossaryElement = glossaryElement.nextSibling) != null);
    }

	toggle(value);
}

/* --- Office --- */

function showMarkerDiv(coords, url, type, startCoordX, startCoordY, endCoordX, endCoordY) {
	removeMarkerDiv();

	coordsArray = coords.split(',');

	if (coordsArray.length > 0) {
		var markerDiv = dojo.doc.createElement('div');

		link = dojo.doc.createElement('a');

		dojo.attr(link, 'href', url);

		dojo.style(link, {
			'display': 'block',
			'height': '100%',
			'width': '100%'
		});

		markerDiv.appendChild(link);

		dojo.attr(markerDiv, 'id', 'MarkerDiv');
		dojo.attr(markerDiv, 'onmouseout', 'removeMarkerDiv()');

		var top = 166;
		var left = parseInt((window.innerWidth / 2) - 304);
		var height = 0;
		var width = 0;

		var viewHeight = window.innerHeight;
		var pageSize = getPageSize();

		if (dojo.isIE == 6) {
			left = parseInt((document.documentElement.clientWidth / 2) - 237);
			viewHeight = document.documentElement.clientHeight;
		}
		else if (dojo.isIE == 7) {
			left = parseInt((document.body.clientWidth / 2) - 237);
			viewHeight = document.body.clientHeight;
		}

		if (pageSize[1] <= viewHeight) {
			if (dojo.isIE) {
				left -= 13;
			}
			else {
				left += 9;
			}
		}

		switch (type) {
			case 1: // rect
				top += parseInt(coordsArray[1]);
				left += parseInt(coordsArray[0]);
				height = (parseInt(coordsArray[3]) - parseInt(coordsArray[1]));
				width = (parseInt(coordsArray[2]) - parseInt(coordsArray[0]));
				break;
			case 2: // circle
				top += parseInt(coordsArray[1]) - parseInt(coordsArray[2]);
				left += parseInt(coordsArray[0]) - parseInt(coordsArray[2]);
				height = parseInt(coordsArray[2]) * 2;
				width = height;
				break;
			case 3: // poly
				top += parseInt(coordsArray[startCoordY]);
				left += parseInt(coordsArray[startCoordX]);
				height = (parseInt(coordsArray[endCoordY]) - parseInt(coordsArray[startCoordY]));
				width = (parseInt(coordsArray[endCoordX]) - parseInt(coordsArray[startCoordX]));
				break;
		}

		dojo.style(markerDiv, {
			'position': 'absolute',
			'top': top + 'px',
			'left': left + 'px',
			'height': height + 'px',
			'width': width + 'px'
		});

		var temp = dojo.body();

		temp.appendChild(markerDiv);
	}
}

function removeMarkerDiv() {
	var markerDiv = dojo.byId('MarkerDiv');

	if (markerDiv != null) {
		var parent = markerDiv.parentNode;

		if (parent != null) {
			parent.removeChild(markerDiv);
		}
	}
}



/* Switch Team */

function switchTeam(site, parametername, teamid) {
	window.location = site + '?' + parametername + '=' + teamid;
}

/* Switch Picture */

function switchPlayerPicture(elementID, back) {
	var picture = dojo.byId(elementID);

	if (picture != null) {
		var pic = switchPicture(picture, '/([0-9]+)\.[a-zA-Z]+', back, playerPictures.length);

		dojo.attr(picture, 'src', playerPictures[pic]['full']);
		dojo.attr(dojo.byId('Hidden' + elementID), 'value', playerPictures[pic]['picturename']);
	}
}

function switchShirtPicture(elementID, back) {
	var picture = dojo.byId(elementID);

	if (picture != null) {
		var pic = switchPicture(picture, '/([0-9]+)\.[a-zA-Z]+', back, shirtPictures.length);

		dojo.attr(picture, 'src', shirtPictures[pic]['full']);
		dojo.attr(dojo.byId('Hidden' + elementID), 'value', pic);
	}
}

function switchEmblemPicture(elementID, back) {
	var picture = dojo.byId(elementID);

	if (picture != null) {
		var pic = switchPicture(picture, '/([0-9]+)\.[a-zA-Z]+', back, emblemPictures.length);

		dojo.attr(picture, 'src', emblemPictures[pic]['full']);
		dojo.attr(dojo.byId('Hidden' + elementID), 'value', pic);
	}
}

function switchPicture(pictureElement, regexString, back, maxLength) {
	if (pictureElement != null) {
		var regEx = new RegExp(regexString);
		var result = regEx.exec(dojo.attr(pictureElement, 'src'));

		if (result != null) {
			var pic = parseInt(result[1], 10);

			if (back == false) {
				pic += 1;
			}
			else if (back == true) {
				pic -= 1;
			}

			if (pic <= 0) {
				pic = maxLength - 1;
			}
			else if (pic >= maxLength) {
				pic = 1;
			}

			return pic;
		}
	}
}

function switchModelPicture(elementID, back) {
	var picture = dojo.byId(elementID);

	if (picture != null) {
		var model = dojo.attr(dojo.byId('Hidden' + elementID), 'value');
		var index = -1;

		for (i = 0; i < stadiumPictures.length; i++) {
			if (stadiumPictures[i] == model) {
				index = i;
				break;
			}
		}

		if (back) {
			index--;
		}
		else {
			index++;
		}

		if (index < 0) {
			index = stadiumPictures.length - 1;
		}
		else if (index >= stadiumPictures.length) {
			index = 0;
		}

		var newModel = stadiumPictures[index];

		dojo.attr(picture, 'src', dojo.attr(picture, 'src').replace(model, newModel));
		dojo.attr(dojo.byId('Hidden' + elementID), 'value', newModel);
	}
}

/* Show Player Profile */

function showPlayerProfile(playerID, transfermarketID, back2team) {
	var url = 'playerprofile.php?';

	if (playerID != null) {
		url += 'id=' + playerID;
	}
	else if (transfermarketID != null) {
		url += 'transfermarket=' + transfermarketID;
	}
	
	if (back2team || back2team != null) {
		url += "&backteam="+back2team;
	}

	url += '&popup=1';

	showInternalPopup(url, null);
}


/**
 * Zeigt den Userdialog an.
 * TODO hier
 * @param optLangKey
 * @return boolean 
 */
function showDeleteQuestion(formId, optLangKey, btName, btValue) {
	var url = 'confirm-js.php?';

	if (formId != null) {
		url += 'formId=' + formId;
	} else {
		return;
	}
	if (optLangKey != null) {
		url += '&optKey=' + optLangKey;
	}
	if (btName != null) {
		url += '&btName=' + btName;
		if (btValue != null) {
			url += '&btValue=' + btValue;
		} else {
			url += '&btValue=' + btName;
		}
	}
	
	url += '&popup=1';

	showInternalPopup(url, null);
}

function doSubmitForm(formId, btName, btValue) {
	var subForm = dojo.byId(formId);
	if (subForm && subForm != null) {
		// hidden input erzeugen
		var newElement = dojo.doc.createElement('input');

		if (btName && btName != null) {
			dojo.attr(newElement, 'type', 'hidden');
			dojo.attr(newElement, 'name', btName);
			// Wert hinzufügen
			dojo.attr(newElement, 'value', btValue);
	
			subForm.appendChild(newElement);
		}
		
		subForm.submit();
	}
}


/* Show Player Delete */

function showPlayerDelete(id) {
	var url = 'playerdelete.php?id=' + id + '&popup=1';

	//showInternalPopup(url, null);
	loadSiteInInternalPopup(url, null);
}

/* Show Player Training */

function showPlayerTraining(id) {
	var url = 'playertraining.php?ids=' + id + '&popup=1';

	//showInternalPopup(url, null);
	loadSiteInInternalPopup(url, null);
}

/* Show Player Sale */

function showPlayerSale(id) {
	var url = 'playersale.php?id=' + id + '&popup=1';

	//showInternalPopup(url, null);
	loadSiteInInternalPopup(url, null);
}

/* Show Player Switch Training */

function showPlayerSwitchTraining(id) {
	var url = 'playerswitchtraining.php?id=' + id + '&popup=1';

	//showInternalPopup(url, null);
	loadSiteInInternalPopup(url, null);
}

/* Show Player Convert */

function showPlayerConvert(id) {
	var url = 'playerconvert.php?id=' + id + '&popup=1';

	//showInternalPopup(url, null);
	loadSiteInInternalPopup(url, null);
}

/* Show Player TrainingsCamp */

function showPlayerTrainingsCamp(id) {
	var url = 'playertrainingscamp.php?ids=' + id + '&popup=1';

	//showInternalPopup(url, null);
	loadSiteInInternalPopup(url, null);
}

function switchTraining(changeElement, playerID) {
	var dijit1 = dijit.byId('SwitchTrainingFrom'+playerID);
	var dijit2 = dijit.byId('SwitchTrainingTo'+playerID);
	if (dijit1 != null && dijit2 != null) {
		if (changeElement.checked == true) {
			dijit1.attr('disabled', false);
			dijit2.attr('disabled', false);
		} else {
			dijit1.attr('disabled', true);
			dijit2.attr('disabled', true);
		}
	}	
}

/* Show Team Profile */

function showTeamProfile(id) {
	var url = 'teamprofile.php?id=' + id + '&popup=1';

	showInternalPopup(url, null);
}

/* Toggle Team Profile Tabs */

function showTeamProfileTab(elementID) {
	var teamProfileTab = dojo.byId('TeamProfileTabs');

	if (teamProfileTab != null) {
		var tabs = teamProfileTab.getElementsByTagName('div');

		for (i = 0; i < tabs.length; i++) {
			dojo.style(tabs[i], 'display', 'none');
		}

		var elementToShow = dojo.byId(elementID);

		if (elementToShow != null) {
			dojo.style(elementToShow, 'display', '');
		}
	}
}

/* Show Stadium Profile */

function showStadiumProfile(sid, type, id) {
	var url = 'stadiumprofile.php?sid=' + sid;

	if (type != null) {
		url += '&type=' + type;
	}

	if (id != null) {
		url += '&id=' + id;
	}
	
	url += '&popup=1';

	showInternalPopup(url, null);
}

/* Show Customer Profile */

function showCustomerProfile(cid, type, id) {
	var url = 'customerprofile.php?cid=' + cid;

	if (type != null) {
		url += '&type=' + type;
	}

	if (id != null) {
		url += '&id=' + id;
	}

	url += '&popup=1';

	showInternalPopup(url, null);
}

/* Show TechTree Entry */

function showTechTreeProfile(art, level) {
	var url = 'techtreeprofile.php?art=' + art + '&level=' + level + '&popup=1';

	showInternalPopup(url, null);
}

function markTechTreeEntry(elementID) {
	var techTreeEntry = dojo.byId(elementID);

	if (techTreeEntry != null) {
		parent = techTreeEntry.parentNode;

		while (parent.nodeName.toLowerCase() != 'ul') {
			parent = parent.parentNode;
		}

		if (parent != null) {
			var divs = parent.getElementsByTagName('div');

			for (i = 0; i < divs.length; i++) {
				dojo.removeClass(divs[i], 'markTechTreeEntry');
			}
		}

		dojo.addClass(techTreeEntry, 'markTechTreeEntry');
	}
}

function buildQueueIDByMarkTechTreeEntry(element, parentID) {
	parent = element.parentNode;

	while (!dojo.hasAttr(parent, 'id') && parent.id != parentID) {
		parent = parent.parentNode;
	}

	if (parent != null) {
		var divs = parent.getElementsByTagName('div');

		for (i = 0; i < divs.length; i++) {
			if (dojo.hasClass(divs[i], 'markTechTreeEntry')) {
				return divs[i].id.substr(1);
			}
		}
	}

	return null;
}

/* Show Items */

function showItems(elementID, showElementID) {
	toggle(elementID);

	var showElement = dojo.byId(showElementID);

	if (showElement != null) {
		if (showElement.value == 0) {
			showElement.value = 1;
		}
		else {
			showElement.value = 0;
		}
	}
}

/* Pool LineUp */

function loadTactic(tactic, formname) {
	// hidden input erzeugen
	newElement = dojo.doc.createElement('input');

	dojo.attr(newElement, 'type', 'hidden');
	dojo.attr(newElement, 'name', 'tactic');
	// Wert hinzufügen
	dojo.attr(newElement, 'value', tactic);

	dojo.doc.forms['poolLineUp'].appendChild(newElement);

	document.forms[formname].submit();
}

function showLineUp(powerSentence) {
	var targetElement = dojo.byId('PlayersLineUpTable');

	if (targetElement == null) {
		return;
	}

	// Clean Old Data
	var parent = targetElement.parentNode;

	if (parent != null) {
		var newTargetElement = targetElement.cloneNode(false);
	
		parent.replaceChild(newTargetElement, targetElement);

		targetElement = newTargetElement;
	}

	// Gesamtstärke der aufgestellten Mannschaft
	var power = 0;

	var counter = 1;
	var tempElement = null;
	var divs = null;
	var cloneDiv = null;
	var playerDivs = null;
	var tempDiv = null;
	var playerPower = null;

	// Clone the lineup to show
	for (i = 1; i <= 82; i++) {
		tempElement = dojo.byId('Position' + i);

		if (tempElement != null) {
			divs = tempElement.getElementsByTagName('div');

			if (divs.length > 0) {
				// copy into PlayersLineUpTable
				for (j = 0; j < divs.length; j++) {
					if (dojo.hasClass(divs[j], 'dojoDndItem')) {
						cloneDiv = divs[j].cloneNode(true);

						dojo.removeClass(cloneDiv, 'even');

						if ((counter++%2) == 0) {
							dojo.addClass(cloneDiv, 'even');
						}

						targetElement.appendChild(cloneDiv);

						playerDivs = divs[j].getElementsByTagName('div');

						for (k = 0; k < playerDivs.length; k++) {
							if (dojo.hasClass(playerDivs[k], 'playerpower')) {
								tempDiv = playerDivs[k].childNodes;

								for (l = 0; l < tempDiv.length; l++) {
									playerPower = String(tempDiv[l].nodeValue);

									if (playerPower.indexOf('.') > -1) {
										power += parseFloat(playerPower) * 1000;
									} else {
										power += parseInt(playerPower);
									}
								}
							}
						}
					}
				}
			}
		}
	}

	// show power
	var newElement = dojo.doc.createElement('div');

	dojo.addClass(newElement, 'power');

	// Wert hinzufügen
	newElement.appendChild(dojo.doc.createTextNode(powerSentence + ' ' + addSeparatorsNF(power, '.', ',', '.')));

	targetElement.appendChild(newElement);
}

/**
 * @param nStr The number to be formatted, as a string or number. No validation is done, so don't input a formatted number. If inD is something other than a period, then nStr must be passed in as a string.
 * @param inD The decimal character for the input, such as '.' for the number 100.2
 * @param outD The decimal character for the output, such as ',' for the number 100,2
 * @param sep The separator character for the output, such as ',' for the number 1,000.2
 * @return
 */
function addSeparatorsNF(nStr, inD, outD, sep)
{
	nStr += '';
	var dpos = nStr.indexOf(inD);
	var nStrEnd = '';
	if (dpos != -1) {
		nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
		nStr = nStr.substring(0, dpos);
	}
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(nStr)) {
		nStr = nStr.replace(rgx, '$1' + sep + '$2');
	}
	return nStr + nStrEnd;
}

function setLineUpHandlers() {
	dojo.require('dojo.dnd.Source');

	for (i = 1; i <= 82; i++) {
		var positionElement = dojo.byId('Position' + i);

		for (j = sourceHandler.length - 1; j >= 0; j--) {
			if (sourceHandler[j].node.id.toLowerCase().indexOf(positionElement.id.toLowerCase()) > -1) {
				sourceHandler.splice(j, 1);
			}
		}

		dojo.connect(positionElement, 'onDndStart', 'dndStart');
		dojo.connect(positionElement, 'onDndDrop', 'dndDrop');

		sourceHandler[sourceHandler.length] = new dojo.dnd.Source(positionElement, {
			copyOnly: false,
			singular: true/*,
			onOverEvent: function () {
				showPlayerHint(this);
			},
			onOutEvent: function () {
				hidePlayerHint(this);
			}*/
		});
	}

	// Tabelle mit den restlichen Spielern Drag'n'Drop-fähig machen
	dndSource = new dojo.dnd.Source('PlayersStandByTable', {
		copyOnly: false,
		singular: true/*,
		checkAcceptance: function(srcObject, nodesArr) {
			var returnValue = true;

			dojo.forEach(nodesArr, function(node) {
				var divs = node.getElementsByTagName('div');

				for (i = 0; i < divs.length; i++) {
					if (dojo.hasClass(divs[i], 'playerfitness')) {
						var fitness = parseInt(divs[i].firstChild.nodeValue);
console.log(fitness);
console.log(fitness <= 5);
						if (fitness <= 5) {
							returnValue = false;
						}
					}
				}
			});
			console.log(returnValue);
			return returnValue;
		}*/
	});

	sourceHandler[sourceHandler.length] = dndSource;

	dojo.connect(dndSource, 'onDndStart', 'dndStart');
	dojo.connect(dndSource, 'onDndDrop', 'dndDrop');
}

//Drag'n'Drop

function dndStart(sourceObject, nodesArray, doCopy) {
	var temp = sourceObject.getAllNodes();
/*
	dojo.forEach(nodesArray, function(node) {
		var divs = node.getElementsByTagName('div');

		for (i = 0; i < divs.length; i++) {
			if (dojo.hasClass(divs[i], 'playerfitness')) {
				var fitness = parseInt(divs[i].firstChild.nodeValue);

				if (fitness <= 5) {
					//dojo.dnd.manager().stopDrag();
					//dojo.stopEvent(this);
					//sourceObject.stopDrag();
					sourceObject.onDndStart.accept = false;
				}
			}
		}
	});
*/
	for (i = 0; i < temp.length; i++) {
		dojo.removeClass(temp[i], 'dojoDndItemOld');
	}
}

function dndDrop(sourceObject, nodesArray, doCopy, targetObject) {
	if (nodesArray.length > 0) {
		var temp = targetObject.getAllNodes();

		for (i = 0; i < temp.length; i++) {
			if (isSameNode(temp[i], nodesArray)) {
				continue;
			}

			if (dojo.hasClass(temp[i], 'dojoDndItemOld')) {
				dojo.removeClass(temp[i], 'dojoDndItemOld');

				sourceObject.insertNodes(false, [temp[i]]);
			}
		}

		dojo.removeClass(nodesArray[0], 'dojoDndItemAnchor');

		if (targetObject.node.id.toLowerCase() != 'playersstandbytable') {
			dojo.addClass(nodesArray[0], 'dojoDndItemOld');
		}
	}
}

function isSameNode(nodeElement, nodeArray) {
	for (j = 0; j < nodeArray.length; j++) {
		if (nodeElement == nodeArray[j]) {
			return true;
		}
	}

	return false;
}

var playerHint = null;

function showPlayerHint(dndElement) {
	if (playerHint != null) {
		return true;
	}

	var targetElement = dndElement.node;

	if (targetElement.childNodes.length > 0) {
		var divs = targetElement.getElementsByTagName('div');

		for (i = 0; i < divs.length; i++) {
			playerHint = divs[i].cloneNode(true);

			dojo.addClass(playerHint, 'playerHint');

			var position = findPosition(targetElement);

			dojo.style(playerHint, {
				position: 'absolute',
				top: (position[0] + targetElement.offsetHeight) + 'px',
				left: (position[1] + targetElement.offsetWidth) + 'px'
			});

			dojo.body().appendChild(playerHint);

			break;
		}
	}

	return true;
}

function hidePlayerHint(dndElement) {
	if (playerHint == null) {
		return;
	}

	var parent = playerHint.parentNode;

	if (parent != null) {
		parent.removeChild(playerHint);

		playerHint = null;
	}
}

function savePreset(event) {
	var presetElements = dojo.doc.getElementsByName('preset');

	if (presetElements.length > 0) {
		dojo.style('PresetHint', 'display', 'none');

		saveLineup(event, presetElements[0].value);
	} else {
		dojo.style('PresetHint', 'display', '');
	}
}

function setSaveAs(newValue) {
	dojo.attr('SaveAsInput', 'value', newValue);
}

function setTeamChange(widget) {
	if (widget.checked == true) {
		dojo.attr('TeamChangeInput', 'value', widget.attr('value'));
	}
}

function saveLineup(event, preset) {
	var tempElement = null;
	var players = new Array();
	var divs = null;
	var playerProperties = null;
	var index = null;
	var newElement = null;
	var tactic = '';
	var tempTactic = 0;

	// Alle Spieler auf dem Spielfeld ermitteln
	for (i = -1; i <= 82; i++) {
		tempElement = dojo.byId('Position' + i);

		if (tempElement != null) {
			divs = tempElement.getElementsByTagName('div');

			if (divs.length > 0) {
				for (j = 0; j < divs.length; j++) {
					playerProperties = divs[j].getElementsByTagName('div');

					for (k = 0; k < playerProperties.length; k++) {
						if (dojo.hasClass(playerProperties[k], 'playerid')) {
							index = players.length;

							players[index] = new Array();
							players[index]['ID'] = playerProperties[k].firstChild.nodeValue;
							players[index]['Position'] = i;

							tempTactic++;
						}
					}
				}
			}
		}

		if ((i%27) == 0) {
			tactic = tactic + String(tempTactic);
			tempTactic = 0;
		}
	}

	if (players.length > 11) {
		dojo.style('PlayerHint', 'display', '');

		return;
	} else {
		dojo.style('PlayerHint', 'display', 'none');
	}

	for (i = 0; i < players.length; i++) {
		player = players[i];

		// hidden input erzeugen
		newElement = dojo.doc.createElement('input');

		dojo.attr(newElement, 'type', 'hidden');
		dojo.attr(newElement, 'name', 'players[' + player['ID'] + ']');
		// Wert hinzufügen
		dojo.attr(newElement, 'value', player['Position']);

		dojo.doc.forms['poolLineUp'].appendChild(newElement);
	}

	//Taktik
	// hidden input erzeugen
	newElement = dojo.doc.createElement('input');

	dojo.attr(newElement, 'type', 'hidden');
	dojo.attr(newElement, 'name', 'tactic');
	// Wert hinzufügen
	dojo.attr(newElement, 'value', tactic);

	dojo.doc.forms['poolLineUp'].appendChild(newElement);

	// Preset
	if (preset != null) {
		// hidden input erzeugen
		newElement = dojo.doc.createElement('input');

		dojo.attr(newElement, 'type', 'hidden');
		dojo.attr(newElement, 'name', 'preset');
		// Wert hinzufügen
		dojo.attr(newElement, 'value', preset);

		dojo.doc.forms['poolLineUp'].appendChild(newElement);
	}

	// Action
	// hidden input erzeugen
	newElement = dojo.doc.createElement('input');

	dojo.attr(newElement, 'type', 'hidden');
	dojo.attr(newElement, 'name', 'action');
	// Wert hinzufügen
	dojo.attr(newElement, 'value', 'save');

	dojo.doc.forms['poolLineUp'].appendChild(newElement);

	dojo.doc.forms['poolLineUp'].submit();
}

function showMessage(messageText) {
	dojo.require('dojo.html');

	var message = dojo.byId('Message');

	if (message != null) {
		dojo.html.set(message, messageText);
	}

	return message;
}

/* Commander */

function markPlayer(elementToMark) {
	dojo.attr('PoolPlayerMoveRight', 'disabled', 'disabled');
	dojo.style('PoolPlayerMoveRight', 'backgroundImage', 'url(../images/design/bt_right_disabled.png)');
	dojo.attr('PoolPlayerMoveLeft', 'disabled', 'disabled');
	dojo.style('PoolPlayerMoveLeft', 'backgroundImage', 'url(../images/design/bt_left_disabled.png)');

	if (dojo.hasAttr(elementToMark, 'id')) {
		dojo.removeAttr(elementToMark, 'id');
	}
	else {
		removeAttributeFromElement('TeamTransferFrom', 'tr', 'id');

		removeAttributeFromElement('TeamTransferTo', 'tr', 'id');

		dojo.attr(elementToMark, 'id', 'PlayerMarker');

		checkPlayerMoveable();
	}
}

function removeAttributeFromElement(elementID, elementTagName, attributeName) {
	var temp = dojo.byId(elementID);

	if (temp != null) {
		temp = temp.getElementsByTagName(elementTagName);
		for (i = 0; i < temp.length; i++) {
			if (dojo.hasAttr(temp[i], attributeName)) {
				dojo.removeAttr(temp[i], attributeName);
			}
		}
	}
}

function moveMarkedPlayerToNewTeam(targetElementName, teamElementID) {
	var playerElement = dojo.byId('PlayerMarker');

	if (playerElement != null) {
		var targetElement = dojo.byId(targetElementName);

		if (targetElement != null) {
			targetElement = targetElement.getElementsByTagName('tbody')[0];

			targetElement.appendChild(playerElement);

			var widget = dijit.byId(teamElementID);

			var teamID = null;

			if (widget) {
				teamID = widget.attr('value');
			}

			if (teamID == null) {
				teamID = dojo.attr(teamElementID, 'value');

				if (teamID == null) {
					teamID = dojo.byId(teamElementID).value;
				}
			}

			if (teamID != null) {
				var temp = playerElement.getElementsByTagName('input');

				for (i = 0; i < temp.length; i++) {
					dojo.attr(temp[i], 'value', teamID);
				}
			}

			removeAttributeFromElement(targetElementName, 'tr', 'id');

			dojo.attr('PoolPlayerMoveRight', 'disabled', 'disabled');
			dojo.style('PoolPlayerMoveRight', 'backgroundImage', 'url(../images/design/bt_right_disabled.png)');
			dojo.attr('PoolPlayerMoveLeft', 'disabled', 'disabled');
			dojo.style('PoolPlayerMoveLeft', 'backgroundImage', 'url(../images/design/bt_left_disabled.png)');
		}
	}
}

function checkPlayerMoveable() {
	var tableToHandle = null;
	var tableLeft = null;

	var table = dojo.byId('TeamTransferFrom');

	if (table != null) {
		var temp = table.getElementsByTagName('tr');

		if (temp != null) {
			for (i = 0; i < temp.length; i++) {
				if (dojo.hasAttr(temp[i], 'id')) {
					tableToHandle = table;
					tableLeft = true;
					break;
				}
			}
		}
	}

	var table = dojo.byId('TeamTransferTo');

	if (table != null) {
		var temp = table.getElementsByTagName('tr');

		if (temp != null) {
			for (i = 0; i < temp.length; i++) {
				if (dojo.hasAttr(temp[i], 'id')) {
					tableToHandle = table;
					tableLeft = false;
					break;
				}
			}
		}
	}

	if (tableToHandle != null) {
		var temp = tableToHandle.getElementsByTagName('input');

		var trainer = 0;
		var player = 0;

		if (temp != null) {
			for (i = 0; i < temp.length; i++) {
				if (dojo.attr(temp[i], 'name').indexOf('trainer') > -1) {
					trainer += 1;
				}
				else {
					player += 1;
				}
			}

			player = player - trainer;
		}

		var playerElement = dojo.byId('PlayerMarker');

		var isPlayer = true;

		if (playerElement != null) {
			temp = playerElement.getElementsByTagName('input');

			if (temp != null) {
				for (i = 0; i < temp.length; i++) {
					if (dojo.attr(temp[i], 'name').indexOf('trainer') > -1) {
						isPlayer = false;
					}
				}
			}
		}
		
		if (tableLeft == true) {
			if (player > poolPlayerMin && player < poolPlayerMax && isPlayer) {
				dojo.removeAttr('PoolPlayerMoveRight', 'disabled');
				dojo.style('PoolPlayerMoveRight', 'backgroundImage', 'url(images/design/bt_right.png)');
			}
			else if (trainer > poolPlayerTrainerMin && trainer < poolPlayerTrainerMax && !isPlayer) {
				dojo.removeAttr('PoolPlayerMoveRight', 'disabled');
				dojo.style('PoolPlayerMoveRight', 'backgroundImage', 'url(images/design/bt_right.png)');
			}
		}
		else if (tableLeft == false) {
			if (player > poolPlayerMin && player < poolPlayerMax && isPlayer) {
				dojo.removeAttr('PoolPlayerMoveLeft', 'disabled');
				dojo.style('PoolPlayerMoveLeft', 'backgroundImage', 'url(images/design/bt_left.png)');
			}
			else if (trainer > poolPlayerTrainerMin && trainer < poolPlayerTrainerMax && !isPlayer) {
				dojo.removeAttr('PoolPlayerMoveLeft', 'disabled');
				dojo.style('PoolPlayerMoveLeft', 'backgroundImage', 'url(images/design/bt_left.png)');
			}
		}
	}
}

/* Calculate Training */

function calculateTraining() {
	var trainingElement = dojo.byId('Training');

	if (trainingElement != null) {
		var tableElements = trainingElement.getElementsByTagName('table');

		if (tableElements.length > 0) {
			var isOver100 = false;

			for (var i = 0; i < tableElements.length; i++) {
				var sum = 0;
				
				var widg = dijit.findWidgets(tableElements[i]);
				
				var sum = 0;
				for (var j = 0; j < widg.length; j++) {
					if (widg[j] != null) {
						sum += parseInt(widg[j].attr('value'));
					}
				}
				if (sum > 100) {
					isOver100 = true;
				}
			}
			showOver100Hint(isOver100);
		}
	}
}

function showOver100Hint(show) {
	var hintElement = dojo.byId('Over100Hint');

	if (hintElement != null) {
		if (show) {
			dojo.style(hintElement, 'display', 'block');
		}
		else {
			dojo.style(hintElement, 'display', 'none');
		}
	}
}

/* Calculate Next Bid Price */

function calculateNextBidPrice(showElementID, targetElementID, price, bid) {
	var showElement = dojo.byId(showElementID);

	var targetElement = dojo.byId(targetElementID);

	if (showElement != null && targetElement != null) {
		toggleWithoutBlock(showElementID);

		if (dojo.style(showElement, 'display') == 'none') {
			targetElement.value = '';
		}
		else {
			if (bid > 0) {
				targetElement.value = parseInt(price) + 1000;
			}
			else {
				targetElement.value = parseInt(price);
			}
		}
	}
}

/* Calculate Licence */

function calcManagerLizenzCost(selectElement, pid) {
	var value = selectElement.value;

	var cost = 7000000;

	if (value != null && value >= 3) {
		cost = 6000000;
	}

	if (pid != null && cost != null) {
		var productCost = dojo.byId(pid);

		if (productCost != null) {
			dojo.require('dojo.number');

			productCost.firstChild.data = dojo.number.format(cost);
		}
	}
}

/* Calculate Place Win */

function calculatePlaceWin(countPlaceID, priceID, WinID) {
	var priceElement = dojo.byId(priceID);

	if (priceElement == null) {
		return;
	}

	price = parseInt(priceElement.value);

	if (String(price) == 'NaN') {
		priceElement.value = '';
		updateContent(WinID, 0);
		return;
	}

	var countPlaceElement = dojo.byId(countPlaceID);

	if (countPlaceElement == null) {
		return;
	}

	var countPlace = parseInt(countPlaceElement.value);

	var win = null;

	if (String(countPlace) != 'NaN') {
		win = countPlace * price;
	}

	if (win != null && win > 0) {
		updateContent(WinID, win);
	}
	else {
		updateContent(WinID, 0);
	}
}

/* Place Upgrade */

function updateVIPPlaceUpgrade(sourceElementID, updateElementID, operation) {
	var sourceElement = dojo.byId(sourceElementID);

	if (sourceElement != null && operation != null) {
		var value = parseInt(sourceElement.firstChild.data);

		if (value != null) {
			var updateValue = value;

			if (operation == 1 && updateValue < 3000) {
				updateValue += 500;
			}
			else if (operation == -1 && updateValue >= -3000) {
				updateValue -= 500;
			}

			sourceElement.firstChild.data = updateValue;

			var hiddenSourceElement = dojo.byId(sourceElementID + 'Hidden');
			
			if (hiddenSourceElement != null) {
				hiddenSourceElement.value = updateValue;
			}

			if (updateValue > 0) {
				calculatePlaceUpgrade(null, updateElementID, updateValue);
			}
			else {
				updateContent(updateElementID, 0);
			}
		}
	}
}



/* Calculate Stadium In */

// Kann gelöscht werden
function calculateStadium(productName, productLevel, isAdd, priceElementID) {
	var priceElement = dojo.byId(priceElementID);

	if (priceElement == null) {
		return;
	}

	var price = parseInt(priceElement.firstChild.data);

	if (String(price) == 'NaN') {
		priceElement.value = '';
		updateContent(priceElementID, 0);
		return;
	}

	if (isAdd) {
		price += stadiumPrices[productName][productLevel + 1];
	}
	else {
		price -= stadiumPrices[productName][productLevel + 1];
	}

	if (price != null && price > 0) {
		updateContent(priceElementID, price);
	}
	else {
		updateContent(priceElementID, 0);
	}
}

/* UpdateContent */

function updateContent(updateElementID, content) {
	var updateElement = dojo.byId(updateElementID);

	if (updateElement != null && content != null) {
		updateElement.firstChild.data = content;
	}
}

/* Show StadiumPeripherie */

function showStadiumPeripherie(source) {
	showOverlay();

	var divElement = dojo.doc.createElement('div');

	dojo.attr(divElement, 'id', 'StadiumPeripherie');

	dojo.connect(divElement, 'click', hideStadiumPeripherie);

	var imageElement = dojo.doc.createElement('img');

	imageElement.src = source;

	dojo.style(imageElement, 'width', '100%');

	divElement.appendChild(imageElement);

	dojo.body().appendChild(divElement);

	var pageSize = getPageSize();

	var top = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

	dojo.style(divElement, {
		'position': 'absolute',
		'top': top + 'px',
		'left': '0px',
		'paddingTop': '150px',
		'height': (pageSize[1] - imageElement.height) + 'px',
		'width': '100%'
		}
	);
}

function hideStadiumPeripherie(event) {
	if (event == null || event.target.getAttribute('id') == 'StadiumPeripherie') {
		var element = dojo.byId('StadiumPeripherie');

		if (element != null) {
			element.parentNode.removeChild(element);
		}

		hideOverlay();
	}
}

function updatePercent(elementID, percent, percentStep) {
	var percentElement = dojo.byId(elementID);
	var newWidth = percent;

	if (percentElement != null) {
		newWidth = percent - percentStep;

		dojo.style(percentElement, 'width', String(newWidth).substr(0, 8) + '%');
	}
	if (percent && percent >= 0) {
		window.setTimeout("updatePercent('" + elementID + "', " + newWidth + ", " + percentStep + ");", /*59500*/1000);
	}
}

function watch(elementID, timestamp) {
	var newTimestamp = timestamp + 1;

	var newTime = new Date();

	newTime.setTime(String(newTimestamp) + String(999));

	var element = dojo.byId(elementID);

	if (element != null) {
		var hours = newTime.getHours();

		if (hours < 10) {
			hours = '0' + String(hours);
		}

		var minutes = newTime.getMinutes();

		if (minutes < 10) {
			minutes = '0' + String(minutes);
		}

		var seconds = newTime.getSeconds();

		if (seconds < 10) {
			seconds = '0' + String(seconds);
		}

		element.firstChild.nodeValue = hours + ':' + minutes + ':' + seconds;
	}

	window.setTimeout("watch('" + elementID + "', " + newTimestamp + ");", 1000);
}

function updateTimeAtTimeHTML(suffix, countdown) {
	var daysElement = dojo.byId('TimeDays' + suffix);
	var hoursElement = dojo.byId('TimeHours' + suffix);
	var minutesElement = dojo.byId('TimeMinutes' + suffix);
	var secondsElement = dojo.byId('TimeSeconds' + suffix);
	
	var finish = false;

	if (getValueByFirstChild(daysElement) == 0 &&
		getValueByFirstChild(hoursElement) == 0 &&
		getValueByFirstChild(minutesElement) == 0 &&
		getValueByFirstChild(secondsElement) == 1) {
		finish = true;
	}

	if (secondsElement != null) {
		var seconds = getReduceValueByFirstChild(secondsElement);

		if (seconds < 0) {
			if (minutesElement != null) {
				var minutes = getReduceValueByFirstChild(minutesElement);
	
				if (minutes < 0) {
					if (hoursElement != null) {
						var hours = getReduceValueByFirstChild(hoursElement);
		
						if (hours < 0) {
							if (daysElement != null) {
								var days = getReduceValueByFirstChild(daysElement);
			
								if (days < 0) {
									days = 0;
								}
								
								if (countdown == true && days < 10) {
									days = '0' + String(days);
								}

								setValueByFirstChild(daysElement, days);
								
								hours = 23;
							} else {
								hours = 0;
							}
						}

						if (countdown == true && hours < 10) {
							hours = '0' + String(hours);
						}
						
						setValueByFirstChild(hoursElement, hours);
						
						minutes = 59;
					} else {
						minutes = 0;
					}
				}
				
				if (countdown == true && minutes < 10) {
					minutes = '0' + String(minutes);
				}
				
				setValueByFirstChild(minutesElement, minutes);
				
				seconds = 59;
			} else {
				seconds = 0;
			}
		}

		if (countdown == true && seconds < 10) {
			seconds = '0' + String(seconds);
		}
		
		setValueByFirstChild(secondsElement, seconds);
	}

	if (finish == false) {
		window.setTimeout("updateTimeAtTimeHTML('" + suffix + "', " + countdown + ");", 1000);
	}
}

function getValueByFirstChild(element) {
	return element.firstChild.data;
}

function getReduceValueByFirstChild(element) {
	value = parseInt(getValueByFirstChild(element), 10);

	if (!isNaN(value)) {
		return value - 1;
	}

	return null;
}

function setValueByFirstChild(element, value) {
	element.firstChild.data = value;
}

function filterTransfermarket(filter, page, sort) {
	var parameter = '?';

	if (filter.length > 0) {
		parameter += 'filter=' + filter;
	}

	if (page.length > 0) {
		if (parameter.length > 1) {
			parameter += '&';
		}

		parameter += 'page=' + page;
	}

	if (sort != null && sort.length > 0) {
		if (parameter.length > 1) {
			parameter += '&';
		}

		parameter += 'sort=' + sort;
	}

	window.location.href = window.location.pathname + parameter;
}

var checkBoxArray = new Array();

function addSelectionToArray(checkBoxItem)
{
	if(checkBoxItem)
	{
		var arrayLength = checkBoxArray.length;
		var type = checkBoxItem.getAttribute('type');
		if (type && type == 'checkbox' && checkBoxItem.checked == true)
		{
			if (arrayLength < 5)
			{
				checkBoxArray[arrayLength] = checkBoxItem;
			}
			else
			{
				var lastitem = checkBoxArray[arrayLength-1];
				lastitem.checked = false;
				checkBoxArray[arrayLength-1] = checkBoxItem;
			}
		}
		else if(type && type == 'checkbox' && checkBoxItem.checked == false)
		{
			var nArray = new Array();
			var count = 0;
			for(var i = 0; i < arrayLength; i++)
			{
				var oldItem = checkBoxArray[i];
				if (oldItem != checkBoxItem)
				{
					nArray[count] = oldItem;
					count++;
				}
			}
			checkBoxArray = nArray;
		}
	}
}

function doLinkAction(url)
{
	if (url != null && url.length > 0)
	{
		window.location.href = url;
	}
}

var termPopup = null;

function showTerms() {
	var params = 'height=706,width=780,top=150,left=150,location=no,menubar=no,scrollbars=yes,status=yes,toolbar=no';

	if (termPopup == null || (termPopup != null && termPopup.closed)) {
		termPopup = window.open('terms.php', '', params);
	}

	termPopup.focus();
}

var imprintPopup = null;

function showImprint() {
	var params = 'height=706,width=780,top=150,left=150,location=no,menubar=no,scrollbars=yes,status=yes,toolbar=no';

	if (imprintPopup == null || (imprintPopup != null && imprintPopup.closed)) {
		imprintPopup = window.open('imprint.php', '', params);
	}

	imprintPopup.focus();
}
