function updatefields(value,fields)
{
	aFields = fields.split(',');
	//0 => fieldname 1 => maxlength
	for(i=0;i<aFields.length;i+=2)
	{
		ret = value;
		if(ret == '')
		{
			ret = '&nbsp;';
		}
	
		if(ret.length > aFields[i+1])
		{
			ret = ret.substr(0,aFields[i+1]-3) + '...';
		}
		MMO(aFields[i]).innerHTML = clearCrap(ret);
	}
}

function copyToInput(id,val)
{
	if($(id).val() == '')
	{
		$(id).val(val);
	}
}

function clearCrap(value)
{
	var match = /<(?:.|\s)*?>/g;
	value = value.replace(match,"");
	if(value == '')
	{
		value = '&nbsp;';
	}
	return value;
}

function validate_password(pw)
{
	var iCount = 0;
	
	if(pw.match(/[A-Z]/)){iCount++;}
	if(pw.match(/[a-z]/)){iCount++;}
	if(pw.match(/[0-9]/)){iCount++;}
	if(pw.match(/[^0-9a-zA-Z]/)){iCount++;}
	if(pw.length >= 6){iCount++;}
	
	$('#securityBar').css('width',(iCount*20)+'%');		
}

function toggle_readonly(id)
{
	var id = id.replace(/[1-3]{1}$/,"");
	for(var i=1;i<=3;i++)
	{
		if($('#'+id+''+i).attr('readonly'))
		{
			$('#'+id+''+i).removeAttr('readonly');
		}
		else
		{
			$('#'+id+''+i).attr('readonly','readonly');
		}
	}
}
/**
* Pagelink
*/

$(document).ready(function(){
	$('#main-header-pagelink').click(function()
	{
		if(!$('#main-header-input').is(':visible'))
		{
			$('#main-header-infos').hide('slide',{direction: 'left'}, 500);
			$('#main-header-input').animate({borderWidth:'0px'},500);
			ajax_get_page_link();
		}
		else
		{
			$('#main-header-input').hide("slide",{direction:"left"},500);
			$('#main-header-infos').animate({borderWidth:'0px'},500);
			$('#main-header-infos').show("slide",{direction:"left"},500);
			$('#pagelink-input').val('');
		}
	});
});

function toClipboard(s)
{
	if( window.clipboardData && clipboardData.setData )
	{
		clipboardData.setData("Text", s);
	}
}

/**
* Date String (Mo, 10.12.2000) into date object
*/
update_enddate = function(date)
{
	var startdate = strToDate(date);
	var enddate = strToDate($('#enddate').val());
	var daynames = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
	
	if(enddate < startdate)
	{
		$('#enddate').val(date);
	}
	if($('#recurrence_sel').val())
	{
		recurrence($('#recurrence_sel').val());
	}
}
var endtime_updated = false;
update_endtime = function(time)
{
	if(time == null){endtime_updated=true;}
	if(endtime_updated)return;
	var endtime = 0; 
	time = parseInt(time);
	if(time > 45)
	{
		//update enddate and time
		endtime = time - 46;
		var startdate = strToDate(date);
		var enddate = strToDate($('#enddate').val());
		if(enddate < startdate)
		{
			update_enddate();
		}
	}
	else
	{
		endtime = time + 2;
	}
	
	$('#endtime').val(endtime);
}

function strToDate(strDate)
{
	var arrDate;
	if(strDate.match(/\ /))
	{
		arrDate = strDate.split(" ");
		strDate = arrDate[1];
	}
	arrDate = strDate.split(".");
	return new Date((arrDate[2]*1+2000),(arrDate[1]-1),arrDate[0],3,0,0);
}

/**
* Communication > Messages recipient search
* Set/Remove Timeout for ajax call while typing
*/

function cMsgSearch()
{
	this.searchString = null;
	this.timer = null;
	this.lastSearch = '';
}

var msgSearch = new cMsgSearch();

msgSearch.search = function()
{
	msgSearch.cancel();
	if(!msgSearch.searchString.match(/search[.]*/i))
	{
		msgSearch.lastSearch = msgSearch.searchString;
		ajax_search_recipient(msgSearch.searchString);
	}
};

msgSearch.start = function(searchString){
	xajax.config.waitCursor=false;
	msgSearch.searchString = searchString;
	msgSearch.cancel();
	msgSearch.timer = window.setTimeout("msgSearch.search()",400);
};

msgSearch.cancel = function(){
	if(msgSearch.timer !== null){
		window.clearTimeout(msgSearch.timer);
		msgSearch.timer = null;
	}
};

$('.remove_parent').live('click',function(){
	ajax_remove_recipient($(this).next().val());
	$(this).parent().remove();
	
})

var liveSearch = new cMsgSearch();
liveSearch.start = function(type,searchString){
	xajax.config.waitCursor=false;
	liveSearch.searchString = searchString;
	liveSearch.cancel();
	liveSearch.timer = window.setTimeout("liveSearch.search('"+type+"')",400);
};

liveSearch.search = function(type)
{
	liveSearch.cancel();
	
	liveSearch.lastSearch = msgSearch.searchString;
	ajax_live_search(type,liveSearch.searchString);
};

liveSearch.cancel = function(){
	if(liveSearch.timer !== null){
		window.clearTimeout(liveSearch.timer);
		liveSearch.timer = null;
	}
};

/**
* returns dom element
* tag,id,class,name,value,type (hidden)
*/

function dom_element(strTag,strID,strClass,strName,strValue,strType)
{
	var dom = document.createElement(strTag);
	if(strID && strID != 'undefined') dom.setAttribute('id',strID);
	if(strClass && strClass != 'undefined') dom.setAttribute('class',strClass);
	if(strTag == 'input')
	{
		dom.setAttribute('value',strValue);
		dom.setAttribute('type',strType);
		if(strName && strName != 'undefined') dom.setAttribute('name',strName);
	}
	else
	{
		if(strName && strName != 'undefined') dom.innerHTML = strName;
	}
	return dom;
}

