function addGroupAsExpert(ideaid, groupid) {
	if (groupid != 0) {
		window.location = 'addEvaluationGroup.php?idea=' + ideaid + '&group=' + groupid;
	}
}

function BindTooltip(event, element, id_of_tag_element, max_width) {
	var element = jQuery(element);
	
	if (element.data('tooltip_initiated')) {
		return false;
	}	

	element.data('tooltip_delay', null);
	
	element	
	.bind('mouseenter', function(event_mouseenter) {
		var delay = window.setTimeout(function() {
			TagToTip(event_mouseenter, element, id_of_tag_element, max_width);
		}, 500);
		element.data('tooltip_delay', delay);
	})
	.bind('mouseleave', function(event_mouseleave) {
		UnTip(event_mouseleave, jQuery(this));
	})
	.data('tooltip_initiated', true);

	var delay = window.setTimeout(function() {
		TagToTip(event, element, id_of_tag_element, max_width);
	}, 500);
	element.data('tooltip_delay', delay);
}

function TagToTip(event, element, id_of_tag_element, max_width) {
	if (jQuery(element).data('tooltip_element')) {
		return false;
	}

	// Create a new ID for the cloned tooltip element and store it in the event causing element.
	var timestamp = new Date();
	var tooltip_element = jQuery('#' + id_of_tag_element);
	var new_id = tooltip_element.attr('id') + '-' + timestamp.getTime();
	var element = jQuery(element).data('tooltip_element', new_id);

	var body_element = jQuery('body').eq(0);

	/*
	 * Determine the width of the tooltip element.
	 */ 
	if (max_width == null) {
		max_width = 400;
	}
	var tooltip_width = Math.min(max_width, tooltip_element.width());

	var new_tooltip_element = tooltip_element.clone();

	new_tooltip_element
	.attr('id', new_id)
	.appendTo(body_element)
	.width(tooltip_width + 'px');

	pos = element.offset();
	if (event.pageX == undefined) {
		event.pageX = pos.left; // + document.body.scrollLeft;
	}
	if (event.pageY == undefined) {
		event.pageY = pos.top; // + document.body.scrollTop; //event.clientY + document.body.scrollTop;
	}
	
	/*
	 * Calculate the offset.
	 * The tooltip element is shown bottom right if there is enough room.
	 * Otherwise the tooltip element is show top left.
	 */
	var offset_top = 15;
	var offset_left = 15;
	var effect_options = { 'direction': 'left' };
	if ((jQuery(window).width() - event.pageX) < new_tooltip_element.width()) {
		offset_top = - 10 - new_tooltip_element.height();
		offset_left = - 10 - new_tooltip_element.width();
		effect_options = { 'direction': 'right' };
	}

	element.data('effect_options', effect_options);
	var css_styles = {
		'position': 'absolute',
		'top': (parseInt(event.pageY) + offset_top) + 'px',
		'left': (parseInt(event.pageX) + offset_left) + 'px'
	};
	
	new_tooltip_element
	.css(css_styles)
	.show('slide', effect_options, 500, function() {
		element
		.bind('mousemove', function(event_mousemove) {
			var css_styles = {};
			css_styles['top'] = (parseInt(event_mousemove.pageY) + offset_top) + 'px';
			css_styles['left'] = (parseInt(event_mousemove.pageX) + offset_left) + 'px';

			new_tooltip_element.css(css_styles);
		});		
	})	
	.bind('mouseover', function(event_mouseover) {
		jQuery(this).hide('slide', effect_options, 500, function() {
			jQuery(this).remove();
		});
	});
}

function UnTip(event, element) {
	var element = jQuery(element);

	if (element.data('tooltip_delay')) {
		window.clearTimeout(element.data('tooltip_delay'));

		element.removeData('tooltip_delay');
	}

	var id_of_tag_element = element.data('tooltip_element');
	var effect_options = element.data('effect_options');
	var tooltip_element = jQuery('#' + id_of_tag_element);
	
	element.unbind('mousemove');

	tooltip_element.hide('slide', effect_options, 500, function() {
		jQuery(this).remove();
		element.removeData('tooltip_element')
	});
}

function reloadPage() {
	window.location.reload();

	return false;
}

function loadNewThemes(action, value) {
	if(action == "add"){
		window.location = "pool.php?addCFI="+value;
	}

	if(action == "delete"){
		window.location = "pool.php?deleteCFI="+value;
	}		

	return false;
}

function closeWindow() {
	window.close();

	return false;
}

function complete_updateImagePool(response_obj) {
	window.opener.updateMainImage(response_obj.get('img_filename'));
	window.close();
}

function complete_makeIdeaOfMonth() {
	alert("Changes saved!");

	hideElement("iom1");
	showElement("iom2");
}

function complete_submitExpertEval() {
	var result_image = $('evalresultimage');
	if (result_image != null) {
		refreshImage(result_image);
	}
	
	hideElement('evalform');
	showElement('evalresult');
	stylePage();
}

function refreshImage(img_element) {
	img_element = $(img_element);
	
	var img_src = img_element.readAttribute('src');

	var query_hash = new Hash(img_src.toQueryParams());

	var timestamp = new Date();
	query_hash.set('js_refresh_flag', timestamp.getTime());

	var new_src = img_src.substr(0, img_src.indexOf('?')) + '?' + query_hash.toQueryString();

	img_element.writeAttribute('src', new_src);
}

function completeSavingIdea(result_obj) {
	openIdea(result_obj.get('idea_id'), result_obj.get('user_id'), global_idea_dest);

	return true;
}

function completeSavingDraftIdea(result_obj) {
	alert(getLangValue('enterIdea.php', 'save_confirm'));
	idea_id = result_obj.get('idea_id')
	$('enteridea-id').value = idea_id;
		
	return true;
}

function checkAdmin(val) {
	if (val) {
		if (!confirm(unescape("Wirklich Administrator-Rechte vergeben?"))) document.user.admin.checked=false;
	}
}

function debug(message, debug_flag) {
	if (debug_flag == null) {
		var debug_flag = (global_js_debug_flag || global_debug_flag);
	}

	var debug_element = $('debug-js');
	if (debug_element != null) {
		if (debug_flag) {
			debug_element.innerHTML += '<p style="margin-bottom:20px;">' + message + '</p>';
		}
	}

	debug_flag = null;
}

function debugAjax(message) {
	var debug_flag = (global_ajax_debug_flag || global_debug_flag);
	debug(message, debug_flag);
}

function getPixelValue(style_string) {
	var return_value = 0;
	
	if (!isNaN(parseInt(style_string))) {
		return_value = parseInt(style_string);
	}

	return return_value;
}

function objectToHash(variable, initial) {
	if ((initial == true) && (variable == null)) {
		return new Hash();
	} else {
		if (typeof variable == 'object') {
			variable = new Hash(variable);
	
			variable.each(function(pair) {
				variable.set(pair.key, objectToHash(pair.value));
			});
		}
	
		return variable;
	}
}

function debugJavascriptElementFunctions(event) {
	var element = $(event.element());

	var text = '';
	while (element != this) {
		var tmp_text = '';
		if (element.onmouseover != null) {
			tmp_text += '<span class="bold">onmouseover:</span> ' + element.onmouseover + '<br />';
		}
		if (element.onmouseout != null) {
			tmp_text += '<span class="bold">onmouseout:</span> ' + element.onmouseout + '<br />';
		}
		if (element.onclick != null) {
			tmp_text += '<span class="bold">onclick:</span> ' + element.onclick + '<br />';
		}
		if (element.onsubmit != null) {
			tmp_text += '<span class="bold">onsubmit:</span> ' + element.onsubmit + '<br />';
		}

		if (tmp_text != '') {
			text += '<p style="padding-bottom:10px;">';
			text += this.nodeName + ' ID:<span class="italic">' + element.identify() + '</span><br />';
			text += tmp_text;
			text += '</p>';
		}

		element = $(element.parentNode);
	}

	var debug_element = $('js-function-debug');
	if (debug_element != null) {
		debug_element.update(text);
		
	}
}

function observeJavascriptElementFunctions(flag) {
	return false;
	if (flag) {
		var elements = $$('div', 'p', 'a', 'img', 'form', 'table', 'tr', 'td');
		elements.each(function(element) {
			element.observe('mouseover', debugJavascriptElementFunctions);
		});
	}
}

function initPage() {
	observeJavascriptElementFunctions();
}

function stylePage(config_hash) {
	if (config_hash == null) {
		config_hash = new Hash();
	}

	addSelektorStyles();
	addStyleFunctions();
	stretchElements();
	equalizeElements('same-height-1', config_hash.get('do_not_equalize'));
	equalizeElements('same-height-2', config_hash.get('do_not_equalize'));
	centerElementsVertical();
	centerElementsVerticalAbsolute();
	centerElementsVerticalViewport();
	centerElementsVerticalViewportScroll();
}

function checkFixedPosition(element, target_y) {
	var viewport_scroll_offsets = document.viewport.getScrollOffsets();

	if (element.style.top != (viewport_scroll_offsets.top + target_y)) {
		var target_y_str = (viewport_scroll_offsets.top + target_y) + 'px';
		new Effect.Morph(element, {
			style: { 'top': target_y_str },
			duration: 0.4,
			queue: {
				position: 'end',
				scope: 'fixed-container-' + element.id,
				limit: 1
			}
		});
	}
}

function executeFunction(name, parameters) {
	var tmp_encoded_params = new Array();

	if (Object.isString(parameters)) {
		tmp_encoded_params.push(Object.toJSON(parameters));
	} else if (Object.isArray(parameters)) {
		parameters.each(function(pair) {
			if (pair.value == null) {
				tmp_encoded_params.push('null');
			} else {
				tmp_encoded_params.push(Object.toJSON(pair.value));
			}
		});
	} else if (Object.isHash(parameters)) {
		parameters.each(function(item) {
			if (item == null) {
				tmp_encoded_params.push('null');
			} else {
				tmp_encoded_params.push(Object.toJSON(item));
			}
		});
	}

	var script_string = name + '(' + tmp_encoded_params.join(',') + ')';
	debug('Executing: ' + script_string);
	var script_string = '<script>' + script_string + '</script>';
	script_string.evalScripts();
}

function startHashInterval() {
	current_hash = window.location.hash;
	ajax_history = window.setInterval(function() {
		if (window.location.hash != current_hash) {
			debug('Hash has changed: BACK or NEXT button has been used.');

			current_hash = window.location.hash;
		}
	}, 200);
}

function stopHashInterval() {
	window.clearInterval(ajax_history);
}

function tabIsActive(params) {
	var element = $(params.get('box') + '-content-' + params.get('tab'));
	if (element != null) {
		if (element.visible()) {
			return true;
		}
	}

	return false;
}

function getCleanedHeight(element_id) {
	var element = $(element_id);

	var height = 0;

	if (element != null) {
		height = element.getHeight();
		height = height - getHeightDirt(element);
	}

	return height;
}

function getHeightDirt(element_id) {
	var element = $(element_id);

	var height = 0;

	if (element != null) {
		height = height + getPixelValue(element.getStyle('padding-top'));
		height = height + getPixelValue(element.getStyle('padding-bottom'));
		height = height + getPixelValue(element.getStyle('margin-top'));
		height = height + getPixelValue(element.getStyle('margin-bottom'));
		if (getPixelValue(element.getStyle('border-top-width')) > 0) {
			if (element.getStyle('border-top-style') != 'none') {
				height = height + getPixelValue(element.getStyle('border-top-width'));
			}
		}
		if (getPixelValue(element.getStyle('border-bottom-width')) > 0) {
			if (element.getStyle('border-bottom-style') != 'none') {
				height = height + getPixelValue(element.getStyle('border-bottom-width'));
			}
		}
	}

	return height;
}

function morphElement(element_id, to_height, keep_height, busy_element, busy_layer) {
	var morph_busy_layer = false;

	var element = $(element_id);
	if (element == null) {
		debug('Morphing element failed: ' + element_id);
		return false;
	}

	var tmp_element = element.up();
	while (tmp_element) {
		if (tmp_element.nodeName == 'BODY') {
			break;
		}
		if (tmp_element.style.height != '') {
			tmp_element.style.height = 'auto';
		}
		tmp_element = tmp_element.up();
	}

	var from_height = getCleanedHeight(element);

	var seconds_per_pixel = 1/200;
	var pixels = from_height - to_height;
	var tmp_duration = Math.max(seconds_per_pixel * Math.abs(pixels), 0.5);
	tmp_duration = Math.min(tmp_duration, 1.25);

	if (!morph_busy_layer) {
		if (busy_element != null) {
			setElementToIdle(busy_element);
		}
	}

	new Effect.Morph(element, {
		style: { height: to_height + 'px' },
		duration: tmp_duration,
		afterFinish: function() {
			debug(element.identify() + ' keepheight: ' + keep_height);
			if (keep_height) {
				element.style.height = to_height + 'px';
			} else {
				element.style.height = 'auto';
			}
			element.style.overflow = 'visible';

			stylePage();
		}
	});

	if (morph_busy_layer) {
		if (busy_layer != null) {
			var busy_layer_height = getCleanedHeight(busy_layer) - pixels;
		
			new Effect.Morph(busy_layer, {
				style: { height: busy_layer_height + 'px' },
				duration: tmp_duration,
				afterFinish: function() {
					if (busy_element != null) {
						setElementToIdle(busy_element);
					}
				},
				afterUpdate: function() {
					adjustBusyLayer(busy_layer);
				}
			});
		}
	}

}

function morphTabs(from_element, to_element) {
	from_element = $(from_element);
	if (from_element == null) {
		return false;
	}

	to_element = $(to_element);
	if (to_element == null) {
		return false;
	}

	debug('MORPHING TABS ' + from_element.identify() + ' to ' + to_element.identify());


	var same_height_elements = getSameHeightElements(to_element);


	var old_height = getCleanedHeight(from_element);
	to_element.style.height = old_height + 'px';
	to_element.style.overflow = 'hidden';

	var tmp_wrapper_element = new Element('div');
	tmp_wrapper_element.update(to_element.innerHTML);
	to_element.update(tmp_wrapper_element);

	showElement(to_element);
	hideElement(from_element);

	var init_page_config = new Hash();
	init_page_config.set('do_not_equalize', same_height_elements);

	stylePage(init_page_config);

	var to_height = getCleanedHeight(tmp_wrapper_element);

	to_element.update(tmp_wrapper_element.innerHTML);

	busy_layer = setElementToBusy(to_element);


	var current_heights_hash = new Hash();
	var original_heights_hash = new Hash();
	
	same_height_elements.each(function(same_height_element) {
		var current_height = getCleanedHeight(same_height_element);
		var tmp_height = same_height_element.getStyle('height');
		current_heights_hash.set(same_height_element.identify(), current_height);
		same_height_element.style.height = 'auto';
		original_heights_hash.set(same_height_element.identify(), getCleanedHeight(same_height_element));
		same_height_element.style.height = current_height + 'px';
	});

	var original_heights_hash_visibleAfter = original_heights_hash.clone();
	original_heights_hash_visibleAfter.unset(from_element.identify());

	var original_heights_hash_visibleBefore = original_heights_hash.clone();
	original_heights_hash_visibleBefore.unset(to_element.identify());

	var max_height = 0;
	if (original_heights_hash_visibleAfter.size() > 0) {
		max_height = original_heights_hash_visibleAfter.values().max();
	}

	debug('FROM: ' + old_height + ' - TO: ' + to_height + ' - MAX: ' + max_height);

	var new_height = Math.max(max_height, to_height);

	var keep_height = false;
	if (to_height != new_height) {
		keep_height = true;
	} else {
		keep_height = false;
	}

	morphElement(to_element, new_height, keep_height, to_element, busy_layer);
}