/**
*
*Gantt Chart close on click
*
*/

$(document).bind('click',function(e){
	var $clicked=$(e.target); // get the element clicked
	if($clicked.parents().is('#overDiv') && !$clicked.is('#od-close'))
	{
	}
	else
	{
		$('#overDiv').html('');
	}
		
	if($('#quick-export-div').is(':visible') && !$clicked.parents().is('#quick-export-div') && !$clicked.is('#quick-export') && !$clicked.parents().is('#quick-export'))
	{
		hideQuickExport();
	}
		
	if(!$clicked.parents().is('#msg_search_result') && $('#messaging_autocomplete_suggestions').is(':visible') && !$clicked.is('#msg_search'))
	{
		$('#messaging_autocomplete_suggestions').hide();
		if(msgSearch.lastSearch != '')
		{
		ajax_search_recipient('',true);
		msgSearch.lastSearch = '';
		}
	}
	if(!$clicked.is('#msg_search'))
	{
		$('#msg_search').val('Search...');
	}
	if($clicked.is('#msg_search'))
	{
		$('#messaging_autocomplete_suggestions').show();
	}
	if(($clicked.is('#msg_recipients') || $clicked.parents().is('#msg_recipients')) && !$clicked.is('#msg_search') && !$clicked.is('span'))
	{
		$('#msg_search').focus();
		$('#msg_search').click();
	}
});

$(document).mousedown(function(e){
	var $clicked=$(e.target);
    // relevant for: show_sticky_ol
	if($clicked.parents().is('#ganttchart') || $clicked.parents().is('#middle-budget-content') || $clicked.parents().is('#imp-rep-cos') || $clicked.parents().is('#imp_con_bud') || $clicked.parents().is('#con-fin-directcosts'))
	{
	$gcposx = e.pageX;// - this.offsetLeft;
	$gcposy = e.pageY;
	}
});

/*
$(function() {
		$(".draggable").draggable();
	});
*/

/**
*
* EMDESK / MPM Login switch
* 
*/
/*
$(document).ready(
	function()
	{
		
	
		$("#mpm-login").click(function(){
			$("#emd-login").removeClass('emlogin-active');
			$("#emd-login").addClass('emlogin-inactive');
			$("#mpm-login").removeClass('emlogin-inactive');
			$("#mpm-login").addClass('emlogin-active');
			$("#emdlogin-state").val(1);
			
			})
		$("#emd-login").click(function(){
			$("#mpm-login").removeClass('emlogin-active');
			$("#mpm-login").addClass('emlogin-inactive');
			$("#emd-login").removeClass('emlogin-inactive');
			$("#emd-login").addClass('emlogin-active');
			$("#emdlogin-state").val(0);
			})

	}
);*/

/**
* Session timeout Warning
*/
/*
$(document).ready(
	function()
	{
		var date = new Date();
		var session_starttime = Math.floor(date.getTime()/1000);
		window.setTimeout("check_sessiontimeout("+session_starttime+")",60000);
	}
);
check_sessiontimeout = function(session_starttime,showed)
{
	var date = new Date();
	
	var time = Math.floor(date.getTime()/1000);
	var time_elapsed = time-session_starttime;
	
	if((time_elapsed >= 5) && !showed)
	{
		showed = true;
		$('.global-session-alert').animate({height:'148px', width: '150px', top:'-150px', left:'-150px'});
		$('#global_session_alert').html("Your session is already idle for "+Math.round(time_elapsed/60)+" minutes. Your action is required within the next "+Math.round((parseInt($('#session-timeout').val())-time_elapsed)/60)+" minutes before the session is closed.");
	}
	window.setTimeout("check_sessiontimeout("+session_starttime+","+showed+")",60000);
}
*/

/**
* Calendar Recurrence
*/

function recurrence(val)
{
	val = parseInt(val);
	if(val > 0)
	{
		$('#recurrence_interval').show();
	}
	var date,wd,day;
	
	date = strToDate($('#startdate').val());
	wd = date.getDay();
	day = date.getDate();
	switch(val)
	{
		//1=>'Daily',2=>'Weekly',3=>'Monthly',4=>'Yearly',5=>'Every Weekday',6=>'Bi-weekly')
		case 0:
			$('#recurrence_interval,#recurrence_tbl_week,#recurrence_tbl_month,#recurrence_tbl_year').hide();
		break;
		case 2:
		case 6:
			$('#recurrence_tbl_week').show();
			$('#recurrence_tbl_month,#recurrence_tbl_year').hide();
			$('#cal_create_wd_'+wd).attr('checked','checked');
		break;
		case 3:
			$('#recurrence_tbl_month').show();
			$('#recurrence_mdradio2').attr('checked','checked');
			$('#recurrence_mdwd').val(day);
			$('#recurrence_tbl_week,#recurrence_tbl_year').hide();
		break;
		case 4:
			$('#recurrence_tbl_year').show();
			$('#recurrence_tbl_month,#recurrence_tbl_week').hide();
		break;
		case 1:
		case 5:
			$('#recurrence_tbl_week,#recurrence_tbl_month,#recurrence_tbl_year').hide();
		break;
	}
}


/**
* Quick Export
*/