function morphContent(element, content, busy_element, busy_layer) {
	element = $(element);
	if (element == null) {
		return false;
	}

	debug('MORPHING CONTENT ' + element.identify());

	
	if (busy_element == null) {
		busy_element = element;
		busy_layer = setElementToBusy(busy_element);
	}

	var old_height = getCleanedHeight(element);
	element.style.height = old_height + 'px';
	element.style.overflow = 'hidden';

	var tmp_wrapper_element = new Element('div');
	tmp_wrapper_element.update(content);
	element.update(tmp_wrapper_element);

	stylePage();

	var to_height = getCleanedHeight(tmp_wrapper_element);

	element.update(tmp_wrapper_element.innerHTML);

	var current_heights_hash = new Hash();
	var original_heights_hash = new Hash();
	
	var same_height_elements = getSameHeightElements(element);
	same_height_elements.each(function(same_height_element) {
		var current_height = getCleanedHeight(same_height_element);
		current_heights_hash.set(same_height_element.identify(), current_height);
		same_height_element.style.height = 'auto';
		original_heights_hash.set(same_height_element.identify(), getCleanedHeight(same_height_element));
		same_height_element.style.height = current_height + 'px';
	});

	var original_heights_hash_visible = original_heights_hash.clone();
	original_heights_hash_visible.unset(element.identify());

	var max_height = 0;
	if (original_heights_hash_visible.size() > 0) {
		max_height = original_heights_hash_visible.values().max();
	}

	var new_height = Math.max(max_height, to_height);

	var keep_height = false;
	if (to_height != new_height) {
		keep_height = true;
	} else {
		keep_height = false;
	}

	morphElement(element, new_height, keep_height, busy_element, busy_layer);
}

function showTabConditional(box, tab, function_name) {
	if (typeof window[function_name] == "function") {
		if (window[function_name]() == true) {
			showTab(box, tab);
		}
	}
}

function showTab(box, tab) {
	var tab_element = $(box + '-content-' + tab);
	if (tab_element == null) {
		return false;
	}
	if (tab_element.visible()) {
		return false;
	}


	global_active_tabs.set(box, tab);
	debug('Showing box "' + box + '" and tab "' + tab + '"');


	var menu_elements = $(box + '-menu').select('.tabbox-menuitem-active');
	menu_elements.each(function(item) {
		item.removeClassName('tabbox-menuitem-active');
	});

	$(box + '-menu-' + tab).addClassName('tabbox-menuitem-active');


	var visible_content_elements = new Array();
	var content_elements = $(box + '-container').select('.tabbox-content');
	content_elements.each(function(item) {
		if (item.visible()) {
			visible_content_elements.push(item);
		}
	});

	var morph = false;

	visible_content_elements.each(function(item) {
		if (morph) {
			debug('MORPH from ' + item.identify() + ' to ' + tab_element.identify());
			morphTabs(item, tab_element);			
		} else {
			item.hide();
		}
	});

	if (!morph) {
		tab_element.show();
		stylePage();
	}

	if (global_track_tabs) {
		if (global_current_page != null) {
			trackTabs(global_current_page, box, tab);
		}
	}
	
	if(box=='enteridea') {
		var parameters = new Hash();
		var text_errors = false;
		var data_elements = $$('textarea.submitdata, input.submitdata');
		data_elements.each(function(item) {
			parameters.set(item.name, item.value);
			if (item.hasClassName('mandatory') && (item.value.length == 0)) {
				text_errors = true;
			}
		});
		if(text_errors == false) {
			//alert('ID: '+$('enteridea-id').value);
			//submitData2(tab, $('enteridea-id').value, false);
			//alert('ja');
		} else {
			//alert('nein');
		}
	}
	
	if(box=="idea") {
		if(tab=="eval" || tab=="comment") {
			showTNC();
		}
	}

	return false;
}

function showAffectedElement(element_id) {
	var element_id_matches = element_id.match(/(.*)-reload-content-(.*)/);
	if (Object.isArray(element_id_matches) && (element_id_matches.size() == 3)) {
		showTab(element_id_matches[1], element_id_matches[2]);
	}
}

function isReloadContentID(element_id) {
	var element_id_matches = element_id.match(/(.*)-reload-content-(.*)/);
	if (Object.isArray(element_id_matches) && (element_id_matches.size() == 3)) {
		return true;
	}
	return false;
}

function isContentID(element_id) {
	var element_id_matches = element_id.match(/(.*)-content-(.*)/);
	if (Object.isArray(element_id_matches) && (element_id_matches.size() == 3)) {
		return true;
	}
	return false;
}

function getContentID(element_id) {
	var element_id_matches = element_id.match(/(.*)-reload-content-(.*)/);
	if (Object.isArray(element_id_matches) && (element_id_matches.size() == 3)) {
		return element_id_matches[1] + '-content-' + element_id_matches[2];
	}
	return null;
}

function getParentTab(element_id) {
	if (element_id != null) {
		if (!isReloadContentID(element_id) && isContentID(element_id)) {
			return element_id;
		}
		var element = $(element_id);
		if (element != null) {
			var tmp_element = element;
			while (tmp_element != null) {
				var tmp_element_id = $(tmp_element).identify();
				if (isReloadContentID(tmp_element_id)) {
					return getContentID(tmp_element_id);
				}
				tmp_element = tmp_element.parentNode;
			}
		}
	}

	return null;
}

function getBoxTab(element_id) {
	return element_id.replace(/-reload-content/, '');
}

function removeElementOverlay(element_id, width, height) {
	var element = $(element_id);
	if (element != null) {
		var overlay_elements = element.select('.ajax-overlay');
		overlay_elements.each(function(tmp_element) {
			tmp_element.remove();
		});
	}
}

function adjustBusyLayer(busy_layer) {
	var busy_parent = $(busy_layer.parentNode);

	if (busy_parent != null) {
		var img_elements = busy_layer.select('img.ajax-indicator');
		img_elements.each(function(item) {
			adjustBusyLayerIndicatorImage(busy_layer, item);
		});
	}
}

function adjustBusyLayerIndicatorImage(div_element, img_element) {
	var div_height = div_element.getHeight();
	var div_width = div_element.getWidth();
	var minimum = Math.min(div_height, div_width);
	var minimum = Math.min(minimum, 50);

	img_element.style.width = minimum + 'px';
	img_element.style.height = minimum + 'px';
	img_element.style.marginTop = Math.round((div_height/2) - (minimum/2)) + 'px';
}

function setElementToDisabled(element) {
	var element = jQuery(element);

	var busy_overlay = jQuery('<div class="busy-overlay"></div>')
	.css('width', element.width())
	.css('height', element.height());

	element.data('position', element.css('position'));
	element.css('position', 'relative');
	element.append(busy_overlay);
}

function setElementToEnabled(element) {
	var element = jQuery(element);

	jQuery('div.busy-overlay', element).remove();

	element.css('position', element.data('position'));
}

function setElementToBusy(element_id) {
	var element = $(element_id);
	if (element != null) {
		var width = element.getWidth() + 'px';
		var height = element.getHeight() + 'px';

		var div_element = new Element('div', { 'class': 'ajax-indicator', 'style': 'height:' + height + '; width:' + width + ';' });
		var img_element = new Element('img', { 'class': 'ajax-indicator', 'src': BASEURL + 'images/indicators/ajax_loader_4_DF0000_FFFFFF.gif' });

		div_element.appendChild(img_element);

		new Effect.Opacity(div_element, { from: 1.0, to: 0.5, duration: 0.0 });
		
		element.appendChild(div_element);

		adjustBusyLayerIndicatorImage(div_element, img_element);

		return div_element;
	}

	return null;
}

function setElementToIdle(element_id) {
	var element = $(element_id);
	if (element != null) {
		var indicator_elements = element.select('.ajax-indicator');
		indicator_elements.each(function(tmp_element) {
			tmp_element.remove();
		});
	}
}

function trackTabs(page, box, tab) {
	var parameters = new Hash();
	parameters.set('page', page);
	parameters.set('box', box);
	parameters.set('tab', tab);

	ajaxFunction(BASEURL + 'actions/trackTabs.php', parameters);

	return false;
}