$(document).ready(function(){
	$('#quick-export')	
	.hover(
	function()
	{
		if(!$('#quick-export-div').is(':visible'))
		{
		$('#quick-export-img').css('margin-top','2px');
		}
	},
	function()
	{
		if(!$('#quick-export-div').is(':visible'))
		{
		$('#quick-export-img').css('margin-top','0px');
		}
	}
	)
	.click(
	function()
	{
		if($('#quick-export-div').is(':visible'))
		{
		$('#quick-export-div').fadeOut("fast");
		//$(this).removeClass('quick-export-on');
		$('#quick-export-img').attr('src','../images/buttons/arrow_quickexport_down.gif');
		$('#quick-export-img').css('margin-top','0px');
		}
		else
		{
		$('#quick-export-div').fadeIn("fast");
		//$(this).addClass('quick-export-on');
		$('#quick-export-img').attr('src','../images/buttons/arrow_quickexport_up.gif');
		$('#quick-export-img').css('margin-top','0px');
		}
			
	}
	)
	.keydown(function(event)
	{
	switch(event.keyCode)
	{
		case 27:
		hideQuickExport();
		break;
	}
	}
	
	);
	$('div.quick-export-item').hover(
	function()
	{
		$(this).addClass('quick-export-item-hover');
	},
	function()
	{
		$(this).removeClass('quick-export-item-hover');
	}
	);
});

hideQuickExport = function()
{
	$('#quick-export-div').fadeOut("fast");
	$('#quick-export-img').attr('src','../images/buttons/arrow_quickexport_down.gif');
	$('#quick-export-img').css('margin-top','0px');
}

/**
* toggles '#whatever' and '#whatever-img' image
*/
emtoggle = function(id,ajax)
{
	var src = $(id+'-img').attr('src').match(/delete/) ? 'add_7' : 'delete_5'; 
	$(id+'-img').attr('src','../images/buttons/'+src+'.gif');
	$.browser.msie ? $(id).toggle() : $(id).slideToggle();
	if(ajax)
	{
	$.ajax({
		async: true,
		type: 'post',
		data: ({
		divToggle: id,
		state: src == 'add_7' ? 0 : 1
		}),
		url: '/cms/?s=user_settings',
		success: function(data) {
		if(data)
		{
			document.location.href = '?p=145';
		}
		}
	});
	}
}

$(document).ready(function()
{
	if($('#myemdesk_message-wall').length > 0)
	{
		$("textarea#message-wall-text").autoResize();
	}
});

/*
$(function()
	{
	$('#messagewall-content').bind('click',
		function()
		{
			$("#message-wall-messages").jScrollPane({ scrollbarWidth:11, scrollbarMargin:0, arrowSize:0 });
		}
	);
	$('.openField').bind('click',
		function()
		{
			$("#message-wall-messages").jScrollPane({ scrollbarWidth:11, scrollbarMargin:0, arrowSize:0 });
		}
	);
});
*/


/**
* Datepicker
*/

$(function() {
	$('.datepicker').datepicker({
	yearRange: '-5:+10', 
	dateFormat: 'D dd.mm.y',
	firstDay: 1, 
	numberOfMonths: [1,2], 
	showAnim:'blind', 
	duration: 100, 
	stepMonths:1, 
	changeYear: true, 
	changeMonth: true
	});
	$('.datepicker2').datepicker({
	yearRange: '-5:+10', 
	dateFormat: 'dd.mm.y',
	firstDay: 1,
	numberOfMonths: [1,2], 
	showAnim:'blind', 
	duration: 100, 
	stepMonths:1, 
	changeYear: true, 
	changeMonth: true,
	showWeek: true
	});
});
activatedp = function(str)
{
	for(var i=0;i<activatedp.arguments.length;i++)
	{
	$(activatedp.arguments[i]).datepicker({
		yearRange: '-5:+10', 
		dateFormat: 'D dd.mm.y',
		firstDay: 1, 
		numberOfMonths: [1,2], 
		showAnim:'blind', 
		duration: 100, 
		stepMonths:2, 
		changeYear: true, 
		changeMonth: true
	});
	}
}
activatedp2 = function(str)
{
	for(var i=0;i<activatedp2.arguments.length;i++)
	{
	$(activatedp2.arguments[i]).datepicker({
		yearRange: '-5:+10', 
		dateFormat: 'dd.mm.y',
		firstDay: 1,
		numberOfMonths: [1,2], 
		showAnim:'blind', 
		duration: 100, 
		stepMonths:2, 
		changeYear: true, 
		changeMonth: true
	});
	}
}
activatedpinl = function(str)
{
	$('#dp_emdesk_calendar').datepicker2({
	yearRange: '-5:+10', 
	showOtherMonths: true, 
	dateFormat: 'dd.mm.y',
	firstDay: 1,
	numberOfMonths: [2,1], 
	stepMonths:1, 
	changeYear: true, 
	changeMonth: true,
	showWeek: true
	});
}
activatedpProject = function(id,project_dates)
{
	$(id).datepicker({
		yearRange: '-5:+10', 
		dateFormat: 'D dd.mm.y',
		firstDay: 1, 
		numberOfMonths: [1,2], 
		showAnim:'blind', 
		duration: 100, 
		stepMonths:2, 
		changeYear: true, 
		changeMonth: true,
		project_dates: project_dates
	});
}


/**
 *WP Project Supbproject lines
 *
 */
sp_swap = function()
{
	$('.sp_swap').mouseover(function(e)
	{
		$(e.target).children('.sp_swap_img').attr('src','../images/pics/subproject_line_aktiv.gif');
		$(e.target).addClass('sp_swap_hover');
	});
	$('.sp_swap').mouseout(function(e)
	{
		$(e.target).children('.sp_swap_img').attr('src','../images/pics/subproject_line_inaktiv.gif');
		$(e.target).removeClass('sp_swap_hover');
	});
	$('.sp_swap_img').mouseover(function(e)
	{
		$(e.target).attr('src','../images/pics/subproject_line_aktiv.gif');
		$(e.target).parent().addClass('sp_swap_hover');
	});
	$('.sp_swap_img').mouseout(function(e)
	{
		$(e.target).children('.sp_swap_img').attr('src','../images/pics/subproject_line_inaktiv.gif');
		$(e.target).parent().removeClass('sp_swap_hover');
	});
	
	$('.sp_swap').click(function(e)
	{
		ajax_add_subproject(this.id);
		$(this).unbind('mouseover mouseout click');
		$(this).removeClass('sp_swap_hover');
	});
	
}
$(sp_swap);