function highlightElement(element, classname) {
	var element = $(element);
	if (element != null) {
		if (!$(element).hasClassName()) {
			$(element).addClassName(classname);
		}
	}
}

function dehighlightElement(element, classname) {
	var element = $(element);
	if (element != null) {
		$(element).removeClassName(classname);
	}
}

function hideElement(element, clear) {
	var element = $(element);

	jQuery(element).hide();
	
	if (clear === true) {
		jQuery(element).empty();
	}
}

function showElement(element) {
	var element = $(element);

	jQuery(element).show();
}

function toggle(element) {
	var element = $(element);
	if (element != null) {
		if (element.visible()) {
			element.hide();
		} else {
			element.show();
		}
	}

	return false;
}

function toggleRelatedCheckbox(element, element_to_show) {
	element = $(element);

	if (element != null) {
		var related_element = $(element_to_show);
		if (related_element != null) {
			related_element.show();
		}
	}
}

function markRelatedCheckboxes(element, elements) {
	element = $(element);

	if (Object.isArray(elements)) {
		elements.each(function(item) {
			item.checked = element.checked;
		});
	}
}

function getSameHeightElements(element) {
	var same_height_elements = new Array();

	var same_height_classes = getSameHeightClasses(element);
	same_height_classes.each(function(tmp_class) {
		var tmp_elements = $$('.' + tmp_class);
		tmp_elements.each(function(item) {
			same_height_elements.push(item);
		});
	});

	return same_height_elements;
}

function getSameHeightClasses(element) {
	var same_height_classes = new Array();
	
	var element_classes = $w(element.className);
	element_classes.each(function(tmp_class) {
		if (tmp_class.substr(0,20) == 'same-height-element-') {
			same_height_classes.push(tmp_class);
		}
	});

	return same_height_classes;
}

function refreshTrackingGraphs(page) {
	var img_element = $('statistics-tracking-graph-bar');
	if (img_element != null) {
		img_element.src = 'jpgraph/reportingStatisticsBar.php?statistics_type=tracking&page=' + page;
	}

	var img_element = $('statistics-tracking-graph-line');
	if (img_element != null) {
		img_element.src = 'jpgraph/reportingStatisticsLine.php?statistics_type=tracking&page=' + page;
	}
}

function showMemberDetails(target_id, viewer, src_element) {
	if (viewer > 0) {
		storeVisitor(target_id,viewer);
	}
	
	loadPage('member.php?id=' + target_id, 'window');
	return false;

	// Add member details div if necessary
	if (jQuery('#member-details').size() == 0) {
		var member_details_element = jQuery('<div id="member-details" class="center-vertical-viewport-scroll" style="display:none;"></div>');
		jQuery('body').eq(0).append(member_details_element);
		//jQuery('#member-details').dialog();
		/*jQuery('#member-details').dialog("option","width",400);
		jQuery('#member-details').dialog("option","height",580);*/
		centerElementVerticalViewportScroll(member_details_element);
	}
	
	var parameters = new Hash();
	parameters.set('userid', target_id);

	ajaxFunction(BASEURL + 'displayMemberDetailsLayer.php', parameters, 'member-details');

	/*if(!jQuery('#member-details').dialog('isOpen')) {
		jQuery('#member-details').dialog('open');
		jQuery('#member-details').dialog("option","width",400);
		jQuery('#member-details').dialog("option","height",580);
	}*/
	if (true) {
		var member_details_element = $('member-details');
		if (member_details_element != null) {
			new Effect.Appear(member_details_element);
		}
	} else {
		showElement('member-details');
	}

	return false;
}

function hideMemberDetails() {
	var element = $('member-details');
	if (element != null) {
		element.innerHTML = '';
		element.hide();
	}
}

function getTopWindow() {
	var tmp_window = window;
	//while (tmp_window.opener != null) {
	//	tmp_window = tmp_window.opener;
	//}

	return tmp_window;
}

function loadPage(page, dest) {
	if (dest == 'popup') {
		window.open(page, "", "width=800,height=600,left=200,top=200,dependent=yes,scrollbars=yes");
	} else if ((dest == 'opener') || (dest == 'parent')) {
		window.opener.location.href = page;
	} else if (dest == 'top') {
		getTopWindow().location.href = page;
	} else {
		window.location.href = page;
	}

	return false;
}

function loadParentPage(page) {
	loadPage(page, 'opener');
}

function loadTopPage(page) {
	loadPage(page, 'top');
}

function openIdea(ideaid, userid, dest) {
	storeIdeaVisitor(ideaid, userid, function() {
		if (dest == "popup") {
			window.open(BASEURL + "idea.php?id=" + ideaid, "", "width=840,height=690,left=100,top=30,dependent=yes,scrollbars=yes,resizable=yes");	
		}

		if (dest == "window") {
			window.location = BASEURL + "idea.php?id=" + ideaid;
		}
	});

	return false;
}

function editIdea(id) {
	getTopWindow().location.href = BASEURL + "enterIdea.php?tabs[]=enteridea-0&id=" + id + "&edit=1";

	// getTopWindow().alert('Sie befinden sich nun im Bearbeitungsmodus.');
}

function editIdeaCat(id) {
	getTopWindow().location = BASEURL + "enterIdea.php?tabs[]=enteridea-2&id=" + id + "&edit=1";
	//window.close();

	// getTopWindow().alert('Sie befinden sich nun im Bearbeitungsmodus.');
}

function getLangValue(page, key) {
	var result = key;

	page_language_data = language_hash.get(page);

	if (page_language_data != null) {
		var language_data = page_language_data.get(key);
		if (language_data != null) {
			result = unescape(language_data);
		}
	}

	return result;
}

function storeProfile() {
	var parameters = new Hash();
	parameters.set('userdata', true);
	parameters.set('about', getFormValue('about'));
	parameters.set('department', getFormValue('department'));
	parameters.set('country', getFormValue('country'));
	parameters.set('telephone', getFormValue('telephone'));
	val=0;
	if($('newsletter').checked) val=1;
	parameters.set('newsletter', val);

	storeProfileData(parameters);
}

function storeNotificationSettings(user_id) {
	var comments = 0;
	if (document.notifications.comments.checked) {
		comments = 1;
	}

	var comment_childs = 0;
	if (document.notifications.comment_childs.checked) {
		comment_childs = 1;
	}

	var pinboard = 0;
	if (document.notifications.pinboard.checked) {
		pinboard = 1;
	}

	storeNotifications(user_id, comments, comment_childs, pinboard);
}

function storeVersion(step, idea) {
	var success = submitData(step, idea, true);

	return false;
}

function getFormValue(id) {
	var value = '';

	if (id != null) {
		var form_element = $(id);
		if (form_element != null) {
			value = form_element.value;
		}
	}

	return value;
}

function getFormSelectValue(id) {
	var value = '';

	if (id != null) {
		var form_element = $(id);
		if (form_element != null) {
			value = form_element.options[form_element.selectedIndex].value;
		}
	}

	return value;
}

function getParentForm(element) {
	element = $(element);
	if (element.nodeName != 'FORM') {
		element = element.up('form');
	}

	return element;
}

function sumitFormACL(element, conflicts) {
	var submit_allowed = true;
	if (conflicts.length > 0) {
		submit_allowed = confirm(getLangValue('global', 'confirm_acl_conflicts'));
	}

	if (submit_allowed) {
		submitForm(element);
	}
}

/**
 * This method is used for submitting a form element.
 * 
 * @param element
 * @return false
 */
function submitForm(element) {
	element = getParentForm(element);
	if (element != null) {
		var tmp_button = jQuery('<input type="submit" style="display:none;" />');
		jQuery(element).append(tmp_button);
		tmp_button.click();
		tmp_button.remove();
	}

	return false;
}

/**
 * Here are some keycodes:
 * 
 * backspace		8
 * tab				9
 * enter			13
 * shift			16
 * ctrl				17
 * alt				18
 * pause/break		19
 * caps lock		20
 * escape			27
 * page up			33
 * page down		34
 * end				35
 * home				36
 * left arrow		37
 * up arrow			38
 * right arrow		39
 * down arrow		40
 * insert			45
 * delete			46
 */
function submitFormOnKeycode(element, event, keycode) {
	var form_element = getParentForm(element);
	if (form_element == null) {
		return false;
	}

	if (event != null) {
		if (event.keyCode == keycode) {
			submitForm(form_element);
		}
	}

	return false;
}

function submitFormOnStringLength(element, len) {
	var form_element = getParentForm(element);
	if (form_element == null) {
		return false;
	}

	if ((element.value.length >= len) && (jQuery(element).data('input_length') != element.value.length)) {
		submitForm(form_element);
	}

	jQuery(element).data('input_length', element.value.length);
	
	return false;
}

function prepareForm(element, parameters, submit_form) {
	if (!Object.isHash(parameters)) {
		parameters = new Hash(parameters);
	}

	element = getParentForm(element);
	if (element == null) {
		return false;
	}

	parameters.each(function(pair) {
		element[pair.key].value = pair.value;
	});

	if (submit_form == true) {
		element.submit();
	}
}

function updateResult(element, url, result_id, add_parameters) {
	element = getParentForm(element);
	if (element == null) {
		return false;
	}

	var parameters = new Hash();

	if (add_parameters != null) {
		var add_parameters = new Hash(add_parameters);
		add_parameters.each(function(pair) {
			parameters.set(pair.key, pair.value);
		});
	}

	var depending_inputs = element.select('.update-result-field');

	depending_inputs.each(function(item) {
		parameters.set(item.name, item.value);
	});


	ajaxFunction(url, parameters, result_id);

	return false;
}

function submitDataDraft(tab, ideaid) {
	if (submitData(tab, ideaid, false)) {
		alert(getLangValue('enterIdea.php', 'leave_editing_mode'));
	}

	return false;
}

function addTag(tag) {
	insertAtCursor('enteridea-tags', ', ' + tag);

	var element = $('enteridea-tags');
	if (element == null) {
		return false;
	}

	var tags = element.value.split(',');

	var trimmed_tags = new Array();
	tags.each(function(item) {
		var trimmed_item = item.strip();
		if (trimmed_item != '') {
			trimmed_tags.push(item.strip());
		}
	});
	trimmed_tags = trimmed_tags.uniq();

	element.value = trimmed_tags.join(', ');
}

function addHiddenInputValue(src_input_element, target_input_name, sep) {
	if (sep == null) {
		sep = '-';
	}

	var target_element = jQuery('input[name="' + target_input_name + '"]').eq(0);

	var value_array = target_element.attr('value').split(sep);
	
	if (src_input_element.checked) {
		value_array.push(jQuery(src_input_element).attr('value'));

		value_array = value_array.uniq();

		target_element.attr('value', value_array.join(sep));
	}
}

function insertAtCursor(element, text) {
	var element = $(element);
	if (element == null) {
		return false;
	}

	if (document.selection) {
		element.focus();
		var sel = document.selection.createRange();
		sel.text = text;
	} else if (element.selectionStart || element.selectionStart == '0') {
		var startPos = element.selectionStart;
		var endPos = element.selectionEnd;
		element.value = element.value.substring(0, startPos)
		+ text
		+ element.value.substring(endPos, element.value.length);
	} else {
		element.value += text;
	}
}

function showErrorFields() {
	alert(getLangValue('enterIdea.php', 'error_fields'));
}

function showErrorCat() {
	alert(getLangValue('enterIdea.php', 'error_cat'));
}

function showErrorImage() {
	alert(getLangValue('enterIdea.php', 'error_image'));
}

function saveAddRelatedIdea(link, userid, ideaid, linked_idea_id) {
	storeLinkIdea(ideaid, linked_idea_id, function() {
		addRelatedIdea(link, userid, ideaid, linked_idea_id);

		submitForm('linkIdea-form');

		if (window.opener.jQuery('#related-ideas-' + ideaid)) {
			window.opener.ajaxFunction('ideaRelatedIdeas.php', {'idea_id': ideaid}, 'related-ideas-' + ideaid);
		}
	});
}

function saveRemoveRelatedIdea(link, userid, ideaid, linked_idea_id) {
	delLinkIdea(ideaid, linked_idea_id, function() {
		removeRelatedIdea(link, userid, ideaid, linked_idea_id);

		submitForm('linkIdea-form');

		if (window.opener.jQuery('#related-ideas-' + ideaid)) {
			window.opener.ajaxFunction('ideaRelatedIdeas.php', {'idea_id': ideaid}, 'related-ideas-' + ideaid);
		}
	});
}

function addRelatedIdea(link, userid, ideaid, linked_idea_id) {
	var related_idea_ids = jQuery('input[name="relatedideaids"]').eq(0).val().split(',');
	related_idea_ids.push(linked_idea_id);

	related_idea_ids = jQuery.unique(related_idea_ids);
	
	related_idea_ids.each(function(item) {
		if ((item == '') || (item == 0) || (item == undefined)) {
			delete related_idea_ids[item];
		}
	});
	
	jQuery('input[name="relatedideaids"]').eq(0).val(related_idea_ids.join(','));
}

function removeRelatedIdea(link, userid, ideaid, linked_idea_id) {
	var related_idea_ids = jQuery('input[name="relatedideaids"]').eq(0).val().split(',');

	var new_related_idea_ids = new Array();

	related_idea_ids.each(function(item) {
		if ((linked_idea_id != item) && (item != '') && (item != 0) && (item != undefined)) {
			new_related_idea_ids.push(item);
		}
	});

	jQuery('input[name="relatedideaids"]').eq(0).val(new_related_idea_ids.join(','));
}

function delCfi(id) {
	if (confirm(getLangValue('js', 'really_dell_cfi'))) {
		window.location = BASEURL + "admin/delCallForIdeas.php?id=" + id;
	}
}

function updateIdeaLang(id,lang) {
	storeIdeaLang(id,lang);
	alert(unescape("Language changed."));
}

function setStatus(idea,state,warn) {
	setState=true;
	if (warn==1) {
		setState=confirm(unescape("Status wirklich %E4ndern? Die Idee befindet sich in Bewertung!"));
	}
	if (setState) {
		window.location = BASEURL + "actions/updateState.php?id="+idea+"&state="+state;
	}
}

function checkForFitImage(string_to_test)
{
      testString = "image=/";
      testStringLength = testString.length;
      
      test = string_to_test.indexOf(testString);
      newString = "";
      
      if(test !== -1)
      {
            test = test + testStringLength;
            newString = string_to_test.slice(test);
            return newString;
      }
      else
      {
            return string_to_test;
      }
}

function getImageData(img_element) {
	img_element = $(img_element);

	var result_hash = new Hash();

	/*var old_source = img_element.readAttribute('src');
    var new_source = ;
    
    if(new_source !== false)
    {
          old_source = new_source;
    }*/
    
	result_hash.set('src', checkForFitImage(img_element.readAttribute('src')));
	
	//result_hash.set('src', img_element.readAttribute('src'));
	result_hash.set('width', img_element.readAttribute('width'));
	result_hash.set('height', img_element.readAttribute('height'));

	if (result_hash.get('height') == 0) {
		result_hash.set('ratio', 1);
	} else {
		result_hash.set('ratio', parseFloat(result_hash.get('width')/result_hash.get('height')));
	}

	return result_hash;
}
  