/**
 * Quick Links Selects
 */
$(document).ready(function(){
	$('.quickselect').disableSelection();
	$('#qs li').click(function(){
		$('#qs').hide();
		location.href = '?p='+this.id.replace(/^qs_/,'');
	});
	$('#ql li:not(.header)').click(function(){
	$('#ql2_cat').html($(this).html());
	if($('#ql2 .jScrollPaneContainer').length > 0)
	{
		$('#ql2_list').jScrollPaneRemove();
	}
	$.ajax({
		async: true,
		type: 'post',
		dataType: 'json',
		data: {
		cid: this.id.replace(/^ql_/,'')
		},
		url: '/cms/?p=329',
		success: function(data) {
			$('#ql2').css('height','auto');
			$('#ql2_list').html('').removeAttr('style');
			var i=0;
			$.each(data,function(k,aV){
				$('<li></li>').append($('<a></a>').attr({
				'href':aV[0],
				'target':'_blank',
				'title':aV[1]
				}).html(aV[1])).appendTo($('#ql2_list'));
				i++;
			});
					
			$('#ql').hide();
			$('#ql2').show();
			if(i > 13)
			{
				$('#ql2_list').css('height','300px');
			}
			$('#ql2_list').jScrollPane({
				scrollbarWidth:17,
				scrollbarMargin:0,
				arrowSize:0
			});
		}
	});
	});
	$('.quickselect,.quicksel_box li:not(.header, :has(ul))').live('mouseover',function(){
		$(this).addClass('hover');
	});
	$('.quickselect,.quicksel_box li').live('mouseout',function(){
		$(this).removeClass('hover');
	});
	$('.quickselect').click(function(){
	if($(this).next().is(':visible'))
	{
		$('.quicksel_box').hide();
		$(this).removeClass('clicked');
	}
	else
	{
		if($(this).next().is('#ql'))
		{
			$('#ql').css('right',3);
		}
		$('.quicksel_box').hide();
		$('.quickselect').removeClass('clicked');
		$(this).addClass('clicked').next().show();
	}
	});
	$(document).click(function(e){
	if(!$(e.target).is('.quickselect,.quicksel_box') && !$(e.target).parents().is('.quickselect,.quicksel_box'))
	{
		$('.quickselect').removeClass('clicked');
		$('.quicksel_box').hide();
	}
	});
});

$.fn.jScrollPaneRemove = function()
{
	$(this).each(function()
	{
	$this = $(this);
	var $c = $this.parent();
	if ($c.is('.jScrollPaneContainer')) {
		$c.after($this).remove();
	}
	});
}

/**
 * Drag/Drop
 */

$(function() {
	var startObj=null,endObj=null;
	var dropped = false;
	$(".draggable").draggable({
	handle: 'div.menu_container',
	cancel: '#pmenu,img',
	revert: 'invalid',
	opacity: 0.7,
	helper: 'clone',
	start: function(e){
		dropped = false;
		startObj = $(e.target);
	},
	stop: function(e){
		if(dropped)
		{
		//swap
		//insert helper
		startObj.before('<span id="emd_ins_start"></span>');
		endObj.before('<span id="emd_ins_end"></span>');
		//move objects
		startObj.insertBefore($('#emd_ins_end')).css({
			top:0,
			left:0
		});
		endObj.insertBefore($('#emd_ins_start')).css({
			top:0,
			left:0
		});
		//remove helper
		$('#emd_ins_start').remove();
		$('#emd_ins_end').remove();
		//save changes for user
				
		$.ajax({
			async: true,
			type: 'post',
			data: ({
			e1: startObj.attr('id'), 
			e2: endObj.attr('id')
			}),
			url: '/cms/?s=user_settings',
			success: function(data) {
			if(data)
			{
				document.location.href = '?p=145';
			}
			}
		});
		}
	}
	});
	$(".droppable").droppable({
	tolerance: 'pointer',
	accept: function(obj){
		if($(this).attr('id').split('_')[0] == obj.attr('id').split('_')[0])
		return true;
	},
	drop: function(e){
		endObj = $(e.target);
		dropped = true;
		endObj.removeClass('drop_over');
	},
	over: function(e){
		$(e.target).addClass('drop_over');
	},
	out: function(e){
		$(e.target).removeClass('drop_over');
	}
	});
	$(".draggable").disableSelection();
});


/**
 * jQuery custom selectboxes
 * 
 * Copyright (c) 2008 Krzysztof Suszynski (suszynski.org)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @version 0.6.1
 * @category visual
 * @package jquery
 * @subpakage ui.selectbox
 * @author Krzysztof Suszynski <k.suszynski@wit.edu.pl>
**/
jQuery.fn.selectbox = function(options){
	/* Default settings */
	var settings = {
	className: 'jquery-selectbox',
	animationSpeed: 0,
	listboxMaxSize: 15,
	replaceInvisible: false
	};
	var commonClass = 'jquery-custom-selectboxes-replaced';
	var listOpen = false;
	var showList = function(listObj) {
	var selectbox = listObj.parents('.' + settings.className + '');
	listObj.slideDown(settings.animationSpeed, function(){
		listOpen = true;
		if(jQuery.browser.msie)jQuery('.'+settings.className+'-list').css('overflow','');
	});
	selectbox.addClass('selecthover');
	jQuery(document).bind('click', onBlurList);
	return listObj;
	}
	var hideList = function(listObj) {
	var selectbox = listObj.parents('.' + settings.className + '');
	listObj.slideUp(settings.animationSpeed, function(){
		listOpen = false;
		jQuery(this).parents('.' + settings.className + '').removeClass('selecthover');
	});
	jQuery(document).unbind('click', onBlurList);
	return listObj;
	}
	var onBlurList = function(e) {
	var trgt = e.target;
	var currentListElements = jQuery('.' + settings.className + '-list:visible').parent().find('*').andSelf();
	if(jQuery.inArray(trgt, currentListElements)<0 && listOpen) {
		hideList( jQuery('.' + commonClass + '-list') );
	}
	return false;
	}
	
	/* Processing settings */
	settings = jQuery.extend(settings, options || {});
	/* Wrapping all passed elements */
	return this.each(function() {
	var _this = jQuery(this);
	if(_this.filter(':visible').length == 0 && !settings.replaceInvisible)
		return;
	var replacement = jQuery(
		'<div class="' + settings.className + ' ' + commonClass + '">' +
		'<div class="' + settings.className + '-moreButton" />' +
		'<div class="' + settings.className + '-list ' + commonClass + '-list" />' +
		'<span class="' + settings.className + '-currentItem" />' +
		'</div>'
		);
	jQuery('option', _this).each(function(k,v){
		var v = jQuery(v);
		var listElement =  jQuery('<span class="' + settings.className + '-item value-'+v.val()+' item-'+k+'">' + v.text() + '</span>');	
		listElement.click(function(){
		var thisListElement = jQuery(this);
		var thisReplacment = thisListElement.parents('.'+settings.className);
		var thisIndex = thisListElement[0].className.split(' ');
		for( k1 in thisIndex ) {
			if(/^item-[0-9]+$/.test(thisIndex[k1])) {
			thisIndex = parseInt(thisIndex[k1].replace('item-',''), 10);
			break;
			}
		};
		var thisValue = thisListElement[0].className.split(' ');
		for( k1 in thisValue ) {
			if(/^value-.+$/.test(thisValue[k1])) {
			thisValue = thisValue[k1].replace('value-','');
			break;
			}
		};
		thisReplacment
		.find('.' + settings.className + '-currentItem')
		.text(thisListElement.text());
		thisReplacment
		.find('select')
		.val(thisValue)
		.triggerHandler('change');
		var thisSublist = thisReplacment.find('.' + settings.className + '-list');
		if(thisSublist.filter(":visible").length > 0) {
			hideList( thisSublist );
		}else{
			showList( thisSublist );
		}
		}).bind('mouseenter',function(){
		jQuery(this).addClass('listelementhover');
		}).bind('mouseleave',function(){
		jQuery(this).removeClass('listelementhover');
		});
		jQuery('.' + settings.className + '-list', replacement).append(listElement);
		if(v.filter(':selected').length > 0) {
		jQuery('.'+settings.className + '-currentItem', replacement).text(v.text());
		}
	});
	replacement.find('.' + settings.className + '-moreButton').click(function(){
		var thisMoreButton = jQuery(this);
		var otherLists = jQuery('.' + settings.className + '-list')
		.not(thisMoreButton.siblings('.' + settings.className + '-list'));
		hideList( otherLists );
		var thisList = thisMoreButton.siblings('.' + settings.className + '-list');
		if(thisList.filter(":visible").length > 0) {
		hideList( thisList );
		}else{
		showList( thisList );
		}
	}).bind('mouseenter',function(){
		jQuery(this).addClass('morebuttonhover');
	}).bind('mouseleave',function(){
		jQuery(this).removeClass('morebuttonhover');
	});
	_this.hide().replaceWith(replacement).appendTo(replacement);
	var thisListBox = replacement.find('.' + settings.className + '-list');
	var thisListBoxSize = thisListBox.find('.' + settings.className + '-item').length;
	if(thisListBoxSize > settings.listboxMaxSize)
		thisListBoxSize = settings.listboxMaxSize;
	if(thisListBoxSize == 0)
		thisListBoxSize = 1;	
	var thisListBoxWidth = Math.round(_this.width()+2);
	replacement.css('width', thisListBoxWidth + 'px');
	thisListBox.css({
		width: Math.round(thisListBoxWidth+12) + 'px',
		height: thisListBoxSize + 'em'
	});
	});
}
jQuery.fn.unselectbox = function(){
	var commonClass = 'jquery-custom-selectboxes-replaced';
	return this.each(function() {
	var selectToRemove = jQuery(this).filter('.' + commonClass);
	selectToRemove.replaceWith(selectToRemove.find('select').show());		
	});
}


/* infobar */
function infobar_show(strContent, strClass, intDuration, strIcon, bCloseButton)
{	
	if (strIcon)
	{
		$("#emdesk-infobar_icon img").attr('src', strIcon);
		$("#emdesk-infobar_icon").show();
	}
	else
	{
		$("#emdesk-infobar_icon").hide();
		strContent = "&nbsp;&nbsp;&nbsp;" + strContent;
	}
	
	if (bCloseButton)	
    {
		$("#emdesk-infobar_close").show();
    }		
	else
	{	
		$("#emdesk-infobar_close").hide();
		window.setTimeout("infobar_hide()", intDuration);
	}
    
    $("#emdesk-infobar").attr("class", strClass);	
	$("#emdesk-infobar_content").html(strContent);	
	$("#emdesk-infobar_wrap").fadeIn("fast");
}
function infobar_hide()
{
	$("#emdesk-infobar_wrap").fadeOut("slow");
}