function focusImage(element, rand_str, width_focus, width_thumbnail) {
	var element = $(element);
	var img_element = element.firstDescendant();

	var detail_element = $('image-detail-' + rand_str);
	if (detail_element == null) {
		return false;
	}

	var pool_element = $('image-pool-' + rand_str);
	if (pool_element == null) {
		return false;
	}

	var pool_images = pool_element.select('a.attachment');
	pool_images.each(function(item) {
		item.onclick = function() {
			return false;
		};
	});
	
	var focus_element = $('image-focus-' + rand_str);
	if (focus_element == null) {
		return false;
	}

	var old_height = getCleanedHeight(focus_element);
	focus_element.style.height = old_height + 'px';
	focus_element.style.overflow = 'hidden';

	var busy_layer = setElementToBusy(focus_element);
	
	var focus_images = focus_element.select('img.attachment');
	var removed_focus_elements = new Array();
	focus_images.each(function(item) {
		var removed_focus_element = $(focus_element.removeChild(item));
		var img_data = getImageData(removed_focus_element);
		removed_focus_element.style.width = width_thumbnail + 'px';
		//alert(width_thumbnail + " / " + img_data.get('ratio'));
		removed_focus_element.style.height = Math.round(width_thumbnail / img_data.get('ratio')) + 'px';
		removed_focus_element.style.marginBottom = '10px';

		var a_element = new Element('a', { 'href': '#', 'class': 'attachment vmiddle' } );
		a_element.setStyle({ 'margin': '0px 10px 10px 0px' });
		a_element.onclick = function () {
			focusImage(this, rand_str, width_focus, width_thumbnail);
			return false;
		};
		a_element.appendChild(removed_focus_element);

		a_element.firstDescendant().hide();

		pool_element.appendChild(a_element);

		removed_focus_elements.push(a_element);
	});

	var tmp_duration = 0.75;
	var img_data = getImageData(img_element);
	
	new Effect.Shrink(img_element, {
		duration: tmp_duration,
		direction: 'top-left',
		afterFinish: function() {
			var removed_pool_element = $(pool_element.removeChild(element)).firstDescendant();
			var new_height = Math.round(width_focus / img_data.get('ratio'));

			removed_focus_elements.each(function(item) {
				new Effect.Grow(item.firstDescendant(), {
					duration: tmp_duration,
					direction: 'top-left'
				});
			});

			var pixels = old_height - new_height;

			new Effect.Morph(focus_element, {
				style: { height: new_height + 'px' },
				duration: tmp_duration,
				afterFinish: function() {
					removed_pool_element.style.width = width_focus + 'px';
					removed_pool_element.style.height = new_height + 'px';
					removed_pool_element.style.marginRight = '0px';
					removed_pool_element.style.marginBottom = '0px';
				
					focus_element.appendChild(img_element);
					removed_pool_element.show();

					if (img_data.get('width') > width_focus) {
						if (!detail_element.visible()) {
							new Effect.Appear(detail_element, {
								duration: tmp_duration,
								queue: {
									scope: 'image-detail-scope',
									position: 'end',
									limit: 1
								}
							});
						}
					} else {
						if (detail_element.visible()) {
							new Effect.Fade(detail_element, {
								duration: tmp_duration,
								queue: {
									scope: 'image-detail-scope',
									position: 'end',
									limit: 1
								}
							});
						}
					}
			
					focus_element.style.height = 'auto';
					focus_element.style.overflow = 'visible';
					setElementToIdle(focus_element);

					pool_images.each(function(item) {
						item.onclick = function () {
							focusImage(this, rand_str, width_focus, width_thumbnail);
							return false;
						};
					});
				}
			});

			if (busy_layer != null) {
				var busy_layer_height = getCleanedHeight(busy_layer) - pixels;
			
				new Effect.Morph(busy_layer, {
					style: { height: busy_layer_height + 'px' },
					duration: tmp_duration,
					afterFinish: function() {
						if (focus_element != null) {
							setElementToIdle(focus_element);
						}
					},
					afterUpdate: function() {
						adjustBusyLayer(busy_layer);
					}
				});
			}
		}
	});
}
	  
function setGo(ideaid) {
	document.getElementById("go").src="images/rating_items/go_item_active.png";
	document.getElementById("nogo").src="images/rating_items/nogo_item.png";
	submitCommunityEval(ideaid,1);
}

function setNoGo(ideaid) {
	document.getElementById("go").src="images/rating_items/go_item.png";
	document.getElementById("nogo").src="images/rating_items/nogo_item_active.png";
	submitCommunityEval(ideaid,0);
}
	  
function updateCommunityEval(val,ideaid,imgadd) {
	for (var i=1; i<=5; i++) {
		newImg = "";
		if (val >= i) {
			newImg = "_active"+imgadd;
		}
		document.getElementById("overall_img_"+i).src = "images/rating_items/quickvote_item" + newImg + ".png";
	}
	document.getElementById("overall_eval").value = val;
	submitCommunityEval(ideaid,val);
}

function updateCommunityEval2(val,ideaid,imgadd) {
	for (var i=1; i<=5; i++) {
		newImg = "";
		if (val >= i) {
			newImg = "_active"+imgadd;
		}
		document.getElementById("overall_img_"+i).src = "images/rating_items/evaluation_item" + newImg + ".png";
	}
	document.getElementById("overall_eval").value = val;
	submitCommunityEval(ideaid,val);
}

function updateCommunityEvalThumbsUp(element,ideaid,val) {
	var container = jQuery(element).closest('span.thumbsup');
	jQuery('span.thumbsup-yes', container).toggle('blind');
	jQuery('span.thumbsup-no', container).toggle('blind');

	submitCommunityEval(ideaid,val,'thumbsup');
}

function updateCommunityEvalThumbsUpDown(element,ideaid,val) {
	//var container = jQuery(element).closest('span.thumbsup');
	//jQuery('span.thumbsup-yes', container).toggle('blind');
	//jQuery('span.thumbsup-no', container).toggle('blind');
	if(val==1) {
		$('thumbsup-yes').src="images/rating_items/thumbsup/thumbsup_yes_active.png";
		$('thumbsup-no').src="images/rating_items/thumbsup/thumbsup_no.png";
	} else {
		$('thumbsup-yes').src="images/rating_items/thumbsup/thumbsup_yes.png";
		$('thumbsup-no').src="images/rating_items/thumbsup/thumbsup_no_active.png";
	}

	submitCommunityEval(ideaid,val,'thumbsupdown');
}

function updateCfi(idea,cfi) {
	window.location = BASEURL + "actions/updateIdeaCfi.php?idea=" + idea + "&cfi=" + cfi;
}

function delIdea(id, invoke_location) {
	if (id > 0) {
		if (confirm(getLangValue('enterIdea.php', 'del_confirm'))) {
			window.location = BASEURL + "actions/delIdea.php?id=" + id + "&loc=" + invoke_location;
		}
	} else {
		alert(getLangValue('enterIdea.php', 'del_impossible'));
	}

	return false;
}

function updateEval(crit,val,ideaid) {
	for (var i = 1; i<=num_of_evaluation_items; i++) {
		newImg = '';
		if (val >= i) {
			newImg = "_active";
		}
		$("eval" + crit + "_img_" + i).src = "images/rating_items/evaluation_item" + newImg + ".png";
	}

	$("eval_val"+crit).value = val;
	
	var parameters = new Hash();
	parameters.set('ideaid', ideaid);
	parameters.set('crit', crit);
	parameters.set('val', val);
	
	return ajaxFunction(BASEURL + 'actions/storeEval.php', parameters);
}

function toggleComment(element, id) {
	element = $(element);

	var li_element = $('comment-' + id);

	var ul_elements = li_element.select('ul.child-comments');

	ul_elements.each(function(item) {
		if (item.up('li') == li_element) {
			if (item.visible()) {
				item.hide();
				element.select('span.toggle-text').first().update(getLangValue('idea.php', 'show'));
			} else {
				item.show();
				element.select('span.toggle-text').first().update(getLangValue('idea.php', 'hide'));
			}
		}
	});
}

function delComment(id,parent,childIndex) {
	if (confirm(getLangValue('idea.php', 'js_del_comment'))) {
		delCommentStore(id);
		childStr="";
		if (parent>0) {
			$("comm_c"+parent+"_"+childIndex).style.display="none";
		} else {
			$("comm_"+id+"_0").style.display="none";
		}

	}
}

function delPick(idea,user) {
	if (confirm(getLangValue('js', 'really_del_pickup'))) {
		delPickIdea(idea,user);
		$("pick_"+idea+"_"+user).style.display="none";
	}
}