/* for imp rep cos import */
function refreshRowCounter()
{
    $("span#validRow_counter").text( $("tr.validImportRow").size() + " data sets" );
    $("span#invalidRow_counter").text( $("tr.invalidImportRow").size() + " data sets" );
}
function getCostDataRow(k)
{
	var arrOutput = new Array();
    if ( $("#validRow_" + k + "_remaining_direct").attr("checked") ) {
        arrOutput.push("1");
	}
    else
    {
        arrOutput.push("0");
    }
	arrOutput.push($("#validRow_" + k + "_description").val());
	arrOutput.push($("#validRow_" + k + "_work_package").val());
	arrOutput.push($("#validRow_" + k + "_contractor_acronym").val());
	arrOutput.push($("#validRow_" + k + "_cost_category").val());
	arrOutput.push($("#validRow_" + k + "_amount1").val() + "." + $("#validRow_" + k + "_amount2").val());
	arrOutput.push($("#validRow_" + k + "_date").val());
	return arrOutput.join("-----");
}
function getValidCostDataRows()
{    
	var arrOutput_rows = new Array();
    
    $("tr.validImportRow").each(function () {
        var arrRow = new Array();
        // remaining_direct,description,work_package,contractor_acronym,cost_category,amount1,amount2,date
        if ($(this).find('input[id*="remaining_direct"]').attr("checked"))
        {
            arrRow.push("1");
        }
        else
        {
            arrRow.push("0");
        }        
        arrRow.push($(this).find('textarea[id*="description"]').val());
        arrRow.push($(this).find('select[id*="work_package"]').val());
        arrRow.push($(this).find('select[id*="contractor_acronym"]').val());
        arrRow.push($(this).find('select[id*="cost_category"]').val());
        arrRow.push($(this).find('input[id*="amount1"]').val() + "." + $(this).find('input[id*="amount2"]').val());
        arrRow.push($(this).find('input[id*="date"]').val());
        
        arrOutput_rows.push(arrRow.join("-----"));
    });
    //alert(arrOutput_rows.join("+++++"));
	return Base64.encode( arrOutput_rows.join("+++++") );
}
function toggleAllRDC(intSenderId, validRows)
{
    if ( $("#"+intSenderId).attr('checked') )
    {
        if ( validRows )
        {
            $("input.rdc_valid").attr('checked','checked');
        }
        else
        {
            $("input.rdc_invalid").attr('checked','checked');
        }
    }
    else
    {
        if ( validRows )
        {
            $("input.rdc_valid").attr('checked','');
        }
        else
        {
            $("input.rdc_invalid").attr('checked','');
        }
    }
}
function addTableRow( tableId, row )
{   // god dammit workaround for IE to add rows to a table via xajax
    $("table#" + tableId + " > tbody").append(row);
}


isImageLoaded = function(img)
{
	if(!img.complete)
	{
		return false;
	}
	if(typeof img.naturalWidth != "undefined" && img.naturalWidth == 0)
	{
		return false;
	}

	return true;
};

il_count = 10;
il_wait = 100;
il_loaded = false;

waitForImage = function(img)
{	
	if(isImageLoaded(img))
	{
		//reset globals
		il_count = 10;il_wait = 100;il_loaded = false;
		il_loaded = true;
	}
	il_count--;
	if(!il_loaded && il_count > 0)
	{
		window.setTimeout('waitForImage('+img+')',il_wait);
	}
};

//center Element (on Visible Screen / parent element)
(function($) {
	$.fn.center = function(parent) 
	{
		var _self = this;
		var complete = true;
		//preload images
		$(this).find('img').each(function(k,v){
			if('undefined' == typeof $(this).attr('ttl'))
			{
				$(this).attr('ttl',10);
			}
			
			if(!v.complete && $(this).attr('ttl') > 0)
			{
				$(this).attr('ttl',($(this).attr('ttl')-1));
				setTimeout(function(){
					$(_self).center(parent);
				},100);
				
				return false;
			}
			if(typeof v.naturalWidth != "undefined" && v.naturalWidth <= 1)
			{
				$(this).attr('ttl',($(this).attr('ttl')-1));
				setTimeout(function(){
					$(_self).center(parent);
				},100);
				return false;
			}
		});
		
		$(this).find('img').each(function(k,v){
			if(!v.complete && $(this).attr('ttl') > 0)
			{
				complete = false;
			}
		});
		if(complete)
		{
			var iPos = 0, iLeft=0;
			if(parent)
			{
				iLeft = ($(parent).width()/2 - $(this).width() / 2);
				iTop = ($(parent).height()/2 - $(this).height() / 2);
			}
			else
			{
				iLeft = ($(window).width()/2 - $(this).width() / 2); 
				iTop = ($(window).height()/2 - $(this).height() / 2) + $(window).scrollTop();
			}
			
			if(iLeft < 10)
			{
				iLeft = 10;
			}
			
			if(($(this).height()+iTop) > document.body.scrollHeight)
			{
				iTop = document.body.scrollHeight - ($(this).height()+10);
			}
			
			if(iTop < 10)
			{
				iTop = 10;
			}
			
			$(this).css({
				'left': iLeft+'px',
				'top': iTop+'px'
			});
		}
	};
})(jQuery);

var tinyMCEautosave = {
	openEditors: [],
	interval: 5, //Minutes
	
	addEditor: function(id)
	{
		var varSecs = Math.round(Math.random()*100) * 1000;
		window.clearTimeout(tinyMCEautosave.openEditors[id]);
		tinyMCEautosave.openEditors[id] = window.setTimeout("tinyMCEautosave.save('"+id+"')",((tinyMCEautosave.interval*1000)*60 + varSecs));
	},
	removeEditor: function(id)
	{
		if(tinyMCEautosave.openEditors[id])
		{
			window.clearTimeout(tinyMCEautosave.openEditors[id]);
			tinyMCEautosave.openEditors[id] = null;
		}
	},
	save: function(id)
	{
		ed = tinyMCE.get(id);
		
		//only save if anything has changed in the last interval
		if('undefined' == typeof ed.lastchange && !ed.getParam('readonly') || (new Date().getTime() / 1000) - ed.lastchange > (tinyMCEautosave.interval * 60))
		{
			tinyMCEautosave.addEditor(id);
			return;
		}
		//check if editor is still open and autosave function is defined
		if('undefined' == typeof ed.save() || typeof ed.getParam('autosave_function') == 'undefined' || (id == 'mce_fullscreen' && typeof ed.getParam('autosave_function_fs') == 'undefined'))
		{
			tinyMCEautosave.removeEditor(id);
			return;
		}
		tinyMCEautosave.addEditor(id);
		if(id == 'mce_fullscreen')
		{
			tinyMCE.saveContentBack();
			eval(ed.getParam('autosave_function_fs'));
		}
		else
		{
			eval(ed.getParam('autosave_function'));
		}
	}
};