function showAllCrits(cnt) {
	for (var i=0; i<cnt; i++) {
		$("evalform_"+i).style.display="block";
		$("showallcrits").style.display="none";

	}
}

function startEval(idea) {
	if (confirm(getLangValue('js', 'really_start_eval'))) {
		setStatus(idea,3,0);
	}
}


function changeImage(path,imageId,side) {
	$("image_details_"+side).src=path;
	$("img_thumb_"+side+currentImage[side]).style.display="inline";
	$("img_thumb_"+side+imageId).style.display="none";
	currentImage[side]=imageId;
}

function showContentHistory(field_id) {
	new Effect.BlindDown('history-' + field_id);
	toggle('history-' + field_id + '-show');
	toggle('history-' + field_id + '-hide');
}

function hideContentHistory(field_id) {
	new Effect.BlindUp('history-' + field_id);
	toggle('history-' + field_id + '-show');
	toggle('history-' + field_id + '-hide');
}

function showAdditionalRelatedIdeas(element) {
	new Effect.BlindDown('related-ideas-hidden');
	toggle('related-ideas-hide');
	toggle(element);
}

function hideAdditionalRelatedIdeas(element) {
	new Effect.BlindUp('related-ideas-hidden');
	toggle('related-ideas-show');
	toggle(element);
}

function checkCB(input_element, class_name, num_of_allows, message) {
	var checked_inputs = 0;
	var input_elements = $$('input.' + class_name);

	input_elements.each(function(item) {
		if (item.checked) {
			checked_inputs++;
		}
	});

    if (checked_inputs > num_of_allows) {
    	input_element.checked = false;
    	if (message != null) {
    		alert(message);
    	}
    }
}

function handlePortfolioIdea(input_element, portfolio) {
	if (global_portfolio_ideas == null) {
		global_portfolio_ideas = new Hash();
	}

	if (global_portfolio_ideas.get(portfolio) == null) {
		global_portfolio_ideas.set(portfolio, new Array());
	}

	var old_array = global_portfolio_ideas.get(portfolio);

	if (input_element.checked) {
		var tmp_portfolio = global_portfolio_ideas.get(portfolio);
		tmp_portfolio.push(input_element.value);
		tmp_portfolio = tmp_portfolio.uniq();
		global_portfolio_ideas.set(portfolio, tmp_portfolio);					
	} else {
		var tmp_portfolio = global_portfolio_ideas.get(portfolio);
		tmp_portfolio = tmp_portfolio.without(input_element.value);
		global_portfolio_ideas.set(portfolio, tmp_portfolio);
	}

	var new_array = global_portfolio_ideas.get(portfolio);
	

	if (new_array.size() > 0) {
		showElement(portfolio + '-portfolio-buttons');
		showElement(portfolio + '-portfolio-idea-preview');
	}

	hidePortfolioIdeas(portfolio);


	var number_elements = $$('span.' + portfolio + '-portfolio-number');
	number_elements.each(function(item) {
		item.update(new_array.size());
	});

	
	saveUserSettings('portfolio_ideas', global_portfolio_ideas, true);
}

function resetPortfolioIdeas(portfolio) {
	global_portfolio_ideas.unset(portfolio);

	var number_elements = $$('span.' + portfolio + '-portfolio-number');
	number_elements.each(function(item) {
		item.update('0');
	});

	hideElement(portfolio + '-portfolio-buttons');
	hideElement(portfolio + '-portfolio-idea-preview');
	$(portfolio + '-portfolio-idea-list').update();

	saveUserSettings('portfolio_ideas', global_portfolio_ideas, true)

	var portfolio_idea_inputs = $$('.' + portfolio + '-portfolio-idea');
	portfolio_idea_inputs.each(function(portfolio_idea_input) {
		portfolio_idea_input.checked = false;
	});
}

function handleCategories(input_name, user_id) {
	var inputs = jQuery('input[name="' + input_name + '"]');

	var cat_ids = new Array();
	inputs.each(function(item) {
		if (jQuery(this).attr('checked')) {
			cat_ids.push(jQuery(this).val());
		}
	});

	saveUserSettings('categories', cat_ids, false);
}

function handleCFI(input_name, user_id) {
	var inputs = jQuery('input[name="' + input_name + '"]');

	var cfi_ids = new Array();
	inputs.each(function(item) {
		if (jQuery(this).attr('checked')) {
			cfi_ids.push(jQuery(this).val());
		}
	});

	saveUserSettings('cfi', cfi_ids, false);
}

function markPortfolioIdeas(portfolio) {
	debug('Marking portfolio ideas for: ' + portfolio);
	var portfolio_ideas = global_portfolio_ideas.get(portfolio);
	if (portfolio_ideas != null) {
		portfolio_ideas.each(function(item) {
			var portfolio_idea_inputs = $$('.' + portfolio + '-portfolio-idea-' + item);
			portfolio_idea_inputs.each(function(portfolio_idea_input) {
				portfolio_idea_input.checked = true;
			});
		});
	}	
}

function showPortfolioIdeas(portfolio) {
	var parameters = new Hash();
	parameters.set('idea_ids[]', global_portfolio_ideas.get(portfolio));

	ajaxFunction(BASEURL + 'showIdeas.php', parameters, portfolio + '-portfolio-idea-list', 'complete_showPortfolioIdeas', portfolio);
}

function showPortfolioIdeasByIDs(portfolio, idea_ids) {
	var parameters = new Hash();
	parameters.set('idea_ids[]', idea_ids);

	ajaxFunction(BASEURL + 'showIdeas.php', parameters, portfolio + '-portfolio-idea-list', 'complete_showPortfolioIdeas', portfolio);	
}

function hidePortfolioIdeas(portfolio) {
	var element = $(portfolio + '-portfolio-idea-list');
	new Effect.BlindUp(element, {
		afterFinish: function() {
			hideElement(portfolio + '-portfolio-ideas-hide');
			showElement(portfolio + '-portfolio-ideas-show');

			element.update('');
		}
	});
}

function complete_showPortfolioIdeas(portfolio) {
	new Effect.BlindDown(portfolio + '-portfolio-idea-list', {
		afterFinish: function() {
			hideElement(portfolio + '-portfolio-ideas-show');
			showElement(portfolio + '-portfolio-ideas-hide');
		}
	});
}

function compareVersions(class_name, idea_id, lang) {
	var checked_inputs = $$('input.' + class_name + ':checked');

    if (checked_inputs.size() != 2) {
    	alert(getLangValue('idea.php', 'chose_exact_2'));
    } else {
		window.open(BASEURL + "ideaVersionComparsion.php?version_1=" + checked_inputs[0].value + "&version_2=" + checked_inputs[1].value + "&idea=" + idea_id + "&lang=" + lang, "", "width=760,height=400,left=200,top=200,dependent=yes,scrollbars=yes");
	}
}

function restoreVersions(idea_id, lang) {
	window.open(BASEURL + "ideaVersionComparsion.php?idea=" + idea_id + "&lang=" + lang + "&restore=1", "", "width=760,height=400,left=200,top=200,dependent=yes,scrollbars=yes");
}

function updateCompareVersion(select_element, version_1, idea_id, lang) {
	window.location = BASEURL + "ideaVersionComparsion.php?version_1=" + version_1 + "&version_2=" + $F(select_element) + "&idea=" + idea_id + "&lang=" + lang + "&restore=1";
}

function loadVersion(version, idea_id, lang) {
	window.location = BASEURL + "ideaVersion.php?version=" + version + "&idea=" + idea_id + "&lang=" + lang;
}

function confirmRestoreVersion() {
	if (confirm(getLangValue('js', 'really_reset_idea'))) {
		return true;
	}

	return false;
}

function addEmailRecipient(id, username) {
	hideElement('no-user-selected');
	showSendButton();

	if ($('email-recipient-' + id) == null) {
		$('recipientList').innerHTML += '<p id="email-recipient-'+id+'" style="margin:0px;">'+username+'&nbsp;&nbsp;&nbsp;<a href="javascript:delRecipient('+id+',\'user\')"><img src="images/icons/del.png" alt="delete" /></a>';
	}
}