var tinyOverlayTimeout = null;
var tableHasFocus = false;
function initTinyFunctions(id)
{
	var iframe,content,contentWindow,top=0,left=0;
	if('undefined' == typeof id){id = null;}
	
	$('#tinyImgOverlay div div').mouseover(function(){
		$(this).css('border','1px solid #777777');
	}).mouseout(function(){
		$(this).css('border','1px solid #B2B2B2');
	});
	
	$('#tinyTblOverlay div div').mouseover(function(){
		$(this).css('border','1px solid #777777');
	}).mouseout(function(){
		$(this).css('border','1px solid #B2B2B2');
	});
	
	for(var i=0; i<$('iframe').length;i++)
	{
		iframe = $('iframe')[i];
		
		if((id && id+'_ifr' != iframe.id) || !$($('iframe')[i]).parent().hasClass('mceIframeContainer'))
		{
			continue;
		}

		contentWindow = ('contentDocument' in iframe) ? iframe.contentDocument : iframe.contentWindow.document;
		content = ('contentDocument' in iframe) ? contentWindow.body : contentWindow.documentElement;
		
		$(iframe.contentWindow).unbind().scroll(function(){
			hideTinyOverlay();
		});
		
		$(content).click(function(e){
			if(!$(e.target).hasClass('mceContentTable') && !$(e.target).parents().hasClass('mceContentTable'))
			{
				tableHasFocus = false;
				hideTinyOverlay();
			}
		});
		
		//Add image overlay
		
		$(content).find('img:not([src*=footnote.php],[src*=comment.php])').unbind().mouseover(function(e){
			if(!$('#overlayImageCaptionInput').is(':visible'))
			//if(!$('#tinyImgOverlay').is(':visible'))
			{
				var iframe = $('#mce_fullscreen_ifr').length > 0 ? $('#mce_fullscreen_ifr')[0] : document.getElementById($(this).parents('body')[0].id+'_ifr');
				var isEmdeskImage = this.src.match(/cms\/getfile/);
				var img = $(this);
				var contentWindow = ('contentDocument' in iframe) ? iframe.contentDocument : iframe.contentWindow.document;
				var content = ('contentDocument' in iframe) ? contentWindow.body : contentWindow.documentElement;
				
				var iScroll = $.browser.msie ? 0 : $(window).scrollTop();
				var scrollDiff = iScroll > 0 ? (iScroll - contentWindow.body.scrollTop) : 0;
				
				top = ($(iframe).offset().top + img.offset().top - contentWindow.body.scrollTop - scrollDiff);
				left = ($(iframe).offset().left + img.offset().left - contentWindow.body.scrollLeft);
				
				if(img.offset().top < contentWindow.body.scrollTop + scrollDiff)
				{
					top += contentWindow.body.scrollTop + scrollDiff - img.offset().top + 5;
				}
				if(img.offset().left < contentWindow.body.scrollLeft)
				{
					left += (contentWindow.body.scrollLeft - img.offset().left);
				}
				
				$('#overlayImageCaption').html(img.attr('alt'));
				$('#overlayImageCaptionEdit').parent().unbind().click(function(){
					if(tinyOverlayTimeout != null) window.clearTimeout(tinyOverlayTimeout);
					$('#overlayImageCaption').hide();
					$('#overlayImageCaptionInput').show().focus();
					if($('#overlayImageCaptionInput').val() == 'Please enter caption...')
					{
						$('#overlayImageCaptionInput').val('');
					}
				});
				$('#overlayImageCaptionInput').unbind().val(img.attr('alt')).css('width',((img.width() >= 200 ? (img.width() > 550 ? 550 : img.width()) : 200)-30)+'px').change(function(e){
					e.preventDefault();
					img.attr('alt',clearCrap(this.value).replace(/&nbsp;/,''));
					$('#overlayImageCaption').html(clearCrap(this.value));
					$('#overlayImageCaption').show();
					$('#overlayImageCaptionInput').hide();
					tinyMCE.activeEditor.onChange.dispatch(tinyMCE.activeEditor);
				}).keydown(function(e){
					switch(e.keyCode)
					{
						case 27:
							$('#overlayImageCaptionInput').hide();
							$('#overlayImageCaption').show();
						break;
						case 13:
							$('#overlayImageCaptionInput').trigger('change');
						break;
					}
				});
				
				$('#tinyImgOverlay').css({top:top+'px',left:(img.width() < 200 ? (left+30) : left)+'px',width:(img.width() >= 210 ? (img.width() < 550 ? img.width() : 550) : 210)+'px'}).show();
				
				if(isEmdeskImage)
				{
					$('#tinyImgOverlay #overlayImageEdit').unbind().click(function(){
						hideTinyOverlay();
						tinyMCE.activeEditor.selection.select(img[0]);
						tinyMCE.activeEditor.execCommand('mceImage');
						//emdesk.mediaManager.init();
						//emdesk.mediaManager.imageInfo(img[0].src.replace(/^.*\?/,''));
					}).parent().show();
				}
				else
				{
					$('#tinyImgOverlay #overlayImageEdit').unbind().parent().hide();
				}
				
				$('#tinyImgOverlay #overlayImageCopy').unbind().click(function(){
					emdesk.clipBoard['tinyImageCopy'] = img.clone();
				});
				$('#tinyImgOverlay #overlayImageCut').unbind().click(function(){
					hideTinyOverlay();
					emdesk.clipBoard['tinyImageCopy'] = img.clone();
					img.remove();
				});
				$('#tinyImgOverlay #overlayImageDelete').unbind().click(function(){
					img.remove();
					hideTinyOverlay();
					tinyMCE.get(iframe.id.replace(/_ifr/,'')).undoManager.add();
				});
				$('#tinyImgOverlay #overlayImageAlignLeft').unbind().click(function(){
					hideTinyOverlay();
					img.css({'float':''}).parents('p').first().css({'text-align':'left'});
				});
				$('#tinyImgOverlay #overlayImageAlignCenter').unbind().click(function(){
					hideTinyOverlay();
					img.css({'float':''}).parents('p').first().css({'text-align':'center'});
				});
				$('#tinyImgOverlay #overlayImageAlignRight').unbind().click(function(){
					hideTinyOverlay();
					img.css({'float':''}).parents('p').first().css({'text-align':'right'});
				});
				if(tinyOverlayTimeout != null) window.clearTimeout(tinyOverlayTimeout);
				tinyOverlayTimeout = window.setTimeout(function(){
					$('#tinyImgOverlay').hide().children().unbind();
					$('#overlayImageCaption').show();
					$('#overlayImageCaptionInput').hide();
					tinyOverlayTimeout = null;
					
				},5000);
			}
		}).bind('click dblclick',function(e){
			if(tinyOverlayTimeout != null) window.clearTimeout(tinyOverlayTimeout);
			hideTinyOverlay();
			$(this).trigger('mouseover');
			
		});
		
		
		//Add table overlay
		$(content).find('table').unbind().addClass('mceContentTable').click(function(){
			if(!$(this).hasClass('mceContentTableActive'))
			{
				tableHasFocus = false;
				hideTinyOverlay();
				$(this).addClass('mceContentTableActive');
			}
			if(!$('#tinyTblOverlay').is(':visible'))
			{
				var tbl = $(this);
				var iframe = $('#mce_fullscreen_ifr').length > 0 ? $('#mce_fullscreen_ifr')[0] : document.getElementById($(this).parents('body')[0].id+'_ifr');
				var contentWindow = ('contentDocument' in iframe) ? iframe.contentDocument : iframe.contentWindow.document;
				var content = ('contentDocument' in iframe) ? contentWindow.body : contentWindow.documentElement;
								
				top = ($(iframe).offset().top + this.offsetTop - contentWindow.body.scrollTop - 35);
				left = ($(iframe).offset().left + $(this).offset().left - contentWindow.body.scrollLeft + tbl.width() - 90);
				
				if(this.offsetTop < contentWindow.body.scrollTop)
				{
					top += (contentWindow.body.scrollTop - this.offsetTop + 5);
				}
				if($(this).offset().left < contentWindow.body.scrollLeft)
				{
					left += (contentWindow.body.scrollLeft - $(this).offset().left);
				}
				
				$('#tinyTblOverlay').css({top:top+'px',left:left+'px'}).show();
				tableHasFocus = true;
				
				$('#tinyTblOverlay #overlayTblEdit').parent().unbind().click(function(){
					tinyMCE.activeEditor.execCommand('mceInsertTable');
				});
				$('#tinyTblOverlay #overlayTblCellEdit').parent().unbind().click(function(){
					tinyMCE.activeEditor.execCommand('mceTableCellProps');
				});
				$('#tinyTblOverlay #overlayTblDelete').parent().unbind().click(function(){
					tinyMCE.activeEditor.execCommand('mceTableDelete');
					hideTinyOverlay();
				});
			}
		});
	}
}