function addManualEmailRecipient() {
	hideElement('no-user-selected');

	showSendButton();

	var email_recipient = document.forms['addpresenter'].elements['manual_recipient'].value;
	var timestamp = new Date();
	timestamp = timestamp.getTime();
	$('recipientList').innerHTML += '<p id="manual-email-recipient-'+timestamp+'" style="margin:0px;"><span class="address">'+email_recipient+'</span>&nbsp;&nbsp;&nbsp;<img onclick="return delRecipient('+timestamp+',\'manual\')" class="link" src="images/icons/del.png" alt="delete" /></p>';

	document.forms['addpresenter'].elements['manual_recipient'].value = '';

	hideElement('add-manual-recipient-button');
}

function delRecipient(id,mode) {
	var prefix = 'email-recipient-';
	if (mode == 'manual') {
		prefix = 'manual-email-recipient-';
	}

	var parent_element = $(prefix+id).parentNode;
	parent_element.removeChild($(prefix+id));

	if (parent_element.getElementsByTagName('p').length == 0) {
		showElement('no-user-selected');
		hideSendButton();
	}
}

function sendIdeaEmails() {
	var recipients = $('recipientList').getElementsByTagName('p');
	var recipient_ids = new Array();
	var recipient_addresses = new Array();
	for (var i = 0; i < recipients.length; i++) {
		if (recipients[i].id.substr(0,16) == 'email-recipient-') {
			recipient_ids.push(recipients[i].id.substr(16));
		}
		if (recipients[i].id.substr(0,23) == 'manual-email-recipient-') {
			var spans = recipients[i].getElementsByTagName('span');
			recipient_addresses.push(spans[0].innerHTML);
		}
	}

	document.sendEmails.recipient_ids.value = recipient_ids.join('_');
	document.sendEmails.recipient_addresses.value = recipient_addresses.join('; ');
	document.sendEmails.submit();

	return false;
}

function checkManualEmailRecipient(element) {
	var display_element = $('add-manual-recipient-button');

	if (display_element != null) {
		if (element.value.indexOf('@') > 0) {
			showElement('add-manual-recipient-button');
		} else {
			hideElement('add-manual-recipient-button');
		}
	}

	return false;
}

function showSendButton() {
	showElement('send-emails-button');

	return false;
}

function hideSendButton() {
	hideElement('send-emails-button');

	return false;
}

function addPresenterStore(ideaid, userid) {
	window.opener.storePresenter(ideaid, userid);
	window.close();
}

function delPresenterStore(ideaid, userid) {
	if (confirm(getLangValue('js', 'really_del_initiator'))) {
		delPresenter(ideaid, userid);
	}
}

function addPresenterManualStore(ideaid, username,email,phone,dep) {
	window.opener.storeManualPresenter(ideaid, username, email, phone, dep);
	window.close();
}

function useImage(path,filename) {
	setIdeaImage(path,filename);
}

function addFileInputField(link_element, element_id) {
	var element = $(element_id);
	if (element != null) {
		var file_input_elements = element.select('input');
		if (file_input_elements.size() > 0) {
			var first_file_input = file_input_elements[0];

			var tmp_date = new Date();
			var another_file_input = first_file_input.cloneNode(false);
			another_file_input.name = 'file' + tmp_date.getTime();
			another_file_input.value = '';

			element.removeChild(link_element);
			element.appendChild(new Element('br'));
			element.appendChild(another_file_input);
			element.appendChild(link_element);
		}
	}
}

function delAtt(id, idea_id, comment_id) {
	window.location = BASEURL + "actions/delCommentAtt.php?attid=" + id + "&idea=" + idea_id + "&cid=" + comment_id;
}

function showImageDetail(rand_str) {
	var focus_element = $('image-focus-' + rand_str);
	if (focus_element == null) {
		return false;
	}

	var image_elements = focus_element.select('img');

	if (image_elements.size() > 0) {
		showImage(image_elements[0]);
	}

	return false;
}

function showImage(img_element) {
	var img_data = getImageData($(img_element));
	var img_window = window.open(BASEURL + "showAttachment.php?file=" + img_data.get('src'), "", "width=800,height=600,left=100,top=100,dependent=yes,scrollbars=yes,rezisable=yes");

	return false;
}

function changeChallenge(val) {
// hardcoded challenge
	if(val==4) {
		//$('challenge2').hide();
		//$('challenge1').show();
		$('cfi').value=4;
		//jQuery('#catarrow').removeClass('catright');
		//jQuery('#catarrow').addClass('catleft');
	} else {
		//$('challenge1').hide();
		//$('challenge2').show();
		$('cfi').value=8;
		//jQuery('#catarrow').removeClass('catleft');
		//jQuery('#catarrow').addClass('catright');
	}
}

function submitComment(target_id) {
	var parameters = new Hash();
	parameters.set('ideaid', target_id);
	parameters.set('newpb', $('newcom').value);
	parameters.set('storepb', 1);
	ajaxFunction(BASEURL + 'ideaDiscussion.php', parameters, 'idea-reload-content-comment');
}

function removeComment(id, target_id) {
	var parameters = new Hash();
	parameters.set('ideaid', target_id);
	parameters.set('id', id);
	parameters.set('removepb', 1);
	ajaxFunction(BASEURL + 'ideaDiscussion.php', parameters, 'idea-reload-content-comment');
}

function submitPb(target_id) {
	var parameters = new Hash();
	parameters.set('userid', target_id);
	parameters.set('newpb', $('newpb').value);
	parameters.set('storepb', 1);
	ajaxFunction(BASEURL + 'displayMemberDetailsLayer.php', parameters, 'member-details');
}

function submitPb2(target_id) {
	var parameters = new Hash();
	parameters.set('userid', target_id);
	parameters.set('newpb', $('newpb2').value);
	parameters.set('storepb', 1);
	parameters.set('xsrf_mess', $('xsrf_mess').value);
	ajaxFunction(BASEURL + 'displayPinboard.php', parameters, 'mycomments');
}

function removePb(id, target_id) {
	var parameters = new Hash();
	parameters.set('userid', target_id);
	parameters.set('id', id);
	parameters.set('removepb', 1);
	ajaxFunction(BASEURL + 'displayMemberDetailsLayer.php', parameters, 'member-details');
}

function removePb2(id, target_id) {
	var parameters = new Hash();
	parameters.set('userid', target_id);
	parameters.set('id', id);
	parameters.set('removepb', 1);
	parameters.set('xsrf_mess', $('xsrf_mess').value);
	ajaxFunction(BASEURL + 'displayPinboard.php', parameters, 'mycomments');
}

function checkDraft() {
	var text_errors = false;
	var data_elements = $$('textarea.submitdata, input.submitdata');
	data_elements.each(function(item) {
		parameters.set(item.name, item.value);
		if (item.hasClassName('mandatory') && (item.value.length == 0)) {
			text_errors = true;
		}
	});
	if(text_errors == false) {
		//submitData(tab, ideaid, false)
	}
	
	return true;
}

function updateDefaultImg(cfi) {
	var categories_inputs = $$('input[name="categories[]"]');
	var categories = new Array();
	categories_inputs.each(function(item) {
		if (item.checked) {
			categories.push(item.value);
		}
	});

	if(categories.length==0) {
		$('defaultimg').src='images/spacer.png';
	} else {
		$('defaultimg').src='images/default_images/noIdeaImg_'+cfi+'_'+categories[0]+'.png';
	}
}

function showVideo(vid) {
	//$('slideback').show();
	//$('slideshow_'+vid).show();
	//$('slideclose_'+vid).show();
	//alert('hallo: '+vid);
	jQuery('#slideshow_'+vid).dialog("open"); 
}

function hideVideo(vid) {
	$('slideback').hide();
	$('slideshow_'+vid).hide();
	$('slideclose_'+vid).hide();
}