function hideTinyOverlay()
{
	var iframe,contentWindow,content;
	$('#tinyTblOverlay').hide().children().unbind();
	$('#overlayImageCaptionInput').hide();
	$('#overlayImageCaption').show();
	
	for(var i=0; i<$('iframe').length;i++)
	{
		iframe = $('iframe')[i];
		contentWindow = ('contentDocument' in iframe) ? iframe.contentDocument : iframe.contentWindow.document;
		content = ('contentDocument' in iframe) ? contentWindow.body : contentWindow.documentElement;
		
		$(content).find('.mceContentTableActive').removeClass('mceContentTableActive');
	}
			
	$('#tinyImgOverlay').hide().children().unbind();
	if(tinyOverlayTimeout != null) window.clearTimeout(tinyOverlayTimeout);
}

function adjustInsertedImage(ed,id)
{
	hideTinyOverlay();
	iframe = $('#'+ed+'_ifr')[0];
	if(iframe)
	{
		var contentWindow = ('contentDocument' in iframe) ? iframe.contentDocument : iframe.contentWindow.document;
		var content = ('contentDocument' in iframe) ? contentWindow.body : contentWindow.documentElement;
		var c = '\\?'+id
		
		$(content).find('img').each(function(){
			if(this.src.match(c))
			{
				img = this;
				loadImage(img,function(){
					if($(img).width() > 760)
					{
						$(img).width(760);
					}
				});
			}
		});
	}
}

function loadImage(img,callback,ttl)
{
	if('undefined' == typeof img.ttl)
	{
		img.ttl = ttl || 100;//default 10s
	}
	
	if(img.ttl <= 0)
	{
		callback();
	}
	
	if(!img.complete && img.ttl > 0)
	{
		img.ttl = (img.ttl-1);
		window.setTimeout(function(){
			loadImage(img,callback);
		},100);
		return false;
	}
	if(typeof img.naturalWidth != "undefined" && img.naturalWidth <= 1)
	{
		img.ttl,(img.ttl-1);
		window.setTimeout(function(){
			loadImage(img,callback);
		},100);
		return false;
	}
	callback();
}

